id
stringlengths 7
14
| text
stringlengths 1
37.2k
|
|---|---|
190267909_31
|
@Override
public int partition(Object messageKey, List<PartitionInfo> partitions) {
if (localPartitions == null || isTimeToRefresh()) {
checkAndAssignLocalPartitions(partitions);
// set next refresh time
updateNextRefreshTime();
}
// we supply on local partitions to this base partitioner
return localPartitions.get(Math.abs(random.nextInt() % localPartitions.size())).partition();
}
|
190303335_18
|
public String getKey() {
return key;
}
|
190335075_411
|
public AbstractInsnNode[] toArray() {
int currentInsnIndex = 0;
AbstractInsnNode currentInsn = firstInsn;
AbstractInsnNode[] insnNodeArray = new AbstractInsnNode[size];
while (currentInsn != null) {
insnNodeArray[currentInsnIndex] = currentInsn;
currentInsn.index = currentInsnIndex++;
currentInsn = currentInsn.nextInsn;
}
return insnNodeArray;
}
|
190419065_18
|
public static String appendPathOntoUrl(Object urlString, Object... pathSection) {
String[] args = new String[pathSection.length];
for (int i = 0; i < pathSection.length; ++i) {
requireNonNull(pathSection[i]);
args[i] = pathSection[i].toString();
}
return appendPathOntoUrl(urlString.toString(), args);
}
|
190664284_131
|
@Override
public int getNumRunningWorkers() {
if(logger.isDebugEnabled()) { logger.debug("In getNumRunningWorkers"); }
int cnt = jobToWorkerInfoMap.values().stream()
.map(workerList -> workerList.stream()
.filter(wm -> WorkerState.isRunningState(wm.getState()))
.collect(Collectors.toList())
.size()
)
.reduce(0,(a, b) -> a + b);
if(logger.isDebugEnabled()) { logger.debug("Returning {} from getNumRunningWorkers", cnt); }
return cnt;
}
|
190686426_1
|
public int add(int n1,int n2) {
return n1+n2;
}
|
190690143_17
|
public JsApiCache buildFrom(Map<String, Object> registeredApis) {
JsApiCache.Builder builder = new JsApiCache.Builder();
for(String apiBaseName : registeredApis.keySet()) {
appendObject(builder, apiBaseName, registeredApis.get(apiBaseName));
}
return builder.build();
}
|
190718318_3
|
public void addProduct(String name, int price) throws WarehouseException {
if (price < 0) {
throw new IllegalArgumentException("The product's price cannot be negative.");
}
Product product = new Product(name, price);
productDao.addProduct(product);
}
|
190783541_11
|
@Override
public void startUploading(IDicomWebClient webClient, BackupState backupState) throws IBackupUploader.BackupException {
scheduleUploadWithDelay(webClient, backupState);
}
|
191232069_5
|
@Override
public PerfIssue verifyPerfIssue(ExpectMaxHeapAllocation annotation, Allocation measuredAllocation) {
Allocation maxExpectedAllocation = new Allocation(annotation.value(), annotation.unit());
if(maxExpectedAllocation.isLessThan(measuredAllocation)) {
String assertionMessage =
"Expected heap allocation (test method thread) to be less than "
+ byteAllocationMeasureFormatter.format(maxExpectedAllocation)
+ " but is " + byteAllocationMeasureFormatter.formatAndAppendAllocationInBytes(measuredAllocation) + ".";
String description = assertionMessage + System.lineSeparator() + measuredAllocation.getComment();
return new PerfIssue(description);
}
return PerfIssue.NONE;
}
|
191478424_0
|
@Override
public boolean visit(MySqlSelectQueryBlock block) {
String from = block.getFrom().toString();
for (String tableName : targetTableNames) {
// 在tableName后加上“.”,定位表名,防止定位到子串
// 例如:esd包括了es
StringBuilder sb = new StringBuilder(tableName);
sb.append(".");
String tableNamePoint = sb.toString();
// 不包含当前的tableName,就结束当前循环
if(!from.contains(tableNamePoint)) {
continue;
}
TableAddNumberEnum tableAddNumberEnum = targetTableFirstContainsMap.get(tableName);
List<MySqlSelectQueryBlock> sqlSelectQueryBlocks = blockMap.computeIfAbsent(tableName, k -> new LinkedList<>());
if(tableAddNumberEnum.equals(TableAddNumberEnum.ZERO)) {
sqlSelectQueryBlocks.add(block);
targetTableFirstContainsMap.put(tableName, TableAddNumberEnum.ONE);
continue;
}
if(tableAddNumberEnum.equals(TableAddNumberEnum.ONE)) {
sqlSelectQueryBlocks.remove(0);
sqlSelectQueryBlocks.add(block);
targetTableFirstContainsMap.put(tableName, TableAddNumberEnum.TWO);
continue;
}
if(tableAddNumberEnum.equals(TableAddNumberEnum.TWO)) {
sqlSelectQueryBlocks.add(block);
}
}
return true;
}
|
191553604_1044
|
@Override
public void onAddedJobGraph(final JobID jobId) {
runAsync(
() -> {
if (!jobManagerRunnerFutures.containsKey(jobId)) {
// IMPORTANT: onAddedJobGraph can generate false positives and, thus, we must expect that
// the specified job is already removed from the SubmittedJobGraphStore. In this case,
// SubmittedJobGraphStore.recoverJob returns null.
final CompletableFuture<Optional<JobGraph>> recoveredJob = recoveryOperation.thenApplyAsync(
FunctionUtils.uncheckedFunction(ignored -> Optional.ofNullable(recoverJob(jobId))),
getRpcService().getExecutor());
final DispatcherId dispatcherId = getFencingToken();
final CompletableFuture<Void> submissionFuture = recoveredJob.thenComposeAsync(
(Optional<JobGraph> jobGraphOptional) -> jobGraphOptional.map(
FunctionUtils.uncheckedFunction(jobGraph -> tryRunRecoveredJobGraph(jobGraph, dispatcherId).thenAcceptAsync(
FunctionUtils.uncheckedConsumer((Boolean isRecoveredJobRunning) -> {
if (!isRecoveredJobRunning) {
submittedJobGraphStore.releaseJobGraph(jobId);
}
}),
getRpcService().getExecutor())))
.orElse(CompletableFuture.completedFuture(null)),
getUnfencedMainThreadExecutor());
submissionFuture.whenComplete(
(Void ignored, Throwable throwable) -> {
if (throwable != null) {
onFatalError(
new DispatcherException(
String.format("Could not start the added job %s", jobId),
ExceptionUtils.stripCompletionException(throwable)));
}
});
recoveryOperation = submissionFuture;
}
});
}
|
191586445_1
|
@OnClose
public void onClose(Session session, @PathParam("username") String username) {
sessions.remove(username);
broadcaster.removeSession(session);
broadcaster.broadcast("#User: " + username + " left");
LOGGER.info(username + " is offline!");
}
|
192009782_4
|
public static RSAPrivateKey encryptedKeyPemStringToRsaPrivateKey(String encryptedPrivateKeyPemString, String privateKeyPassword)
throws PopPrivateKeyParseException {
if (StringUtils.isBlank(encryptedPrivateKeyPemString)) {
throw new IllegalArgumentException("The encryptedPrivateKeyPemString should not be null or empty");
}
if (StringUtils.isBlank(privateKeyPassword)) {
throw new IllegalArgumentException("The privateKeyPassword should not be null or empty");
}
try {
if (encryptedPrivateKeyPemString.startsWith(PKCS_8_ENCRYPTED_PRIVATE_KEY_PREFIX)
&& encryptedPrivateKeyPemString.contains(PKCS_8_ENCRYPTED_PRIVATE_KEY_SUFFIX)) {
return buildRsaPrivateKey(encryptedPrivateKeyPemString, privateKeyPassword);
} else {
throw new PopPrivateKeyParseException(
"The encryptedPrivateKeyPemString contains unsupported format, only PKCS#8 format is currently supported");
}
} catch (PopPrivateKeyParseException ex) {
throw ex;
} catch (Exception ex) {
throw new PopPrivateKeyParseException(
"Error occurred while converting encryptedPrivateKeyPemString to RSAPrivateKey, error: " + ex.toString(), ex);
}
}
|
192381473_43
|
public static boolean isIndexRequest(@NonNull Request esRequest) {
// the path should contain /index/type/ or /index/type/id
// type shouldn't be _search
String[] pathFields = esRequest.getEndpoint().substring(1).split("/");
return (pathFields.length == Constants.INDEX_PATH_LENGTH
|| pathFields.length == Constants.INDEX_PATH_LENGTH_WITHOUT_ID)
&& !Constants.SEARCH_REQUEST.equals(pathFields[1])
&& pathFields[0].matches(Constants.INDEX_REGEX);
}
|
192457111_9
|
;
|
192508383_59
|
@Override
public void execute(SensorContext context) {
if (shouldExecuteOnProject()) {
for (RuleViolation violation : executor.execute()) {
pmdViolationRecorder.saveViolation(violation, context);
}
}
}
|
192537952_91
|
@PostMapping("/permission/remove")
@AdminRequired
@RouteMeta(permission = "删除多个权限", module = "管理员")
public UnifyResponseVO removePermissions(@RequestBody @Validated RemovePermissionsDTO validator) {
adminService.removePermissions(validator);
return ResponseUtil.generateUnifyResponse(8);
}
|
192931477_1
|
public static IProviderServer getProviderServer() {
String protocol = Property.Rpc.protocol;
IProviderServer extension = ExtensionLoader.getExtensionLoader(IProviderServer.class).getExtension(protocol);
return extension;
}
|
192942452_46
|
public void ensureStopped() throws InterruptedException {
for (int i = 0; i < 30; i++) {
ApplicationStatus currentStatus = detailSupplier.get().applicationStatus();
switch (currentStatus) {
case RUNNING:
stop();
break;
case STOPPING:
break;
case READY:
return;
default:
throw new IllegalStateException("application in unexpected state: " + currentStatus);
}
Thread.sleep(statusPollingInterval);
}
throw new IllegalStateException("timed out waiting for application to stop");
}
|
193047220_40
|
@Override
public List<ComponentsValidator> create(FactoryOptions options) {
List<ComponentsValidator> validators = new ArrayList<>();
// skeletons
validators.add(new ComponentsHeadersValuesValidator(headerValidatorFactory.create(options)));
validators.add(new ComponentsParametersValuesValidator(parameterValidatorFactory.create(options)));
validators.add(new ComponentsRequestBodiesValuesValidator(requestBodyValidatorFactory.create(options)));
validators.add(new ComponentsResponsesValuesValidator(responseValidatorFactory.create(options)));
validators.add(new ComponentsSchemasValuesValidator(schemaValidatorFactory.create(options)));
validators.add(new ComponentsSecuritySchemesValuesValidator(securitySchemeValidatorFactory.create(options)));
// concretes
addComponentsCallbacksKeysCaseValidator(validators, options);
addComponentsExamplesKeysCaseValidator(validators, options);
addComponentsHeadersKeysCaseValidator(validators, options);
addComponentsLinksKeysCaseValidator(validators, options);
addComponentsParametersKeysCaseValidator(validators, options);
addComponentsRequestBodiesKeysCaseValidator(validators, options);
addComponentsResponsesKeysCaseValidator(validators, options);
addComponentsSchemasKeysCaseValidator(validators, options);
addComponentsSecuritySchemesKeysCaseValidator(validators, options);
return Collections.unmodifiableList(validators);
}
|
193065376_4
|
@Substitute
public static Object simpleDeepCopy(Object toCopy) {
return JsonUtils.cloneJson(toCopy);
}
|
193085253_6
|
public Optional<LeaveRequest> approve(UUID id) {
Optional<LeaveRequest> found = repo.findById(id);
found.ifPresent(lr -> lr.setStatus(Status.APPROVED));
return found;
}
|
193109862_14
|
public boolean sameAs(DENOPTIMEdge other, StringBuilder reason)
{
if (this.getSourceDAP() != other.getSourceDAP())
{
reason.append("Different source atom ("+this.getSourceDAP()+":"
+other.getSourceDAP()+"); ");
return false;
}
if (this.getTargetDAP() != other.getTargetDAP())
{
reason.append("Different target atom ("+this.getTargetDAP()+":"
+other.getTargetDAP()+"); ");
return false;
}
if (!this.getSourceReaction().equals(other.getSourceReaction()))
{
reason.append("Different source APClass ("
+this.getSourceReaction()+":"
+other.getSourceReaction()+"); ");
return false;
}
if (!this.getTargetReaction().equals(other.getTargetReaction()))
{
reason.append("Different target APClass ("
+this.getTargetReaction()+":"
+other.getTargetReaction()+"); ");
return false;
}
if (this.getBondType() != (other.getBondType()))
{
reason.append("Different bond type ("+this.getBondType()+":"
+other.getBondType()+"); ");
return false;
}
return true;
}
|
193272759_264
|
public synchronized void addTrainingSet(TrainingSet trainingSet)
{
trainingSet.setTrainingSetID(trainingSetIDCounter++);
trainingSets.add(trainingSet);
}
|
193500053_6
|
static Map<String, List<String>> stripDuplicatePrefixes(Map<String, List<String>> fullList) {
// Create a prefix tree
var trie = mapToTrie(fullList);
// Prune it
var pruned = pruneEntry(trie);
// Restore the map from the tree
return trieToMap(pruned, "");
}
|
193582925_57
|
public static void testMain(String[] args) {
new StorageCli(args, true).processCmd();
}
|
193657959_5
|
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
String jwt = resolveToken(httpServletRequest);
if (StringUtils.hasText(jwt) && this.tokenProvider.validateToken(jwt)) {
Authentication authentication = this.tokenProvider.getAuthentication(jwt);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(servletRequest, servletResponse);
}
|
193855481_2
|
@Override
public void decrypt(final String passphrase, final Path targetPath) {
try {
final byte[] clearBytes = decrypt(this.getPath(), passphrase, targetPath);
final String clearText = new String(clearBytes, StandardCharsets.ISO_8859_1);
} catch (final GeneralSecurityException | IOException ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
}
|
193945625_21
|
protected ProgressEvent<ResourceModel, CallbackContext> handleRequest(
final AmazonWebServicesClientProxy proxy,
final ResourceHandlerRequest<ResourceModel> request,
final CallbackContext callbackContext,
final ProxyClient<CloudFormationClient> proxyClient,
final Logger logger) {
final ResourceModel resourceModel = request.getDesiredResourceState();
final CallChain.Initiator<CloudFormationClient, ResourceModel, CallbackContext> initiator =
proxy.newInitiator(proxyClient, resourceModel, callbackContext);
return initiator.initiate("read")
.translateToServiceRequest((model) -> Translator.translateToReadRequest(model, logger))
.makeServiceCall((awsRequest, sdkProxyClient) -> readResource(awsRequest, sdkProxyClient , resourceModel))
.done(awsResponse -> ProgressEvent.defaultSuccessHandler(Translator.translateFromReadResponse(awsResponse)));
}
|
194059614_0
|
@Override
public AuthorizedAppDTO apply(OAuthConsumerAppDTO oAuthConsumerAppDTO) {
AuthorizedAppDTO authorizedAppDTO = new AuthorizedAppDTO();
authorizedAppDTO.setAppId(oAuthConsumerAppDTO.getApplicationName());
authorizedAppDTO.setClientId(oAuthConsumerAppDTO.getOauthConsumerKey());
return authorizedAppDTO;
}
|
194304228_11
|
public static String unicodeCodePoint2PercentHexString(int codePoint, String charsetName) {
if (!Character.isDefined(codePoint))
throw new IllegalArgumentException(
String.format("Given code point [U+%1$04X - %1$d] not assigned to an abstract character.", codePoint));
if (Character.getType(codePoint) == Character.SURROGATE)
throw new IllegalArgumentException(String
.format("Given code point [U+%1$04X - %1$d] is an unencodable (by itself) surrogate character.", codePoint));
Charset charset = Charset.availableCharsets().get(charsetName);
if (charset == null)
throw new IllegalArgumentException(String.format("Unsupported charset [%s].", charsetName));
char[] chars = Character.toChars(codePoint);
ByteBuffer byteBuffer = null;
try {
byteBuffer = charset.newEncoder().encode(CharBuffer.wrap(chars));
} catch (CharacterCodingException e) {
String message = String.format("Given code point [U+%1$04X - %1$d] cannot be encode in given charset [%2$s].",
codePoint, charsetName);
throw new IllegalArgumentException(message, e);
}
byteBuffer.rewind();
StringBuilder encodedString = new StringBuilder();
for (int i = 0; i < byteBuffer.limit(); i++) {
String asHex = Integer.toHexString(byteBuffer.get() & 0xFF);
encodedString.append("%").append(asHex.length() == 1 ? "0" : "").append(asHex);
}
return encodedString.toString();
}
|
194333585_127
|
static String constructMetadataParamQuery(List<String> metadataSelectCols) {
String pkColsCsv = getPksCsv();
String query =
QueryUtil.constructSelectStatement(OUTPUT_METADATA_TABLE_NAME, metadataSelectCols,
pkColsCsv, null, true);
String inClause = " IN " + QueryUtil.constructParameterizedInClause(3, 1);
return query + inClause;
}
|
194654807_4
|
public Path install(BuildahConfiguration buildahConfiguration) throws IOException {
final LocationResolver locationResolver = this.locationResolverChain.getLocationResolver(buildahConfiguration);
return install(locationResolver.getBuildahName(), locationResolver.loadBuildahResource(), buildahConfiguration);
}
|
194726816_0
|
public static MultiSignaturePublicKey create(List<PublicKey> publicKeys, int threshold) {
byte[] multiSigPublicKeyBytes = new byte[publicKeys.size() * PUBLIC_KEY_LENGTH + 1];
int counter = 0;
for (PublicKey pk : publicKeys) {
byte[] pkBytes = pk.toArray();
System.arraycopy(pkBytes, 0, multiSigPublicKeyBytes, counter++ * PUBLIC_KEY_LENGTH, PUBLIC_KEY_LENGTH);
}
multiSigPublicKeyBytes[multiSigPublicKeyBytes.length - 1] = (byte) threshold;
return new MultiSignaturePublicKey(ByteArray.from(multiSigPublicKeyBytes));
}
|
194776722_7
|
public boolean isVertical() {
return this.isVerticalLine;
}
|
194907949_1
|
@NotNull
@Override
public Ore getOre() {
return this.ore;
}
|
195077933_15
|
@GetMapping(path = "/list")
@Authorize(value = {
AuthConstant.AUTHORIZATION_SUPPORT_USER
})
public ListAccountResponse listAccounts(@RequestParam int offset, @RequestParam @Min(0) int limit) {
AccountList accountList = accountService.list(offset, limit);
ListAccountResponse listAccountResponse = new ListAccountResponse(accountList);
return listAccountResponse;
}
|
195192171_1
|
public Map<String,String> transferMapValue(Map<String, String> params){
Map<String,String> postmap=new HashMap<String,String>();
Iterator entries = params.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
String paramkey = (String)entry.getKey();
String paramvalue = (String)entry.getValue();
String desStr = DESUtilWithIV.des(paramvalue, key, Cipher.ENCRYPT_MODE);
postmap.put(paramkey,desStr);
}
postmap.put("encrypt","1");
LogUtil.debugLogWithJava("调试,开始加密字符串");
LogUtil.debugLogWithJava("加密后的map");
LogUtil.debugLogWithJava(postmap.toString());
return postmap;
}
|
195288202_0
|
@PostMapping
ResponseEntity<?> post(@Valid @RequestBody Car car) throws URISyntaxException {
/**
* TODO: Use the `save` method from the Car Service to save the input car.
* TODO: Use the `assembler` on that saved car and return as part of the response.
* Update the first line as part of the above implementing.
*/
Resource<Car> resource = assembler.toResource(new Car());
return ResponseEntity.created(new URI(resource.getId().expand().getHref())).body(resource);
}
|
195297601_0
|
public BigDecimal convert(BigDecimal amount, String currencyFrom, String currencyTo) {
BigDecimal exchangeRate = currencyDto.getExchangeRate(currencyFrom, currencyTo);
return amount.multiply(exchangeRate);
}
|
195330123_50
|
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
// if this is a "new" table, init HTable object. Else, use existing one
if (!tableName.equals(table)) {
currentTable = null;
try {
getHTable(table);
tableName = table;
} catch (IOException e) {
System.err.println("Error accessing HBase table: " + e);
return Status.ERROR;
}
}
Scan s = new Scan(Bytes.toBytes(startkey));
// HBase has no record limit. Here, assume recordcount is small enough to
// bring back in one call.
// We get back recordcount records
s.setCaching(recordcount);
if (this.usePageFilter) {
s.setFilter(new PageFilter(recordcount));
}
// add specified fields or else all fields
if (fields == null) {
s.addFamily(columnFamilyBytes);
} else {
for (String field : fields) {
s.addColumn(columnFamilyBytes, Bytes.toBytes(field));
}
}
// get results
ResultScanner scanner = null;
try {
scanner = currentTable.getScanner(s);
int numResults = 0;
for (Result rr = scanner.next(); rr != null; rr = scanner.next()) {
// get row key
String key = Bytes.toString(rr.getRow());
if (debug) {
System.out.println("Got scan result for key: " + key);
}
HashMap<String, ByteIterator> rowResult =
new HashMap<String, ByteIterator>();
while (rr.advance()) {
final Cell cell = rr.current();
rowResult.put(Bytes.toString(CellUtil.cloneQualifier(cell)),
new ByteArrayByteIterator(CellUtil.cloneValue(cell)));
}
// add rowResult to result vector
result.add(rowResult);
numResults++;
// PageFilter does not guarantee that the number of results is <=
// pageSize, so this
// break is required.
if (numResults >= recordcount) {// if hit recordcount, bail out
break;
}
} // done with row
} catch (IOException e) {
if (debug) {
System.out.println("Error in getting/parsing scan result: " + e);
}
return Status.ERROR;
} finally {
if (scanner != null) {
scanner.close();
}
}
return Status.OK;
}
|
195429957_0
|
public static Span getSpan() {
Context c = Vertx.currentContext();
return c == null ? null : c.getLocal(ACTIVE_SPAN);
}
|
195506596_11
|
public ResponseEntity<InlineResponse200> grantUserTokenPost(@ApiParam(value = "") @Valid @RequestBody GrantInfo body) {
String accept = request.getHeader("Accept");
if (accept != null && accept.contains("application/json")) {
try {
return new ResponseEntity<InlineResponse200>(objectMapper.readValue("{\n" +
" \"status\" : \"status\",\n" +
" \"token\" : \"046b6c7f-0b8a-43b9-b35d-6489e6daee91\"\n" +
"}", InlineResponse200.class), HttpStatus.NOT_IMPLEMENTED);
} catch (IOException e) {
log.error("Couldn't serialize response for content type application/json", e);
return new ResponseEntity<InlineResponse200>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
return new ResponseEntity<InlineResponse200>(HttpStatus.NOT_IMPLEMENTED);
}
|
195650526_707
|
static String toJavaName(String opensslName) {
if (opensslName == null) {
return null;
}
Matcher matcher = PATTERN.matcher(opensslName);
if (matcher.matches()) {
String group2 = matcher.group(2);
if (group2 != null) {
return group2.toUpperCase(Locale.ROOT) + "with" + matcher.group(3).toUpperCase(Locale.ROOT);
}
if (matcher.group(4) != null) {
return matcher.group(7).toUpperCase(Locale.ROOT) + "with" + matcher.group(5).toUpperCase(Locale.ROOT);
}
}
return null;
}
|
195708935_5
|
public ParsedOutput parse(List<String> args) {
final Command commandName = this.findCommand(args);
fillShortAndLongOptions(commandName);
final Map<CommandFlag, Object> options = this.findOptions(args);
return new ParsedOutput(commandName, args, options);
}
|
196110471_5
|
public static StringBuilder appendByteArrayAsHex(StringBuilder sb, byte[] ab, int of, int cb)
{
sb.ensureCapacity(sb.length() + cb * 2);
while (--cb >= 0)
{
int n = ab[of++];
sb.append(nibbleToChar(n >> 4))
.append(nibbleToChar(n));
}
return sb;
}
|
196320779_0
|
public CasterClient(ServerInfo serverInfo) {
this.serverInfo = serverInfo;
}
|
197006279_77
|
public static Entry entry(String name) throws BlockException {
return Env.sph.entry(name, EntryType.OUT, 1, OBJECTS0);
}
|
197111529_1
|
public static void park(Object blocker) {
Thread t = Thread.currentThread();
setBlocker(t, blocker);
UNSAFE.park(false, 0L);
setBlocker(t, null);
}
|
197192301_6
|
public static ArtifactType discoverType(ContentHandle content, String contentType) throws InvalidArtifactTypeException {
boolean triedProto = false;
// If the content-type suggests it's protobuf, try that first.
if (contentType == null || contentType.toLowerCase().contains("proto")) {
triedProto = true;
ArtifactType type = tryProto(content);
if (type != null) {
return type;
}
}
// Try the various JSON formatted types
try {
JsonNode tree = mapper.readTree(content.content());
// OpenAPI
if (tree.has("openapi") || tree.has("swagger")) {
return ArtifactType.OPENAPI;
}
// AsyncAPI
if (tree.has("asyncapi")) {
return ArtifactType.ASYNCAPI;
}
// JSON Schema
if (tree.has("$schema") && tree.get("$schema").asText().contains("json-schema.org")) {
return ArtifactType.JSON;
}
// Kafka Connect??
// TODO detect Kafka Connect schemas
// Avro
if (tree.has("type")) {
return ArtifactType.AVRO;
}
throw new InvalidArtifactTypeException("Failed to discover artifact type from JSON content.");
} catch (Exception e) {
// Apparently it's not JSON.
}
// Try protobuf (only if we haven't already)
if (!triedProto) {
ArtifactType type = tryProto(content);
if (type != null) {
return type;
}
}
// Try GraphQL (SDL)
if (tryGraphQL(content)) {
return ArtifactType.GRAPHQL;
}
// Try the various XML formatted types
try (InputStream stream = content.stream()) {
Document xmlDocument = DocumentBuilderAccessor.getDocumentBuilder().parse(stream);
Element root = xmlDocument.getDocumentElement();
String ns = root.getNamespaceURI();
// XSD
if (ns != null && ns.equals("http://www.w3.org/2001/XMLSchema")) {
return ArtifactType.XSD;
} // WSDL
else if (ns != null && (ns.equals("http://schemas.xmlsoap.org/wsdl/")
|| ns.equals("http://www.w3.org/ns/wsdl/"))) {
return ArtifactType.WSDL;
} else {
// default to XML since its been parsed
return ArtifactType.XML;
}
} catch (Exception e) {
// It's not XML.
}
throw new InvalidArtifactTypeException("Failed to discover artifact type from content.");
}
|
197277844_0
|
static String getPayload(String token) {
int first = token.indexOf('.');
int last = token.lastIndexOf('.');
return token.substring(first+1, last);
}
|
197569657_35
|
public long count(String sql,
Collection params) {
return this.get(Number.class, getDialect().count(sql, params))
.longValue();
}
|
197729287_0
|
@Bindable
public String getTitle() {
return title;
}
|
197782274_0
|
@Override
public int compareTo(Contact contact) {
String givenName1 = this.givenName == null ? "" : this.givenName.toLowerCase();
String givenName2 = contact == null ? ""
: (contact.givenName == null ? "" : contact.givenName.toLowerCase());
return givenName1.compareTo(givenName2);
}
|
198181246_11
|
public List<ServiceInstance> getInstances(Microservice microservice, String revision) {
List<ServiceInstance> instanceList = new ArrayList<>();
Response response = null;
try {
Map<String, String> heades = Maps.newHashMap();
String CONSUMER_HEADER = "X-ConsumerId";
heades.put(CONSUMER_HEADER, RegisterCache.getServiceID());
// rev是一个query字段,单位是app service version,需要缓存
response = httpTransport
.sendGetRequest(
addParam2URI(buildURI("/registry/instances"), null, revision,
microservice),
heades);
if (response.getStatusCode() == HttpStatus.SC_OK) {
Microservice result = JsonUtils.OBJ_MAPPER
.readValue(response.getContent(), Microservice.class);
if (result == null || result.getInstances() == null) {
return instanceList;
}
String REVISION_HEADER = "X-Resource-Revision";
if (!StringUtils.isEmpty(response.getHeader(REVISION_HEADER))) {
MicroserviceHandler.serviceRevision.put(
microservice.getServiceName(), response.getHeader(REVISION_HEADER));
}
MicroserviceCache.initInsList(result.getInstances(), microservice.getServiceName());
for (MicroserviceInstance instance : result.getInstances()) {
int port;
String host;
if (!instance.getEndpoints().isEmpty()) {
String endpoint = instance.getEndpoints().get(0);
URI endpointURIBuilder = new URIBuilder(endpoint).build();
port = endpointURIBuilder.getPort();
host = endpointURIBuilder.getHost();
} else {
LOGGER.warn(
"read response failed. status:" + response.getStatusCode() + "; message:" + response
.getStatusMessage() + "; content:" + response.getContent());
return null;
}
Map<String, String> map = new HashMap<>();
map.put(INSTANCE_STATUS, instance.getStatus().name());
if (instance.getDataCenterInfo() != null) {
map.put(ZONE, instance.getDataCenterInfo().getZone());
}
instanceList.add(
new DefaultServiceInstance(instance.getInstanceId(), instance.getServiceName(), host,
port, false, map));
}
return instanceList;
} else if (response.getStatusCode() != HttpStatus.SC_NOT_MODIFIED) {
LOGGER.debug(
"read response failed. status:" + response.getStatusCode() + "; message:" + response
.getStatusMessage() + "; content:" + response.getContent());
}
} catch (URISyntaxException e) {
LOGGER.warn("build url failed.", e);
} catch (IOException e) {
LOGGER.warn("read response failed. " + response);
} catch (RemoteServerUnavailableException e) {
LOGGER.warn("get instances failed.", e);
}
return null;
}
|
198181508_0
|
public static String getComputerIdentifier() {
SystemInfo systemInfo = new SystemInfo();
OperatingSystem operatingSystem = systemInfo.getOperatingSystem();
HardwareAbstractionLayer hardwareAbstractionLayer = systemInfo.getHardware();
CentralProcessor centralProcessor = hardwareAbstractionLayer.getProcessor();
ComputerSystem computerSystem = hardwareAbstractionLayer.getComputerSystem();
String vendor = operatingSystem.getManufacturer();
String processorSerialNumber = computerSystem.getSerialNumber();
String processorIdentifier = centralProcessor.getIdentifier();
int processors = centralProcessor.getLogicalProcessorCount();
String delimiter = "-";
return String.format("%08x", vendor.hashCode()) + delimiter
+ String.format("%08x", processorSerialNumber.hashCode()) + delimiter
+ String.format("%08x", processorIdentifier.hashCode()) + delimiter + processors;
}
|
198220069_27
|
public List<ByteBuffer> filter(Consumer consumer, List<ByteBuffer> byteBuffers, FilterCallback filterCallback) throws JoyQueueException {
FilterPipeline<MessageFilter> filterPipeline = filterRuleCache.get(consumer.getId());
if (filterPipeline == null) {
filterPipeline = createFilterPipeline(consumer.getConsumerPolicy());
filterRuleCache.putIfAbsent(consumer.getId(), filterPipeline);
}
List<ByteBuffer> result = filterPipeline.execute(byteBuffers, filterCallback);
return result;
}
|
198222234_67
|
@Override
public <I, O> ProcessingStage<I, O> create(Engine engine, Stage.FlatMapIterable stage) {
Function<I, Iterable<O>> mapper = Casts.cast(stage.getMapper());
return new FlatMapIterable<>(mapper);
}
|
198238470_474
|
public void assertAllowedForProject(SecHubConfiguration configuration) {
List<URI> allowed = fetchAllowedUris(configuration);
Optional<SecHubInfrastructureScanConfiguration> infrascanOpt = configuration.getInfraScan();
if (infrascanOpt.isPresent()) {
SecHubInfrastructureScanConfiguration infraconf = infrascanOpt.get();
assertWhitelisted(allowed, infraconf.getUris());
assertWhitelisted(allowed, asUris(infraconf.getIps()));
}
Optional<SecHubWebScanConfiguration> webscanopt = configuration.getWebScan();
if (webscanopt.isPresent()) {
SecHubWebScanConfiguration webconf = webscanopt.get();
assertWhitelisted(allowed, webconf.getUris());
}
}
|
198355705_9
|
public ElasticSqlParseResult parse(String sql) throws ElasticSql2DslException{
Walker walker=new Walker(sql);
ElasticsearchParser.SqlContext sqlContext = walker.buildAntlrTree();
ElasticDslContext elasticDslContext=new ElasticDslContext(sqlContext);
for(QueryParser parser:buildSqlParserChain()){
parser.parse(elasticDslContext);
}
return elasticDslContext.getParseResult();
}
|
198569702_7
|
@Override
public byte[] decrypt(byte[] encryptData) {
try {
javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(KEY_ALGORITHM);
cipher.init(javax.crypto.Cipher.DECRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(Base64.getDecoder().decode(encryptData));
return result;
} catch (Exception e) {
throw new CryptoException(e);
}
}
|
198857750_2
|
public RemoteWebDriver start() {
driver = createRemoteWebDriver(getSauceUrl(), sauceOptions.toCapabilities());
return driver;
}
|
198950692_148
|
public PageResultPlus<CommonLog> getCommonLogList(CommonLogParams commonLogParams) {
Long commonLogCount = this.baseMapper.getCommonLogCount();
if (commonLogParams.getGtValue() == null) {
commonLogParams.setGtValue(commonLogCount);
}
List<CommonLog> commonLogList = this.baseMapper.getCommonLogList(commonLogParams);
return CommonLogFactory.getResponse(commonLogList, commonLogCount, commonLogParams);
}
|
199027540_43
|
public long getTime() {
return time;
}
|
199046636_39
|
@PutMapping("/admin/tag/update")
public Response updateOne(@RequestParam("id") Long id, @RequestParam("name") String name) {
return ResponseUtil.success(tagService.update(id, name));
}
|
199262429_198
|
public boolean isEmpty() {
return root == null;
}
|
199309560_3
|
public OpenAPI generate() {
return generate(OpenApiGeneratorConfigBuilder.defaultConfig().build());
}
|
199431217_0
|
public void recover(Path path, long min, Properties properties) throws IOException {
Files.createDirectories(path);
this.base = path.toFile();
this.config = toConfig(properties);
bufferPool.addPreLoad(config.getFileDataSize(), config.getCachedFileCoreCount(), config.getCachedFileMaxCount());
recoverFileMap(min);
long recoverPosition = this.storeFileMap.isEmpty() ? min : this.storeFileMap.lastKey() + this.storeFileMap.lastEntry().getValue().fileDataSize();
flushPosition.set(recoverPosition);
writePosition.set(recoverPosition);
leftPosition.set(this.storeFileMap.isEmpty() ? min : this.storeFileMap.firstKey());
resetWriteStoreFile();
if (logger.isDebugEnabled()) {
logger.debug("Store loaded, left: {}, right: {}, base: {}.",
ThreadSafeFormat.formatWithComma(min()),
ThreadSafeFormat.formatWithComma(max()),
base.getAbsolutePath());
}
}
|
199491032_2
|
Result<? extends Record> run() {
// Pull the latest state from the DB
model.updateData();
// Run the solver and return the virtual machines table with solver-identified values for the
// controllable__physical_machines column
return model.solve(VIRTUAL_MACHINES_TABLE);
}
|
199626064_3
|
@Override
public int read() throws IOException {
char[] buffer = new char[1];
int read = read(buffer);
if (read < 0) {
return read;
} else {
return buffer[0];
}
}
|
199703640_0
|
@SuppressWarnings("unchecked")
@Override
public <T extends Actor> Collection<Class<? extends T>> findActorInterfaces(final Predicate<Class<T>> predicate)
{
List<Class<? extends T>> interfaces = null;
for (Class<?> concreteInterface : concreteImplementations.keySet())
{
if (predicate.test((Class<T>) concreteInterface))
{
if (interfaces == null)
{
interfaces = new ArrayList<>();
}
interfaces.add((Class<T>) concreteInterface);
}
}
return interfaces != null ? interfaces : Collections.emptyList();
}
|
199829201_0
|
@Override
public Result<NewCustomerPartResponse> partNewCustomerActivity(NewCustomerPartRequest request) {
ContextParam contextParam = new ContextParam(FunctionCodeEnum.ACTIVITY_PARTICIPATE, request,
ActivityTypeEnum.NEW_CUSTOMER_GIFT.getType());
return activityDispatcher.dispatcher(contextParam);
}
|
199902324_0
|
@POST
@ApiOperation(value = "Create a new Card", notes = "Create a card using json")
public Response createCard(Card card){
card = cardService.createCard(card);
return Response.created(getGetUri(card)).build();
}
|
200004447_0
|
public FullState getCurrentFullState(int pid) {
try {
CpuState cpuState = StatParser.getInstance().parseCpuInfo();
File processFile = new File("/proc", String.valueOf(pid));
ProcessState processState = StatParser.getInstance().parseProcessInfo(pid);
File taskFile = new File(processFile, "task");
File[] taskFiles = taskFile.listFiles();
if (!taskFile.exists() || taskFiles == null) {
return null;
}
Map<Integer, ThreadState> threadInfo = getThreadInfo(pid, taskFiles);
return new FullState(cpuState, processState, threadInfo);
} catch (IOException e) {
LOGGER.error("get current process state error");
return null;
}
}
|
200044570_0
|
public static byte[] bytesFromHexString(String s) {
if ((s.length() % 2) != 0) {
throw new IllegalArgumentException(
"Converting to bytes requires even number of characters, got " + s.length());
}
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;
}
|
200053873_12
|
@ReactMethod
public void enableVerboseLogging() {
MarketingCloudSdk.setLogLevel(MCLogListener.VERBOSE);
MarketingCloudSdk.setLogListener(new MCLogListener.AndroidLogListener());
}
|
200062847_31
|
@Nonnull
@Override
public CompletionItemKind getKind() {
return CompletionItemKind.Method;
}
|
200492090_13
|
@Override
public Behavior<DssRestChannelHandlerCommand> create() {
if (initializeBehavior.get()) {
throw new DssUserActorDuplicateBehaviorCreateException("Cannot setup twice for one object");
}
initializeBehavior.set(true);
return Behaviors.setup(this::dssRestHandler);
}
|
200539506_37
|
public GenericResponse deleteModel(Integer printId) {
GenericResponse response = new GenericResponse();
response.setSuccess(false);
response.setMessage("File could not be deleted");
response.setHttpStatus(HttpStatus.BAD_REQUEST);
PrintJob printJob = printJobRepo.findPrintJobById(printId);
if(printJob == null) {
throw new IdeaLabApiException(PRINT_JOBS_NOT_EXIST);
}
fileService.deleteFile(printJob.getFilePath());
printJob.setFilePath("Deleted");
printJob.setFileSharableLink("Deleted");
printJob = printJobRepo.save(printJob);
response.setSuccess(true);
response.setMessage("Successfully deleted file from DropBox");
response.setHttpStatus(HttpStatus.ACCEPTED);
return response;
}
|
200620451_122
|
@Override
public List<Place> findAll() {
log.info(LogMessage.IN_FIND_ALL);
return placeRepo.findAll();
}
|
200642013_0
|
public Response validateAndAdd(ProductFormData productData) {
if ("".equals(productData.getName())) {
return new Response(0, -2, "Missing Name");
}
if ("".equals(productData.getType()) ) {
return new Response(0, -2, "Missing Type");
}
Product product = new Product(productData.getName());
product.setType("Unknown");
if ("Eyeshadow".equals(productData.getType()) || "Mascara".equals(productData.getType())) {
product.setType(productData.getType());
product.setFamily(ProductFamily.EYES);
if ("Eyeshadow".equals(productData.getType()) && product.getName().contains("Queen")) {
product.setRange(ProductRange.QUEEN);
}
}
product.setRange(ProductRange.BUDGET);
if (productData.isPackagingRecyclable()) {
product.setRange(ProductRange.PROFESSIONAL);
}
if ("Foundation".equals(productData.getType())) {
if (productData.getSuggestedPrice() > 10) {
product.setRange(ProductRange.PROFESSIONAL);
}
}
if ("Lipstick".equals(productData.getType())) {
product.setType(productData.getType());
product.setFamily(ProductFamily.LIPS);
if (productData.getSuggestedPrice() > 10) {
product.setRange(ProductRange.PROFESSIONAL);
}
if (productData.getSuggestedPrice() > 20) {
if (productData.getWeight() > 0 && productData.getWeight() < 10) {
return new Response(0, -1, "Error - failed quality check for Queen Range");
}
product.setRange(ProductRange.QUEEN);
}
}
if ("Mascara".equals(productData.getType())) {
product.setFamily(ProductFamily.LASHES);
if (productData.getSuggestedPrice() > 15) {
product.setRange(ProductRange.PROFESSIONAL);
}
if (productData.getSuggestedPrice() > 25 && productData.isPackagingRecyclable()) {
product.setRange(ProductRange.QUEEN);
}
}
if (productData.getWeight() < 0) {
return new Response(0, -3, "Weight error");
}
product.setWeight(productData.getWeight());
if ("Blusher".equals(productData.getType()) || "Foundation".equals(productData.getType())) {
product.setType(productData.getType());
product.setFamily(ProductFamily.SKIN);
if ("Blusher".equals(productData.getType()) && productData.getWeight() > 10) {
return new Response(0, -3, "Error - weight too high");
}
}
if (!productData.isPackagingRecyclable() && product.getRange() == ProductRange.QUEEN) {
return new Response(0, -1, "Error - failed quality check for Queen Range");
}
if ("Unknown".equals(product.getType())) {
return new Response(0, -1, "Unknown product type " + productData.getType());
}
return new Response(db.storeProduct(product), 0, "Product Successfully Added");
}
|
200703047_38
|
public AccountsCreateResponse accounts(List<String> accounts) {
this.accounts = accounts;
return this;
}
|
200725818_0
|
@Override
public OperationResult transform(Transaction transaction) {
String error = validateOperation(transaction);
if (error != null) {
return new OperationResult(false, transaction, null, error);
}
BigDecimal creditAmount = transaction.getCreditAmount();
if (Transaction.Type.EXCHANGE.equals(transaction.getType())) {
Optional<ExchangeRate> exchangeRate = Optional
.ofNullable(rateStore.get(transaction.getCreditCurrency() + "-" + transaction.getDebitCurrency()));
Optional<ExchangeRate> invertedExchangeRate = Optional
.ofNullable(rateStore.get(transaction.getDebitCurrency() + "-" + transaction.getCreditCurrency()));
ExchangeRate rate = exchangeRate.orElse(invertedExchangeRate.orElse(null));
if (rate == null) {
return new OperationResult(false, transaction, null, "Exchange rate could not be found for "
+ transaction.getCreditCurrency() + " and " + transaction.getDebitCurrency());
}
if (rate.getBaseCurrency().equals(transaction.getCreditCurrency())) {
creditAmount = transaction.getDebitAmount().multiply(rate.getBid());
} else {
creditAmount = transaction.getDebitAmount().divide(rate.getAsk(), 5, RoundingMode.HALF_UP);
}
}
String storeKey = transaction.getAccount() + "-" + transaction.getCreditCurrency();
AccountCurrencyBalance existingBalance = Optional.ofNullable(balanceStore.get(storeKey))
.orElseGet(() -> new AccountCurrencyBalance(
new AccountCurrency(transaction.getAccount(), transaction.getCreditCurrency()),
BigDecimal.ZERO));
AccountCurrencyBalance newBalance = new AccountCurrencyBalance(existingBalance.getAccountCurrency(),
existingBalance.getBalance().add(creditAmount));
balanceStore.put(storeKey, newBalance);
return new OperationResult(true,
new Transaction(transaction.getGuid(), transaction.getAccount(), transaction.getType(),
transaction.getDebitAmount(), transaction.getDebitCurrency(), creditAmount,
transaction.getCreditCurrency()),
newBalance, null);
}
|
200810412_178
|
@Override
public void run(ApplicationArguments args) {
log.warn("Do not run this tool at the same time as replicating to the target table!");
if (isDryRun) {
log.warn("Dry-run only!");
}
try {
metastore = clientSupplier.get();
housekeepingPaths = fetchHousekeepingPaths(beekeeperRepository);
vacuumTable(databaseName, tableName);
} catch (URISyntaxException | TException | IOException e) {
throw new RuntimeException(e);
} finally {
if (metastore != null) {
metastore.close();
}
}
}
|
200980523_46
|
public void gameStateChanged(GameState newState) {
Set<Listener> listenersForNewState = recalculateListenersForNewState(newState);
this.registerNew(listenersForNewState);
}
|
201021482_12
|
@Override
public void describe(SensorDescriptor descriptor) {
descriptor.name("OpenAPI Scanner Sensor")
.onlyOnFileType(InputFile.Type.MAIN)
.onlyOnLanguage(OpenApi.KEY);
}
|
201080381_1239
|
public Quotation companyAddress2(String companyAddress2) {
this.companyAddress2 = companyAddress2;
return this;
}
|
201179882_3
|
public float getTilt() {
return mTilt;
}
|
201185153_17
|
HttpStatus exceptionToStatus(final Exception exc) {
if (exc instanceof BankService.ClientNotFoundExc) {
return HttpStatus.NOT_FOUND;
}
if (exc instanceof Client.NotManagedAccountExc) {
return HttpStatus.NOT_FOUND;
}
if (exc instanceof Client.NotOwnerExc) {
return HttpStatus.FORBIDDEN;
}
if (exc instanceof Client.WithoutRightExc) {
return HttpStatus.FORBIDDEN;
}
final String excClassName = exc.getClass().getName();
if (excClassName.startsWith(restInterfacePackagePrefix) || excClassName.startsWith(domainPackagePrefix)) {
return HttpStatus.BAD_REQUEST;
}
return HttpStatus.INTERNAL_SERVER_ERROR;
}
|
201194795_9
|
@Override
public String getLanguageVersion() {
return System.getProperty("java.version");
}
|
201285390_53
|
@Override
public boolean cleanUnusedTopic(String cluster) throws RemotingConnectException, RemotingSendRequestException,
RemotingTimeoutException, MQClientException, InterruptedException {
return defaultMQAdminExtImpl.cleanUnusedTopicByAddr(cluster);
}
|
201327708_0
|
public static ProtoString parse(String encoded) {
// Since this string is coming from the lexer/parser, it should be guaranteed to be
// non-null, not empty (at least 1 quote), and start with either a single or double quote.
if (encoded.isEmpty()) {
throw new IllegalArgumentException("String must not be empty.");
}
if (encoded.charAt(0) != '\'' && encoded.charAt(0) != '"') {
throw new IllegalArgumentException("String must start with a single or double quote.");
}
int[] offsets = new int[encoded.length()];
ImmutableList.Builder<TextRange> invalidEscapeRanges = ImmutableList.builder();
StringBuilder result = new StringBuilder(encoded.length());
StringLexer lexer = new StringLexer();
lexer.start(encoded);
boolean lastWasLiteral = false;
while (lexer.hasMoreTokens()) {
CharSequence value = lexer.currentTokenValue();
int start = lexer.getTokenStart();
for (int i = 0; i < value.length(); i++) {
offsets[result.length() + i] = start + i;
}
result.append(value);
if (lexer.isCurrentTokenInvalid()) {
invalidEscapeRanges.add(TextRange.create(lexer.getTokenStart(), lexer.getTokenEnd()));
}
lastWasLiteral = lexer.isCurrentTokenLiteral();
lexer.advance();
}
// If the last character doesn't match the opening quote, this string is unterminated. We ensure
// that the last character was part of a literal string part to prevent an escaped quote from
// being considered a valid terminator.
boolean unterminated = false;
String parsed;
if (!lastWasLiteral
|| result.charAt(result.length() - 1) != result.charAt(0)
|| result.length() == 1) {
unterminated = true;
// Cut off the starting quote
parsed = result.substring(1);
} else {
// Cut off the starting and ending quotes
parsed = result.substring(1, result.length() - 1);
}
offsets = Arrays.copyOfRange(offsets, 1, 1 + parsed.length());
return new ProtoString(encoded, parsed, unterminated, invalidEscapeRanges.build(), offsets);
}
|
201347287_2
|
@Nullable
public String getString(int id) {
final String result = strings.get(id);
if (result == null) {
// String not loaded or doesn't exist.
return loadString(id);
} else {
return result;
}
}
|
201427469_11
|
public static Action pickProvider(PackageManager pm) {
// Setting the Intent Data as seen at
// https://cs.android.com/android/platform/superproject/+/fd994cf9ef8207ad03dc3a1d831e9263ddfd4469:packages/apps/PermissionController/src/com/android/packageinstaller/role/model/BrowserRoleBehavior.java
Intent queryBrowsersIntent = new Intent()
.setAction(Intent.ACTION_VIEW)
.addCategory(Intent.CATEGORY_BROWSABLE)
.setData(Uri.fromParts("http", "", null));
if (sPackageNameForTesting != null) {
queryBrowsersIntent.setPackage(sPackageNameForTesting);
}
String bestCctProvider = null;
String bestBrowserProvider = null;
// These packages will be in order of Android's preference.
List<ResolveInfo> possibleProviders
= pm.queryIntentActivities(queryBrowsersIntent, PackageManager.MATCH_DEFAULT_ONLY);
// According to the documentation, the flag we want to use above is MATCH_DEFAULT_ONLY.
// This would match all the browsers installed on the user's system whose intent handler
// contains the category Intent.CATEGORY_DEFAULT. However, in Android M the behavior of
// the PackageManager changed to only return the default browser unless the MATCH_ALL is
// passed (this is specific to querying browsers - if you query for any other type of
// package, MATCH_DEFAULT_ONLY will work as documented). This flag did not exist on Android
// versions before M, so we only use it in that case.
//
// Additionally we add the result of the call with MATCH_ALL onto the end of the result of
// MATCH_DEFAULT_ONLY (instead of calling queryIntentActivities just once, with MATCH_ALL)
// because (again, as opposed to the documentation) when MATCH_ALL is used the results are
// not returned in order of Android's preference.
//
// This will result in the user's default browser being in the list twice, however that
// shouldn't affect the correctness of the following code.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
possibleProviders.addAll(pm.queryIntentActivities(queryBrowsersIntent,
PackageManager.MATCH_ALL));
}
Map<String, Integer> customTabsServices = getLaunchModesForCustomTabsServices(pm);
for (ResolveInfo possibleProvider : possibleProviders) {
String providerName = possibleProvider.activityInfo.packageName;
@LaunchMode int launchMode = customTabsServices.containsKey(providerName)
? customTabsServices.get(providerName) : LaunchMode.BROWSER;
switch (launchMode) {
case LaunchMode.TRUSTED_WEB_ACTIVITY:
Log.d(TAG, "Found TWA provider, finishing search: " + providerName);
return new Action(LaunchMode.TRUSTED_WEB_ACTIVITY, providerName);
case LaunchMode.CUSTOM_TAB:
Log.d(TAG, "Found Custom Tabs provider: " + providerName);
if (bestCctProvider == null) bestCctProvider = providerName;
break;
case LaunchMode.BROWSER:
Log.d(TAG, "Found browser: " + providerName);
if (bestBrowserProvider == null) bestBrowserProvider = providerName;
break;
}
}
if (bestCctProvider != null) {
Log.d(TAG, "Found no TWA providers, using first Custom Tabs provider: "
+ bestCctProvider);
return new Action(LaunchMode.CUSTOM_TAB, bestCctProvider);
}
Log.d(TAG, "Found no TWA providers, using first browser: " + bestBrowserProvider);
return new Action(LaunchMode.BROWSER, bestBrowserProvider);
}
|
201612522_16
|
@Override
public ScriptEngine getScriptEngine() {
return new JShellScriptEngine();
}
|
201655283_0
|
public String Execute(String sql) {
this.generateStatements(sql);
return parseStatements();
}
|
202008893_71
|
public static void updatePromLookup(final int envId, int compId, String httpPath){
Session session = HibernateConfig.getSessionFactory().getCurrentSession();
Transaction txn = session.beginTransaction();
Query query = session.createQuery(HQLConstants.UPDATE_PROM_LOOKUP_DETAILS);
query.setString("httpPath", httpPath);
query.setTimestamp("lastUpdateDate", new java.sql.Timestamp(System.currentTimeMillis()));
query.setLong("compId", compId);
query.setLong("environmentId", envId);
query.executeUpdate();
txn.commit();
}
|
202089894_59
|
public static AsymmetricKeyPair initAsymmetricKeyPair() {
return RSACoder.initKey();
}
|
202309300_0
|
public static String createSignedJwt(String user, PrivateKey privateKey) throws Exception {
Calendar c = Calendar.getInstance();
c.add(Calendar.MINUTE, 1);
Date d = c.getTime();
return createSignedJwt(user, d.getTime() / 1000, privateKey);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.