_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q172500
FieldEncrypter.checkInputEncrypt
test
public Optional<Field> checkInputEncrypt(Field field) throws StageException { if (UNSUPPORTED_TYPES.contains(field.getType())) { throw new StageException(CRYPTO_03, field.getType()); } return Optional.of(field); }
java
{ "resource": "" }
q172501
FieldEncrypter.checkInputDecrypt
test
public Optional<Field> checkInputDecrypt(Record record, Field field) { if (field.getType() != Field.Type.BYTE_ARRAY) { getContext().toError(record, CRYPTO_02, field.getType()); return Optional.empty(); } return Optional.of(field); }
java
{ "resource": "" }
q172502
FieldEncrypter.checkInputDecrypt
test
public Optional<Field> checkInputDecrypt(Field field) throws StageException { if (field.getType() != Field.Type.BYTE_ARRAY) { throw new StageException(CRYPTO_02, field.getType()); } return Optional.of(field); }
java
{ "resource": "" }
q172503
FieldEncrypter.prepareEncrypt
test
public byte[] prepareEncrypt(Field field, Map<String, String> context) { context.put(SDC_FIELD_TYPE, field.getType().name()); if (field.getType() == Field.Type.BYTE_ARRAY) { return field.getValueAsByteArray(); } else { // Treat all other data as strings return field.getValueAsString().getBytes(Charsets.UTF_8); } }
java
{ "resource": "" }
q172504
Matcher.usePattern
test
public Matcher usePattern(Pattern newPattern) { if (newPattern == null) { throw new IllegalArgumentException("newPattern cannot be null"); } this.parentPattern = newPattern; matcher.usePattern(newPattern.pattern()); return this; }
java
{ "resource": "" }
q172505
Matcher.appendReplacement
test
public Matcher appendReplacement(StringBuffer sb, String replacement) { matcher.appendReplacement(sb, parentPattern.replaceProperties(replacement)); return this; }
java
{ "resource": "" }
q172506
Matcher.namedGroups
test
@Override public Map<String, String> namedGroups() { Map<String, String> result = new LinkedHashMap<String, String>(); if (matcher.find(0)) { for (String groupName : parentPattern.groupNames()) { String groupValue = matcher.group(groupIndex(groupName)); result.put(groupName, groupValue); } } return result; }
java
{ "resource": "" }
q172507
Matcher.replaceAll
test
public String replaceAll(String replacement) { String r = parentPattern.replaceProperties(replacement); return matcher.replaceAll(r); }
java
{ "resource": "" }
q172508
DataFormatUpgradeHelper.ensureAvroSchemaExists
test
public static void ensureAvroSchemaExists(List<Config> configs, String prefix) { Optional<Config> avroSchema = findByName(configs, "avroSchema"); if (!avroSchema.isPresent()) { configs.add(new Config(prefix + ".avroSchema", null)); } }
java
{ "resource": "" }
q172509
Util.getGlobalVariable
test
public static String getGlobalVariable(DataSource dataSource, String variable) throws SQLException { try (Connection conn = dataSource.getConnection()) { try ( Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(String.format("show global variables like '%s'", variable)); ) { if (rs.next()) { return rs.getString(2); } else { return ""; } } } }
java
{ "resource": "" }
q172510
Pipeline.createStartEvent
test
private Record createStartEvent() { Preconditions.checkState(startEventStage != null, "Start Event Stage is not set!"); EventRecord eventRecord = new EventRecordImpl( "pipeline-start", 1, startEventStage.getInfo().getInstanceName(), "", null, null ); Map<String, Field> rootField = new LinkedHashMap<>(); rootField.put("user", Field.create(Field.Type.STRING, userContext.getUser())); rootField.put("pipelineId", Field.create(Field.Type.STRING, name)); rootField.put("pipelineTitle", Field.create(Field.Type.STRING, pipelineConf.getTitle())); // Pipeline parameters Map<String, Field> parameters = new LinkedHashMap<>(); if(runtimeParameters != null) { for (Map.Entry<String, Object> entry : runtimeParameters.entrySet()) { parameters.put( entry.getKey(), Field.create(Field.Type.STRING, entry.getValue().toString()) ); } } rootField.put("parameters", Field.create(parameters)); eventRecord.set(Field.create(rootField)); return eventRecord; }
java
{ "resource": "" }
q172511
Pipeline.createStopEvent
test
private Record createStopEvent(PipelineStopReason stopReason) { Preconditions.checkState(stopEventStage != null, "Stop Event Stage is not set!"); EventRecord eventRecord = new EventRecordImpl( "pipeline-stop", 1, stopEventStage.getInfo().getInstanceName(), "", null, null ); Map<String, Field> rootField = new LinkedHashMap<>(); rootField.put("reason", Field.create(Field.Type.STRING, stopReason.name())); rootField.put("pipelineId", Field.create(Field.Type.STRING, name)); rootField.put("pipelineTitle", Field.create(Field.Type.STRING, pipelineConf.getTitle())); eventRecord.set(Field.create(rootField)); return eventRecord; }
java
{ "resource": "" }
q172512
SobjectRecordCreator.fixOffset
test
protected String fixOffset(String offsetColumn, String offset) { com.sforce.soap.partner.Field sfdcField = getFieldMetadata(sobjectType, offsetColumn); if (SobjectRecordCreator.DECIMAL_TYPES.contains(sfdcField.getType().toString()) && offset.contains("E")) { BigDecimal val = new BigDecimal(offset); offset = val.toPlainString(); if (val.compareTo(MAX_OFFSET_INT) > 0 && !offset.contains(".")) { // We need the ".0" suffix since Salesforce doesn't like integer // bigger than 2147483647 offset += ".0"; } } return offset; }
java
{ "resource": "" }
q172513
ConfigValueExtractor.extractAsRuntime
test
private Object extractAsRuntime(Field field, String valueStr) { if (field.getType() == Byte.TYPE || field.getType() == Byte.class || field.getType() == Short.TYPE || field.getType() == Short.class || field.getType() == Integer.TYPE || field.getType() == Integer.class || field.getType() == Long.TYPE || field.getType() == Long.class || field.getType() == Float.TYPE || field.getType() == Float.class || field.getType() == Double.TYPE || field.getType() == Double.class) { return extractAsNumber(field, valueStr); } else if (String.class.isAssignableFrom(field.getType())) { return valueStr; } throw new IllegalArgumentException(Utils.format("Invalid type for RUNTIME type: {}", field.getType())); }
java
{ "resource": "" }
q172514
HiveQueryExecutor.executeAlterTableAddPartitionQuery
test
public void executeAlterTableAddPartitionQuery( String qualifiedTableName, LinkedHashMap<String, String> partitionNameValueMap, Map<String, HiveTypeInfo> partitionTypeMap, String partitionPath ) throws StageException { String sql = buildPartitionAdditionQuery(qualifiedTableName, partitionNameValueMap, partitionTypeMap, partitionPath); execute(sql); }
java
{ "resource": "" }
q172515
HiveQueryExecutor.executeAlterTableSetTblPropertiesQuery
test
public void executeAlterTableSetTblPropertiesQuery( String qualifiedTableName, String partitionPath ) throws StageException { String sql = buildSetTablePropertiesQuery(qualifiedTableName, partitionPath); execute(sql); }
java
{ "resource": "" }
q172516
HiveQueryExecutor.executeDescribeDatabase
test
public String executeDescribeDatabase(String dbName) throws StageException { String sql = buildDescribeDatabase(dbName); return executeQuery(sql, rs -> { if(!rs.next()) { throw new HiveStageCheckedException(Errors.HIVE_35, "Database doesn't exists."); } return HiveMetastoreUtil.stripHdfsHostAndPort(rs.getString(RESULT_SET_LOCATION)); }); }
java
{ "resource": "" }
q172517
HiveQueryExecutor.execute
test
private void execute(String query) throws StageException { LOG.debug("Executing SQL: {}", query); Timer.Context t = updateTimer.time(); try(Statement statement = hiveConfigBean.getHiveConnection().createStatement()) { statement.execute(query); } catch (Exception e) { LOG.error("Exception while processing query: {}", query, e); throw new HiveStageCheckedException(Errors.HIVE_20, query, e.getMessage()); } finally { long time = t.stop(); LOG.debug("Query '{}' took {} nanoseconds", query, time); updateMeter.mark(); } }
java
{ "resource": "" }
q172518
HiveQueryExecutor.executeQuery
test
private<T> T executeQuery(String query, WithResultSet<T> execution) throws StageException { LOG.debug("Executing SQL: {}", query); Timer.Context t = selectTimer.time(); try( Statement statement = hiveConfigBean.getHiveConnection().createStatement(); ResultSet rs = statement.executeQuery(query); ) { // Stop timer immediately so that we're calculating only query execution time and not the processing time long time = t.stop(); LOG.debug("Query '{}' took {} nanoseconds", query, time); t = null; return execution.run(rs); } catch(Exception e) { LOG.error("Exception while processing query: {}", query, e); throw new HiveStageCheckedException(Errors.HIVE_20, query, e.getMessage()); } finally { // If the timer wasn't stopped due to exception yet, stop it now if(t != null) { long time = t.stop(); LOG.debug("Query '{}' took {} nanoseconds", query, time); } selectMeter.mark(); } }
java
{ "resource": "" }
q172519
PipeRunner.executeBatch
test
public void executeBatch( String offsetKey, String offsetValue, long batchStartTime, ThrowingConsumer<Pipe> consumer ) throws PipelineRuntimeException, StageException { MDC.put(LogConstants.RUNNER, String.valueOf(runnerId)); // Persist static information for the batch (this won't change as the batch progresses) this.runtimeMetricGauge.put(METRIC_BATCH_START_TIME, batchStartTime); this.runtimeMetricGauge.put(METRIC_OFFSET_KEY, Optional.ofNullable(offsetKey).orElse("")); this.runtimeMetricGauge.put(METRIC_OFFSET_VALUE, Optional.ofNullable(offsetValue).orElse("")); this.runtimeMetricGauge.put(METRIC_STAGE_START_TIME, System.currentTimeMillis()); try { // Run one pipe at a time for(Pipe p : pipes) { String instanceName = p.getStage().getInfo().getInstanceName(); this.runtimeMetricGauge.put(METRIC_CURRENT_STAGE, instanceName); MDC.put(LogConstants.STAGE, instanceName); if (p instanceof StagePipe) { this.runtimeMetricGauge.put(METRIC_STAGE_START_TIME, System.currentTimeMillis()); } acceptConsumer(consumer, p); } // We've successfully finished batch this.runtimeMetricGauge.computeIfPresent(METRIC_BATCH_COUNT, (key, value) -> ((long)value) + 1); } finally { resetBatchSpecificMetrics(); MDC.put(LogConstants.RUNNER, ""); MDC.put(LogConstants.STAGE, ""); } }
java
{ "resource": "" }
q172520
PipeRunner.forEach
test
public void forEach(ThrowingConsumer<Pipe> consumer) { try { MDC.put(LogConstants.RUNNER, String.valueOf(runnerId)); try { for(Pipe p : pipes) { MDC.put(LogConstants.STAGE, p.getStage().getInfo().getInstanceName()); acceptConsumer(consumer, p); } } finally { MDC.put(LogConstants.RUNNER, ""); MDC.put(LogConstants.STAGE, ""); } } catch (PipelineException|StageException e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q172521
PipeRunner.getOffsetCommitTrigger
test
public OffsetCommitTrigger getOffsetCommitTrigger() { for (Pipe pipe : pipes) { Stage stage = pipe.getStage().getStage(); if (stage instanceof Target && stage instanceof OffsetCommitTrigger) { return (OffsetCommitTrigger) stage; } } return null; }
java
{ "resource": "" }
q172522
PipeRunner.onRecordErrorStopPipeline
test
public boolean onRecordErrorStopPipeline() { for(Pipe pipe : pipes) { StageContext stageContext = pipe.getStage().getContext(); if(stageContext.getOnErrorRecord() == OnRecordError.STOP_PIPELINE) { return true; } } return false; }
java
{ "resource": "" }
q172523
PipeRunner.acceptConsumer
test
private void acceptConsumer(ThrowingConsumer<Pipe> consumer, Pipe p) throws PipelineRuntimeException, StageException { try { // Process pipe consumer.accept(p); } catch (Throwable t) { String instanceName = p.getStage().getInfo().getInstanceName(); LOG.error("Failed executing stage '{}': {}", instanceName, t.toString(), t); Throwables.propagateIfInstanceOf(t, PipelineRuntimeException.class); Throwables.propagateIfInstanceOf(t, StageException.class); Throwables.propagate(t); } }
java
{ "resource": "" }
q172524
BigQueryTarget.getInsertIdForRecord
test
private String getInsertIdForRecord(ELVars elVars, Record record) throws OnRecordErrorException { String recordId = null; RecordEL.setRecordInContext(elVars, record); try { if (!(StringUtils.isEmpty(conf.rowIdExpression))) { recordId = rowIdELEval.eval(elVars, conf.rowIdExpression, String.class); if (StringUtils.isEmpty(recordId)) { throw new OnRecordErrorException(record, Errors.BIGQUERY_15); } } } catch (ELEvalException e) { LOG.error("Error evaluating Row Expression EL", e); throw new OnRecordErrorException(record, Errors.BIGQUERY_10,e); } return recordId; }
java
{ "resource": "" }
q172525
BigQueryTarget.getValueFromField
test
private Object getValueFromField(String fieldPath, Field field) { LOG.trace("Visiting Field Path '{}' of type '{}'", fieldPath, field.getType()); switch (field.getType()) { case LIST: //REPEATED List<Field> listField = field.getValueAsList(); //Convert the list to map with indices as key and Field as value (Map<Integer, Field>) Map<Integer, Field> fields = IntStream.range(0, listField.size()).boxed() .collect(Collectors.toMap(Function.identity(), listField::get)); //filter map to remove fields with null value fields = fields.entrySet().stream() .filter(e -> e.getValue().getValue() != null) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); //now use the map index to generate field path and generate object for big query write return fields.entrySet().stream() .map(e -> getValueFromField(fieldPath + "[" + e.getKey() + "]", e.getValue())) .collect(Collectors.toList()); case MAP: case LIST_MAP: //RECORD return field.getValueAsMap().entrySet().stream() .filter(me -> me.getValue().getValue() != null) .collect( Collectors.toMap( Map.Entry::getKey, e -> getValueFromField(fieldPath + "/" + e.getKey(), e.getValue()) ) ); case DATE: return dateFormat.format(field.getValueAsDate()); case TIME: return timeFormat.format(field.getValueAsTime()); case DATETIME: return dateTimeFormat.format(field.getValueAsDatetime()); case BYTE_ARRAY: return Base64.getEncoder().encodeToString(field.getValueAsByteArray()); case DECIMAL: case BYTE: case CHAR: case FILE_REF: throw new IllegalArgumentException(Utils.format(Errors.BIGQUERY_12.getMessage(), fieldPath, field.getType())); default: //Boolean -> Map to Boolean in big query //Float, Double -> Map to Float in big query //String -> maps to String in big query //Short, Integer, Long -> Map to integer in big query return field.getValue(); } }
java
{ "resource": "" }
q172526
CouchbaseProcessor.setFragmentInRecord
test
private Observable<Record> setFragmentInRecord(Record record, DocumentFragment<Lookup> frag) { if(frag.content(0) == null) { LOG.debug("Sub-document path not found"); return handleError(record, Errors.COUCHBASE_25, true); } for(SubdocMappingConfig subdocMapping : config.subdocMappingConfigs) { Object fragJson = frag.content(subdocMapping.subdocPath); if(fragJson == null) { return handleError(record, Errors.COUCHBASE_25, true); } try { record.set(subdocMapping.sdcField, jsonToField(fragJson)); record.getHeader().setAttribute(config.CAS_HEADER_ATTRIBUTE, String.valueOf(frag.cas())); } catch (IOException e) { try { record.set(subdocMapping.sdcField, jsonToField(JsonObject.fromJson(fragJson.toString()).toMap())); record.getHeader().setAttribute(config.CAS_HEADER_ATTRIBUTE, String.valueOf(frag.cas())); } catch (IOException ex) { return handleError(record, Errors.COUCHBASE_19, ex, false); } } } return Observable.just(record); }
java
{ "resource": "" }
q172527
CouchbaseProcessor.setDocumentInRecord
test
private Observable<Record> setDocumentInRecord(Record record, JsonDocument doc) { if(doc.content() == null) { LOG.debug("Document does not exist: {}", doc.id()); return handleError(record, Errors.COUCHBASE_26, true); } try { record.set(config.outputField, jsonToField(doc.content().toMap())); record.getHeader().setAttribute(config.CAS_HEADER_ATTRIBUTE, String.valueOf(doc.cas())); return Observable.just(record); } catch (IOException e) { LOG.debug("Unable to set KV lookup in record for: {}", doc.id()); return handleError(record, Errors.COUCHBASE_19, e, false); } }
java
{ "resource": "" }
q172528
CouchbaseProcessor.setN1QLRowInRecord
test
private Observable<Record> setN1QLRowInRecord(Record record, AsyncN1qlQueryRow row) { for(N1QLMappingConfig n1qlMapping : config.n1qlMappingConfigs) { if (config.multipleValueOperation == MultipleValueType.FIRST && record.get(n1qlMapping.sdcField) != null) { LOG.debug("Only populating output field with first record. Skipping additional result."); return Observable.empty(); } Object property = row.value().get(n1qlMapping.property); if (property == null) { LOG.debug("Requested property not returned: {}", n1qlMapping.property); return handleError(record, Errors.COUCHBASE_27, true); } try { record.set(n1qlMapping.sdcField, jsonToField(property)); } catch (IOException e) { try { record.set(n1qlMapping.sdcField, jsonToField(JsonObject.fromJson(property.toString()).toMap())); } catch (IOException ex) { LOG.debug("Unable to set N1QL property in record"); return handleError(record, Errors.COUCHBASE_19, ex, false); } } } return Observable.just(record); }
java
{ "resource": "" }
q172529
AmazonS3Runnable.handleWholeFileDataFormat
test
private void handleWholeFileDataFormat(S3ObjectSummary s3ObjectSummary, String recordId) throws StageException { S3Object partialS3ObjectForMetadata; //partialObject with fetchSize 1 byte. //This is mostly used for extracting metadata and such. partialS3ObjectForMetadata = AmazonS3Util.getObjectRange(s3Client, s3ConfigBean.s3Config.bucket, s3ObjectSummary.getKey(), 1, s3ConfigBean.sseConfig.useCustomerSSEKey, s3ConfigBean.sseConfig.customerKey, s3ConfigBean.sseConfig.customerKeyMd5 ); S3FileRef.Builder s3FileRefBuilder = new S3FileRef.Builder().s3Client(s3Client) .s3ObjectSummary(s3ObjectSummary) .useSSE(s3ConfigBean.sseConfig.useCustomerSSEKey) .customerKey(s3ConfigBean.sseConfig.customerKey) .customerKeyMd5(s3ConfigBean.sseConfig.customerKeyMd5) .bufferSize((int) dataParser.suggestedWholeFileBufferSize()) .createMetrics(true) .totalSizeInBytes(s3ObjectSummary.getSize()) .rateLimit(dataParser.wholeFileRateLimit()); if (dataParser.isWholeFileChecksumRequired()) { s3FileRefBuilder.verifyChecksum(true).checksumAlgorithm(HashingUtil.HashType.MD5) //128 bit hex encoded md5 checksum. .checksum(partialS3ObjectForMetadata.getObjectMetadata().getETag()); } Map<String, Object> metadata = AmazonS3Util.getMetaData(partialS3ObjectForMetadata); metadata.put(S3Constants.BUCKET, s3ObjectSummary.getBucketName()); metadata.put(S3Constants.OBJECT_KEY, s3ObjectSummary.getKey()); metadata.put(S3Constants.OWNER, s3ObjectSummary.getOwner()); metadata.put(S3Constants.SIZE, s3ObjectSummary.getSize()); metadata.put(HeaderAttributeConstants.FILE_NAME, s3ObjectSummary.getKey()); metadata.remove(S3Constants.CONTENT_LENGTH); parser = dataParser.getParser(recordId, metadata, s3FileRefBuilder.build()); //Object is assigned so that setHeaders() function can use this to get metadata //information about the object object = partialS3ObjectForMetadata; }
java
{ "resource": "" }
q172530
GtidSourceOffset.incompleteTransactionsContain
test
public boolean incompleteTransactionsContain(String gtid, long seqNo) { Long s = incompleteTransactions.get(gtid); return s != null && s >= seqNo; }
java
{ "resource": "" }
q172531
LambdaUtil.withClassLoaderInternal
test
private static <T> T withClassLoaderInternal( ClassLoader classLoader, ExceptionSupplier<T> supplier ) throws Exception { ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(classLoader); return supplier.get(); } finally { Thread.currentThread().setContextClassLoader(previousClassLoader); } }
java
{ "resource": "" }
q172532
HeaderImpl.setStageCreator
test
public void setStageCreator(String stateCreator) { Preconditions.checkNotNull(stateCreator, "stateCreator cannot be null"); map.put(STAGE_CREATOR_INSTANCE_ATTR, stateCreator); }
java
{ "resource": "" }
q172533
SecurityContext.logout
test
public synchronized void logout() { if (subject != null) { LOG.debug("Logout. Kerberos enabled '{}', Principal '{}'", securityConfiguration.isKerberosEnabled(), subject.getPrincipals()); if (loginContext != null) { try { loginContext.logout(); } catch (LoginException ex) { LOG.warn("Error while doing logout from Kerberos: {}", ex.toString(), ex); } finally { loginContext = null; } } subject = null; } }
java
{ "resource": "" }
q172534
SdcSecurityManager.setExceptions
test
private void setExceptions(Configuration configuration) { this.exceptions.clear(); this.stageLibExceptions.clear(); // Load general exceptions for(String path : configuration.get(PROPERTY_EXCEPTIONS, "").split(",")) { this.exceptions.add(replaceVariables(path)); } // Load Stage library specific exceptions Configuration stageSpecific = configuration.getSubSetConfiguration(PROPERTY_STAGE_EXCEPTIONS, true); for(Map.Entry<String, String> entry : stageSpecific.getValues().entrySet()) { Set<String> stageExceptions = new HashSet<>(); for(String path : entry.getValue().split(",")) { stageExceptions.add(replaceVariables(path)); } this.stageLibExceptions.put(entry.getKey(), stageExceptions); } }
java
{ "resource": "" }
q172535
SdcSecurityManager.replaceVariables
test
private String replaceVariables(String path) { return path.replace("$SDC_DATA", dataDir) .replace("$SDC_CONF", configDir) .replace("$SDC_RESOURCES", resourcesDir) ; }
java
{ "resource": "" }
q172536
SdcSecurityManager.ensureProperPermissions
test
private void ensureProperPermissions(String path) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); // 1) Container can access anything if(cl instanceof ContainerClassLoader) { return; } // 2. Some files are whitelisted globally for all stage libraries if(exceptions.contains(path)) { return; } // 3. Some stage libraries have some files whitelisted globally if(cl instanceof SDCClassLoader) { String libraryName = ((SDCClassLoader)cl).getName(); if(stageLibExceptions.containsKey(libraryName) && stageLibExceptions.get(libraryName).contains(path)) { return; } } // No whitelist, no fun, go away throw new SecurityException(Utils.format( "Classloader {} is not allowed access to Data Collector internal directories ({}).", cl.toString(), path )); }
java
{ "resource": "" }
q172537
BootstrapEmrBatch.main
test
public static void main(String[] args) throws Exception { EmrBinding binding = null; try { binding = new EmrBinding(args); binding.init(); binding.awaitTermination(); // killed by ClusterProviderImpl before returning } catch (Exception ex) { String msg = "Error trying to invoke BootstrapEmrBatch.main: " + ex; throw new IllegalStateException(msg, ex); } finally { try { if (binding != null) { binding.close(); } } catch (Exception ex) { LOG.warn("Error on binding close: " + ex, ex); } } }
java
{ "resource": "" }
q172538
RecordWriterManager.getDirPath
test
String getDirPath(Date date, Record record) throws StageException { if(dirPathTemplateInHeader) { // We're not validating if the header exists as that job is already done return record.getHeader().getAttribute(HdfsTarget.TARGET_DIRECTORY_HEADER); } return pathResolver.resolvePath(date, record); }
java
{ "resource": "" }
q172539
RecordWriterManager.renameToFinalName
test
Path renameToFinalName(FileSystem fs, Path tempPath) throws IOException, StageException { return fsHelper.renameAndGetPath(fs, tempPath); }
java
{ "resource": "" }
q172540
RecordWriterManager.shouldRoll
test
public boolean shouldRoll(RecordWriter writer, Record record) { if (rollIfHeader && record.getHeader().getAttribute(rollHeaderName) != null) { LOG.debug("Path[{}] - will be rolled because of roll attribute '{}' set to '{}' in the record : '{}'", writer.getPath(), rollHeaderName, record.getHeader().getAttribute(rollHeaderName), record.getHeader().getSourceId()); return true; } return false; }
java
{ "resource": "" }
q172541
AntPathMatcher.matchStrings
test
private boolean matchStrings(String pattern, String str, Map<String, String> uriTemplateVariables) { return getStringMatcher(pattern).matchStrings(str, uriTemplateVariables); }
java
{ "resource": "" }
q172542
MultiFileReader.getOffsets
test
public Map<String, String> getOffsets() throws IOException { Utils.checkState(open, "Not open"); return fileContextProvider.getOffsets(); }
java
{ "resource": "" }
q172543
MultiFileReader.getRemainingWaitTime
test
private long getRemainingWaitTime(long startTime, long maxWaitTimeMillis) { long remaining = maxWaitTimeMillis - (System.currentTimeMillis() - startTime); return (remaining > 0) ? remaining : 0; }
java
{ "resource": "" }
q172544
MultiFileReader.getOffsetsLag
test
public Map<String, Long> getOffsetsLag(Map<String, String> offsetMap) throws IOException{ return fileContextProvider.getOffsetsLag(offsetMap); }
java
{ "resource": "" }
q172545
StageLibraryDelegateCreator.createAndInitialize
test
public <R> R createAndInitialize( StageLibraryTask stageLib, Configuration configuration, String stageLibraryName, Class<R> exportedInterface ) { StageLibraryDelegate instance = create( stageLib, stageLibraryName, exportedInterface ); if(instance == null) { return null; } // Create & set context StageLibraryDelegateContext context = new StageLibraryDelegateContext( configuration ); instance.setContext(context); return (R)new StageLibraryDelegateRuntime( instance.getClass().getClassLoader(), instance ); }
java
{ "resource": "" }
q172546
StageLibraryDelegateCreator.create
test
public StageLibraryDelegate create( StageLibraryTask stageLib, String stageLibraryName, Class exportedInterface ) { StageLibraryDelegateDefinitition def = stageLib.getStageLibraryDelegateDefinition(stageLibraryName, exportedInterface); if(def == null) { return null; } return createInstance(def); }
java
{ "resource": "" }
q172547
StageLibraryDelegateCreator.createInstance
test
private StageLibraryDelegate createInstance(StageLibraryDelegateDefinitition def) { StageLibraryDelegate instance = null; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(def.getClassLoader()); instance = def.getKlass().newInstance(); } catch (InstantiationException | IllegalAccessException ex) { LOG.error("Can't create instance of delegator: " + ex.toString(), ex); } finally { Thread.currentThread().setContextClassLoader(classLoader); } return instance; }
java
{ "resource": "" }
q172548
MetricRuleEvaluatorHelper.getMetricValue
test
public static Object getMetricValue( MetricRegistry metrics, String metricId, MetricType metricType, MetricElement metricElement ) throws ObserverException { // We moved the logic of CURRENT_BATCH_AGE and TIME_IN_CURRENT_STAGE due to multi-threaded framework if(metricElement.isOneOf(MetricElement.CURRENT_BATCH_AGE, MetricElement.TIME_IN_CURRENT_STAGE)) { switch (metricElement) { case CURRENT_BATCH_AGE: return getTimeFromRunner(metrics, PipeRunner.METRIC_BATCH_START_TIME); case TIME_IN_CURRENT_STAGE: return getTimeFromRunner(metrics, PipeRunner.METRIC_STAGE_START_TIME); default: throw new IllegalStateException(Utils.format("Unknown metric type '{}'", metricType)); } } // Default path Metric metric = getMetric( metrics, metricId, metricType ); if(metric != null) { return getMetricValue(metricElement, metricType, metric); } return null; }
java
{ "resource": "" }
q172549
HTTPSession.findHeaderEnd
test
private int findHeaderEnd(final byte[] buf, int rlen) { int splitbyte = 0; while (splitbyte + 1 < rlen) { // RFC2616 if (buf[splitbyte] == '\r' && buf[splitbyte + 1] == '\n' && splitbyte + 3 < rlen && buf[splitbyte + 2] == '\r' && buf[splitbyte + 3] == '\n') { return splitbyte + 4; } // tolerance if (buf[splitbyte] == '\n' && buf[splitbyte + 1] == '\n') { return splitbyte + 2; } splitbyte++; } return 0; }
java
{ "resource": "" }
q172550
HTTPSession.getBodySize
test
public long getBodySize() { if (this.headers.containsKey("content-length")) { return Long.parseLong(this.headers.get("content-length")); } else if (this.splitbyte < this.rlen) { return this.rlen - this.splitbyte; } return 0; }
java
{ "resource": "" }
q172551
HTTPSession.saveTmpFile
test
private String saveTmpFile(ByteBuffer b, int offset, int len, String filename_hint) { String path = ""; if (len > 0) { FileOutputStream fileOutputStream = null; try { ITempFile tempFile = this.tempFileManager.createTempFile(filename_hint); ByteBuffer src = b.duplicate(); fileOutputStream = new FileOutputStream(tempFile.getName()); FileChannel dest = fileOutputStream.getChannel(); src.position(offset).limit(offset + len); dest.write(src.slice()); path = tempFile.getName(); } catch (Exception e) { // Catch exception if any throw new Error(e); // we won't recover, so throw an error } finally { NanoHTTPD.safeClose(fileOutputStream); } } return path; }
java
{ "resource": "" }
q172552
NanoHTTPD.makeSSLSocketFactory
test
public static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException { try { KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream keystoreStream = NanoHTTPD.class.getResourceAsStream(keyAndTrustStoreClasspathPath); if (keystoreStream == null) { throw new IOException("Unable to load keystore from classpath: " + keyAndTrustStoreClasspathPath); } keystore.load(keystoreStream, passphrase); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keystore, passphrase); return makeSSLSocketFactory(keystore, keyManagerFactory); } catch (Exception e) { throw new IOException(e.getMessage()); } }
java
{ "resource": "" }
q172553
NanoHTTPD.getMimeTypeForFile
test
public static String getMimeTypeForFile(String uri) { int dot = uri.lastIndexOf('.'); String mime = null; if (dot >= 0) { mime = mimeTypes().get(uri.substring(dot + 1).toLowerCase()); } return mime == null ? "application/octet-stream" : mime; }
java
{ "resource": "" }
q172554
NanoHTTPD.handle
test
public Response handle(IHTTPSession session) { for (IHandler<IHTTPSession, Response> interceptor : interceptors) { Response response = interceptor.handle(session); if (response != null) return response; } return httpHandler.handle(session); }
java
{ "resource": "" }
q172555
NanoHTTPD.stop
test
public void stop() { try { safeClose(this.myServerSocket); this.asyncRunner.closeAll(); if (this.myThread != null) { this.myThread.join(); } } catch (Exception e) { NanoHTTPD.LOG.log(Level.SEVERE, "Could not stop all connections", e); } }
java
{ "resource": "" }
q172556
RouterNanoHTTPD.addMappings
test
public void addMappings() { router.setNotImplemented(NotImplementedHandler.class); router.setNotFoundHandler(Error404UriHandler.class); router.addRoute("/", Integer.MAX_VALUE / 2, IndexHandler.class); router.addRoute("/index.html", Integer.MAX_VALUE / 2, IndexHandler.class); }
java
{ "resource": "" }
q172557
Response.send
test
public void send(OutputStream outputStream) { SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US); gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT")); try { if (this.status == null) { throw new Error("sendResponse(): Status can't be null."); } PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, new ContentType(this.mimeType).getEncoding())), false); pw.append("HTTP/1.1 ").append(this.status.getDescription()).append(" \r\n"); if (this.mimeType != null) { printHeader(pw, "Content-Type", this.mimeType); } if (getHeader("date") == null) { printHeader(pw, "Date", gmtFrmt.format(new Date())); } for (Entry<String, String> entry : this.header.entrySet()) { printHeader(pw, entry.getKey(), entry.getValue()); } for (String cookieHeader : this.cookieHeaders) { printHeader(pw, "Set-Cookie", cookieHeader); } if (getHeader("connection") == null) { printHeader(pw, "Connection", (this.keepAlive ? "keep-alive" : "close")); } if (getHeader("content-length") != null) { setUseGzip(false); } if (useGzipWhenAccepted()) { printHeader(pw, "Content-Encoding", "gzip"); setChunkedTransfer(true); } long pending = this.data != null ? this.contentLength : 0; if (this.requestMethod != Method.HEAD && this.chunkedTransfer) { printHeader(pw, "Transfer-Encoding", "chunked"); } else if (!useGzipWhenAccepted()) { pending = sendContentLengthHeaderIfNotAlreadyPresent(pw, pending); } pw.append("\r\n"); pw.flush(); sendBodyWithCorrectTransferAndEncoding(outputStream, pending); outputStream.flush(); NanoHTTPD.safeClose(this.data); } catch (IOException ioe) { NanoHTTPD.LOG.log(Level.SEVERE, "Could not send response to the client", ioe); } }
java
{ "resource": "" }
q172558
Response.sendBody
test
private void sendBody(OutputStream outputStream, long pending) throws IOException { long BUFFER_SIZE = 16 * 1024; byte[] buff = new byte[(int) BUFFER_SIZE]; boolean sendEverything = pending == -1; while (pending > 0 || sendEverything) { long bytesToRead = sendEverything ? BUFFER_SIZE : Math.min(pending, BUFFER_SIZE); int read = this.data.read(buff, 0, (int) bytesToRead); if (read <= 0) { break; } try { outputStream.write(buff, 0, read); } catch (Exception e) { if(this.data != null) { this.data.close(); } } if (!sendEverything) { pending -= read; } } }
java
{ "resource": "" }
q172559
Response.newFixedLengthResponse
test
public static Response newFixedLengthResponse(IStatus status, String mimeType, InputStream data, long totalBytes) { return new Response(status, mimeType, data, totalBytes); }
java
{ "resource": "" }
q172560
Response.useGzipWhenAccepted
test
public boolean useGzipWhenAccepted() { if (gzipUsage == GzipUsage.DEFAULT) return getMimeType() != null && (getMimeType().toLowerCase().contains("text/") || getMimeType().toLowerCase().contains("/json")); else return gzipUsage == GzipUsage.ALWAYS; }
java
{ "resource": "" }
q172561
CookieHandler.set
test
public void set(String name, String value, int expires) { this.queue.add(new Cookie(name, value, Cookie.getHTTPTime(expires))); }
java
{ "resource": "" }
q172562
CookieHandler.unloadQueue
test
public void unloadQueue(Response response) { for (Cookie cookie : this.queue) { response.addCookieHeader(cookie.getHTTPHeader()); } }
java
{ "resource": "" }
q172563
DefaultCookieSerializer.base64Decode
test
private String base64Decode(String base64Value) { try { byte[] decodedCookieBytes = Base64.getDecoder().decode(base64Value); return new String(decodedCookieBytes); } catch (Exception ex) { logger.debug("Unable to Base64 decode value: " + base64Value); return null; } }
java
{ "resource": "" }
q172564
DefaultCookieSerializer.base64Encode
test
private String base64Encode(String value) { byte[] encodedCookieBytes = Base64.getEncoder().encode(value.getBytes()); return new String(encodedCookieBytes); }
java
{ "resource": "" }
q172565
JdbcOperationsSessionRepository.setTableName
test
public void setTableName(String tableName) { Assert.hasText(tableName, "Table name must not be empty"); this.tableName = tableName.trim(); prepareQueries(); }
java
{ "resource": "" }
q172566
SpringSessionBackedSessionRegistry.name
test
protected String name(Object principal) { if (principal instanceof UserDetails) { return ((UserDetails) principal).getUsername(); } if (principal instanceof Principal) { return ((Principal) principal).getName(); } return principal.toString(); }
java
{ "resource": "" }
q172567
AbstractHttpSessionApplicationInitializer.insertSessionRepositoryFilter
test
private void insertSessionRepositoryFilter(ServletContext servletContext) { String filterName = DEFAULT_FILTER_NAME; DelegatingFilterProxy springSessionRepositoryFilter = new DelegatingFilterProxy( filterName); String contextAttribute = getWebApplicationContextAttribute(); if (contextAttribute != null) { springSessionRepositoryFilter.setContextAttribute(contextAttribute); } registerFilter(servletContext, true, filterName, springSessionRepositoryFilter); }
java
{ "resource": "" }
q172568
SpringSessionBackedSessionInformation.resolvePrincipal
test
private static String resolvePrincipal(Session session) { String principalName = session .getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME); if (principalName != null) { return principalName; } SecurityContext securityContext = session .getAttribute(SPRING_SECURITY_CONTEXT); if (securityContext != null && securityContext.getAuthentication() != null) { return securityContext.getAuthentication().getName(); } return ""; }
java
{ "resource": "" }
q172569
RedisOperationsSessionRepository.getSession
test
private RedisSession getSession(String id, boolean allowExpired) { Map<Object, Object> entries = getSessionBoundHashOperations(id).entries(); if (entries.isEmpty()) { return null; } MapSession loaded = loadSession(id, entries); if (!allowExpired && loaded.isExpired()) { return null; } RedisSession result = new RedisSession(loaded); result.originalLastAccessTime = loaded.getLastAccessedTime(); return result; }
java
{ "resource": "" }
q172570
MailSessionAdd.getJndiName
test
static String getJndiName(final ModelNode modelNode, OperationContext context) throws OperationFailedException { final String rawJndiName = MailSessionDefinition.JNDI_NAME.resolveModelAttribute(context, modelNode).asString(); return getJndiName(rawJndiName); }
java
{ "resource": "" }
q172571
MethodInfoHelper.getCanonicalParameterTypes
test
public static String[] getCanonicalParameterTypes(Method viewMethod) { Class<?>[] parameterTypes = viewMethod.getParameterTypes(); if (parameterTypes == null) { return NO_STRINGS; } String[] canonicalNames = new String[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { canonicalNames[i] = parameterTypes[i].getCanonicalName(); } return canonicalNames; }
java
{ "resource": "" }
q172572
JCAOrderedLastSynchronizationList.registerInterposedSynchronization
test
public void registerInterposedSynchronization(Synchronization synchronization) throws IllegalStateException, SystemException { int status = ContextTransactionSynchronizationRegistry.getInstance().getTransactionStatus(); switch (status) { case javax.transaction.Status.STATUS_ACTIVE: case javax.transaction.Status.STATUS_PREPARING: break; case Status.STATUS_MARKED_ROLLBACK: // do nothing; we can pretend like it was registered, but it'll never be run anyway. return; default: throw TransactionLogger.ROOT_LOGGER.syncsnotallowed(status); } if (synchronization.getClass().getName().startsWith("org.jboss.jca")) { if (TransactionLogger.ROOT_LOGGER.isTraceEnabled()) { TransactionLogger.ROOT_LOGGER.trace("JCAOrderedLastSynchronizationList.jcaSyncs.add - Class: " + synchronization.getClass() + " HashCode: " + synchronization.hashCode() + " toString: " + synchronization); } jcaSyncs.add(synchronization); } else { if (TransactionLogger.ROOT_LOGGER.isTraceEnabled()) { TransactionLogger.ROOT_LOGGER.trace("JCAOrderedLastSynchronizationList.preJcaSyncs.add - Class: " + synchronization.getClass() + " HashCode: " + synchronization.hashCode() + " toString: " + synchronization); } preJcaSyncs.add(synchronization); } }
java
{ "resource": "" }
q172573
JCAOrderedLastSynchronizationList.beforeCompletion
test
@Override public void beforeCompletion() { // This is needed to guard against syncs being registered during the run, otherwise we could have used an iterator int lastIndexProcessed = 0; while ((lastIndexProcessed < preJcaSyncs.size())) { Synchronization preJcaSync = preJcaSyncs.get(lastIndexProcessed); if (TransactionLogger.ROOT_LOGGER.isTraceEnabled()) { TransactionLogger.ROOT_LOGGER.trace("JCAOrderedLastSynchronizationList.preJcaSyncs.before_completion - Class: " + preJcaSync.getClass() + " HashCode: " + preJcaSync.hashCode() + " toString: " + preJcaSync); } preJcaSync.beforeCompletion(); lastIndexProcessed = lastIndexProcessed + 1; } // Do the same for the jca syncs lastIndexProcessed = 0; while ((lastIndexProcessed < jcaSyncs.size())) { Synchronization jcaSync = jcaSyncs.get(lastIndexProcessed); if (TransactionLogger.ROOT_LOGGER.isTraceEnabled()) { TransactionLogger.ROOT_LOGGER.trace("JCAOrderedLastSynchronizationList.jcaSyncs.before_completion - Class: " + jcaSync.getClass() + " HashCode: " + jcaSync.hashCode() + " toString: " + jcaSync); } jcaSync.beforeCompletion(); lastIndexProcessed = lastIndexProcessed + 1; } }
java
{ "resource": "" }
q172574
TxServerInterceptor.getCurrentTransaction
test
public static Transaction getCurrentTransaction() { Transaction tx = null; if (piCurrent != null) { // A non-null piCurrent means that a TxServerInterceptor was // installed: check if there is a transaction propagation context try { Any any = piCurrent.get_slot(slotId); if (any.type().kind().value() != TCKind._tk_null) { // Yes, there is a TPC: add the foreign transaction marker tx = ForeignTransaction.INSTANCE; } } catch (InvalidSlot e) { throw IIOPLogger.ROOT_LOGGER.errorGettingSlotInTxInterceptor(e); } } return tx; }
java
{ "resource": "" }
q172575
KernelDeploymentModuleProcessor.deploy
test
@Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit unit = phaseContext.getDeploymentUnit(); final List<KernelDeploymentXmlDescriptor> kdXmlDescriptors = unit.getAttachment(KernelDeploymentXmlDescriptor.ATTACHMENT_KEY); if (kdXmlDescriptors == null || kdXmlDescriptors.isEmpty()) return; for (KernelDeploymentXmlDescriptor kdxd : kdXmlDescriptors) { if (kdxd.getBeanFactoriesCount() > 0) { final ModuleSpecification moduleSpecification = unit.getAttachment(Attachments.MODULE_SPECIFICATION); final ModuleLoader moduleLoader = Module.getBootModuleLoader(); ModuleDependency dependency = new ModuleDependency(moduleLoader, POJO_MODULE, false, false, false, false); PathFilter filter = PathFilters.isChildOf(BaseBeanFactory.class.getPackage().getName()); dependency.addImportFilter(filter, true); dependency.addImportFilter(PathFilters.rejectAll(), false); moduleSpecification.addSystemDependency(dependency); return; } } }
java
{ "resource": "" }
q172576
HibernatePersistenceProviderAdaptor.doesScopedPersistenceUnitNameIdentifyCacheRegionName
test
@Override public boolean doesScopedPersistenceUnitNameIdentifyCacheRegionName(PersistenceUnitMetadata pu) { String cacheRegionPrefix = pu.getProperties().getProperty(AvailableSettings.CACHE_REGION_PREFIX); return cacheRegionPrefix == null || cacheRegionPrefix.equals(pu.getScopedPersistenceUnitName()); }
java
{ "resource": "" }
q172577
WSSubsystemAdd.getServerConfigDependencies
test
private static List<ServiceName> getServerConfigDependencies(OperationContext context, boolean appclient) { final List<ServiceName> serviceNames = new ArrayList<ServiceName>(); final Resource subsystemResource = context.readResourceFromRoot(PathAddress.pathAddress(WSExtension.SUBSYSTEM_PATH), false); readConfigServiceNames(serviceNames, subsystemResource, Constants.CLIENT_CONFIG); readConfigServiceNames(serviceNames, subsystemResource, Constants.ENDPOINT_CONFIG); if (!appclient) { serviceNames.add(CommonWebServer.SERVICE_NAME); } return serviceNames; }
java
{ "resource": "" }
q172578
EJBReadWriteLock.decReadLockCount
test
private void decReadLockCount() { Integer current = readLockCount.get(); int next; assert current != null : "can't decrease, readLockCount is not set"; next = current.intValue() - 1; if (next == 0) readLockCount.remove(); else readLockCount.set(new Integer(next)); }
java
{ "resource": "" }
q172579
EJBReadWriteLock.incReadLockCount
test
private void incReadLockCount() { Integer current = readLockCount.get(); int next; if (current == null) next = 1; else next = current.intValue() + 1; readLockCount.set(new Integer(next)); }
java
{ "resource": "" }
q172580
BeanDeploymentModule.addService
test
public synchronized <S extends Service> void addService(Class<S> clazz, S service) { for (BeanDeploymentArchiveImpl bda : beanDeploymentArchives) { bda.getServices().add(clazz,service); } }
java
{ "resource": "" }
q172581
CalendarTimer.handleRestorationCalculation
test
public void handleRestorationCalculation() { if(nextExpiration == null) { return; } //next expiration in the future, we don't care if(nextExpiration.getTime() >= System.currentTimeMillis()) { return; } //just set the next expiration to 1ms in the past //this means it will run to catch up the missed expiration //and then the next calculated expiration will be in the future nextExpiration = new Date(System.currentTimeMillis() - 1); }
java
{ "resource": "" }
q172582
HibernateSearchProcessor.deploy
test
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); final ModuleLoader moduleLoader = Module.getBootModuleLoader(); if (JPADeploymentMarker.isJPADeployment(deploymentUnit)) { addSearchDependency(moduleSpecification, moduleLoader, deploymentUnit); } }
java
{ "resource": "" }
q172583
WeldDeployment.makeTopLevelBdasVisibleFromStaticModules
test
private void makeTopLevelBdasVisibleFromStaticModules() { for (BeanDeploymentArchiveImpl bda : beanDeploymentArchives) { if (bda.getBeanArchiveType().equals(BeanDeploymentArchiveImpl.BeanArchiveType.EXTERNAL) || bda.getBeanArchiveType().equals(BeanDeploymentArchiveImpl.BeanArchiveType.SYNTHETIC)) { for (BeanDeploymentArchiveImpl topLevelBda : rootBeanDeploymentModule.getBeanDeploymentArchives()) { bda.addBeanDeploymentArchive(topLevelBda); } } } }
java
{ "resource": "" }
q172584
AbstractMetaDataBuilderPOJO.create
test
JSEArchiveMetaData create(final Deployment dep) { if (WSLogger.ROOT_LOGGER.isTraceEnabled()) { WSLogger.ROOT_LOGGER.tracef("Creating JBoss agnostic meta data for POJO webservice deployment: %s", dep.getSimpleName()); } final JBossWebMetaData jbossWebMD = WSHelper.getRequiredAttachment(dep, JBossWebMetaData.class); final DeploymentUnit unit = WSHelper.getRequiredAttachment(dep, DeploymentUnit.class); final List<POJOEndpoint> pojoEndpoints = getPojoEndpoints(unit); final JSEArchiveMetaData.Builder builder = new JSEArchiveMetaData.Builder(); // set context root final String contextRoot = getContextRoot(dep, jbossWebMD); builder.setContextRoot(contextRoot); WSLogger.ROOT_LOGGER.tracef("Setting context root: %s", contextRoot); // set servlet url patterns mappings final Map<String, String> servletMappings = getServletUrlPatternsMappings(jbossWebMD, pojoEndpoints); builder.setServletMappings(servletMappings); // set servlet class names mappings final Map<String, String> servletClassNamesMappings = getServletClassMappings(jbossWebMD, pojoEndpoints); builder.setServletClassNames(servletClassNamesMappings); // set security domain final String securityDomain = jbossWebMD.getSecurityDomain(); builder.setSecurityDomain(securityDomain); // set wsdl location resolver final JBossWebservicesMetaData jbossWebservicesMD = WSHelper.getOptionalAttachment(dep, JBossWebservicesMetaData.class); if (jbossWebservicesMD != null) { final PublishLocationAdapter resolver = new PublishLocationAdapterImpl(jbossWebservicesMD.getWebserviceDescriptions()); builder.setPublishLocationAdapter(resolver); } // set security meta data final List<JSESecurityMetaData> jseSecurityMDs = getSecurityMetaData(jbossWebMD.getSecurityConstraints()); builder.setSecurityMetaData(jseSecurityMDs); // set config name and file setConfigNameAndFile(builder, jbossWebMD, jbossWebservicesMD); return builder.build(); }
java
{ "resource": "" }
q172585
AbstractMetaDataBuilderPOJO.setConfigNameAndFile
test
private void setConfigNameAndFile(final JSEArchiveMetaData.Builder builder, final JBossWebMetaData jbossWebMD, final JBossWebservicesMetaData jbossWebservicesMD) { if (jbossWebservicesMD != null) { if (jbossWebservicesMD.getConfigName() != null) { final String configName = jbossWebservicesMD.getConfigName(); builder.setConfigName(configName); WSLogger.ROOT_LOGGER.tracef("Setting config name: %s", configName); final String configFile = jbossWebservicesMD.getConfigFile(); builder.setConfigFile(configFile); WSLogger.ROOT_LOGGER.tracef("Setting config file: %s", configFile); // ensure higher priority against web.xml context parameters return; } } final List<ParamValueMetaData> contextParams = jbossWebMD.getContextParams(); if (contextParams != null) { for (final ParamValueMetaData contextParam : contextParams) { if (WSConstants.JBOSSWS_CONFIG_NAME.equals(contextParam.getParamName())) { final String configName = contextParam.getParamValue(); builder.setConfigName(configName); WSLogger.ROOT_LOGGER.tracef("Setting config name: %s", configName); } if (WSConstants.JBOSSWS_CONFIG_FILE.equals(contextParam.getParamName())) { final String configFile = contextParam.getParamValue(); builder.setConfigFile(configFile); WSLogger.ROOT_LOGGER.tracef("Setting config file: %s", configFile); } } } }
java
{ "resource": "" }
q172586
AbstractMetaDataBuilderPOJO.getSecurityMetaData
test
private List<JSESecurityMetaData> getSecurityMetaData(final List<SecurityConstraintMetaData> securityConstraintsMD) { final List<JSESecurityMetaData> jseSecurityMDs = new LinkedList<JSESecurityMetaData>(); if (securityConstraintsMD != null) { for (final SecurityConstraintMetaData securityConstraintMD : securityConstraintsMD) { final JSESecurityMetaData.Builder jseSecurityMDBuilder = new JSESecurityMetaData.Builder(); // transport guarantee jseSecurityMDBuilder.setTransportGuarantee(securityConstraintMD.getTransportGuarantee().name()); // web resources for (final WebResourceCollectionMetaData webResourceMD : securityConstraintMD.getResourceCollections()) { jseSecurityMDBuilder.addWebResource(webResourceMD.getName(), webResourceMD.getUrlPatterns()); } jseSecurityMDs.add(jseSecurityMDBuilder.build()); } } return jseSecurityMDs; }
java
{ "resource": "" }
q172587
AbstractMetaDataBuilderPOJO.getServletUrlPatternsMappings
test
private Map<String, String> getServletUrlPatternsMappings(final JBossWebMetaData jbossWebMD, final List<POJOEndpoint> pojoEndpoints) { final Map<String, String> mappings = new HashMap<String, String>(); final List<ServletMappingMetaData> servletMappings = WebMetaDataHelper.getServletMappings(jbossWebMD); for (final POJOEndpoint pojoEndpoint : pojoEndpoints) { mappings.put(pojoEndpoint.getName(), pojoEndpoint.getUrlPattern()); if (!pojoEndpoint.isDeclared()) { final String endpointName = pojoEndpoint.getName(); final List<String> urlPatterns = WebMetaDataHelper.getUrlPatterns(pojoEndpoint.getUrlPattern()); WebMetaDataHelper.newServletMapping(endpointName, urlPatterns, servletMappings); } } return mappings; }
java
{ "resource": "" }
q172588
AbstractMetaDataBuilderPOJO.getServletClassMappings
test
private Map<String, String> getServletClassMappings(final JBossWebMetaData jbossWebMD, final List<POJOEndpoint> pojoEndpoints) { final Map<String, String> mappings = new HashMap<String, String>(); final JBossServletsMetaData servlets = WebMetaDataHelper.getServlets(jbossWebMD); for (final POJOEndpoint pojoEndpoint : pojoEndpoints) { final String pojoName = pojoEndpoint.getName(); final String pojoClassName = pojoEndpoint.getClassName(); mappings.put(pojoName, pojoClassName); if (!pojoEndpoint.isDeclared()) { final String endpointName = pojoEndpoint.getName(); final String endpointClassName = pojoEndpoint.getClassName(); WebMetaDataHelper.newServlet(endpointName, endpointClassName, servlets); } } return mappings; }
java
{ "resource": "" }
q172589
EjbInjectionSource.resolve
test
private void resolve() { if (!resolved) { synchronized (this) { if (!resolved) { final Set<ViewDescription> views = getViews(); final Set<EJBViewDescription> ejbsForViewName = new HashSet<EJBViewDescription>(); for (final ViewDescription view : views) { if (view instanceof EJBViewDescription) { final MethodIntf viewType = ((EJBViewDescription) view).getMethodIntf(); // @EJB injection *shouldn't* consider the @WebService endpoint view or MDBs if (viewType == MethodIntf.SERVICE_ENDPOINT || viewType == MethodIntf.MESSAGE_ENDPOINT) { continue; } ejbsForViewName.add((EJBViewDescription) view); } } if (ejbsForViewName.isEmpty()) { if (beanName == null) { error = EjbLogger.ROOT_LOGGER.ejbNotFound(typeName, bindingName); } else { error = EjbLogger.ROOT_LOGGER.ejbNotFound(typeName, beanName, bindingName); } } else if (ejbsForViewName.size() > 1) { if (beanName == null) { error = EjbLogger.ROOT_LOGGER.moreThanOneEjbFound(typeName, bindingName, ejbsForViewName); } else { error = EjbLogger.ROOT_LOGGER.moreThanOneEjbFound(typeName, beanName, bindingName, ejbsForViewName); } } else { final EJBViewDescription description = ejbsForViewName.iterator().next(); final EJBViewDescription ejbViewDescription = (EJBViewDescription) description; //for remote interfaces we do not want to use a normal binding //we need to bind the remote proxy factory into JNDI instead to get the correct behaviour if (ejbViewDescription.getMethodIntf() == MethodIntf.REMOTE || ejbViewDescription.getMethodIntf() == MethodIntf.HOME) { final EJBComponentDescription componentDescription = (EJBComponentDescription) description.getComponentDescription(); final EEModuleDescription moduleDescription = componentDescription.getModuleDescription(); final String earApplicationName = moduleDescription.getEarApplicationName(); final Value<ClassLoader> viewClassLoader = new Value<ClassLoader>() { @Override public ClassLoader getValue() throws IllegalStateException, IllegalArgumentException { final Module module = deploymentUnit.getAttachment(Attachments.MODULE); return module != null ? module.getClassLoader() : null; } }; remoteFactory = new RemoteViewManagedReferenceFactory(earApplicationName, moduleDescription.getModuleName(), moduleDescription.getDistinctName(), componentDescription.getComponentName(), description.getViewClassName(), componentDescription.isStateful(), viewClassLoader, appclient); } final ServiceName serviceName = description.getServiceName(); resolvedViewName = serviceName; } resolved = true; } } } }
java
{ "resource": "" }
q172590
BroadcastGroupDefinition.getAvailableConnectors
test
private static Set<String> getAvailableConnectors(final OperationContext context,final ModelNode operation) throws OperationFailedException{ PathAddress address = PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)); PathAddress active = MessagingServices.getActiveMQServerPathAddress(address); Set<String> availableConnectors = new HashSet<String>(); Resource subsystemResource = context.readResourceFromRoot(active.getParent(), false); availableConnectors.addAll(subsystemResource.getChildrenNames(CommonAttributes.REMOTE_CONNECTOR)); Resource activeMQServerResource = context.readResourceFromRoot(active, false); availableConnectors.addAll(activeMQServerResource.getChildrenNames(CommonAttributes.HTTP_CONNECTOR)); availableConnectors.addAll(activeMQServerResource.getChildrenNames(CommonAttributes.IN_VM_CONNECTOR)); availableConnectors.addAll(activeMQServerResource.getChildrenNames(CommonAttributes.REMOTE_CONNECTOR)); availableConnectors.addAll(activeMQServerResource.getChildrenNames(CommonAttributes.CONNECTOR)); return availableConnectors; }
java
{ "resource": "" }
q172591
TransactionSubsystem10Parser.parseCoreEnvironmentElement
test
static void parseCoreEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException { final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case NODE_IDENTIFIER: TransactionSubsystemRootResourceDefinition.NODE_IDENTIFIER.parseAndSetParameter(value, operation, reader); break; case PATH: case RELATIVE_TO: throw TransactionLogger.ROOT_LOGGER.unsupportedAttribute(attribute.getLocalName(), reader.getLocation()); default: throw unexpectedAttribute(reader, i); } } // elements final EnumSet<Element> required = EnumSet.of(Element.PROCESS_ID); final EnumSet<Element> encountered = EnumSet.noneOf(Element.class); while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { final Element element = Element.forName(reader.getLocalName()); required.remove(element); switch (element) { case PROCESS_ID: { if (!encountered.add(element)) { throw duplicateNamedElement(reader, reader.getLocalName()); } parseProcessIdEnvironmentElement(reader, operation); break; } default: throw unexpectedElement(reader); } } if (!required.isEmpty()) { throw missingRequiredElement(reader, required); } }
java
{ "resource": "" }
q172592
TransactionSubsystem10Parser.parseProcessIdEnvironmentElement
test
static void parseProcessIdEnvironmentElement(XMLExtendedStreamReader reader, ModelNode coreEnvironmentAdd) throws XMLStreamException { // no attributes if (reader.getAttributeCount() > 0) { throw unexpectedAttribute(reader, 0); } // elements boolean encountered = false; while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { final Element element = Element.forName(reader.getLocalName()); switch (element) { case UUID: if (encountered) { throw unexpectedElement(reader); } encountered = true; if (reader.getAttributeCount() > 0) { throw unexpectedAttribute(reader, 0); } coreEnvironmentAdd.get(TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName()).set(true); requireNoContent(reader); break; case SOCKET: { if (encountered) { throw unexpectedElement(reader); } encountered = true; parseSocketProcessIdElement(reader, coreEnvironmentAdd); break; } default: throw unexpectedElement(reader); } } if (!encountered) { throw missingOneOf(reader, EnumSet.of(Element.UUID, Element.SOCKET)); } }
java
{ "resource": "" }
q172593
Operations.getPathAddress
test
public static PathAddress getPathAddress(ModelNode operation) { return PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR)); }
java
{ "resource": "" }
q172594
Operations.setPathAddress
test
public static void setPathAddress(ModelNode operation, PathAddress address) { operation.get(ModelDescriptionConstants.OP_ADDR).set(address.toModelNode()); }
java
{ "resource": "" }
q172595
Operations.getAttributeValue
test
public static ModelNode getAttributeValue(ModelNode operation) { return operation.hasDefined(ModelDescriptionConstants.VALUE) ? operation.get(ModelDescriptionConstants.VALUE) : new ModelNode(); }
java
{ "resource": "" }
q172596
Operations.isIncludeDefaults
test
public static boolean isIncludeDefaults(ModelNode operation) { return operation.hasDefined(ModelDescriptionConstants.INCLUDE_DEFAULTS) ? operation.get(ModelDescriptionConstants.INCLUDE_DEFAULTS).asBoolean() : true; }
java
{ "resource": "" }
q172597
Operations.createCompositeOperation
test
public static ModelNode createCompositeOperation(List<ModelNode> operations) { ModelNode operation = Util.createOperation(ModelDescriptionConstants.COMPOSITE, PathAddress.EMPTY_ADDRESS); ModelNode steps = operation.get(ModelDescriptionConstants.STEPS); for (ModelNode step: operations) { steps.add(step); } return operation; }
java
{ "resource": "" }
q172598
Operations.createAddOperation
test
public static ModelNode createAddOperation(PathAddress address, Map<Attribute, ModelNode> parameters) { ModelNode operation = Util.createAddOperation(address); for (Map.Entry<Attribute, ModelNode> entry : parameters.entrySet()) { operation.get(entry.getKey().getName()).set(entry.getValue()); } return operation; }
java
{ "resource": "" }
q172599
Operations.createAddOperation
test
public static ModelNode createAddOperation(PathAddress address, int index) { return createAddOperation(address, index, Collections.emptyMap()); }
java
{ "resource": "" }