auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void consume(String message) { logger.info("[MQ] receive message: {}: {}.", this.queue(), message); if (Strings.isNullOrEmpty(message)) { logger.error("[MQ] message is empty"); return; } try { InvestSuccessMessage investSuccessMessage = JsonConverter.readValue(message, InvestSuccessMessage.class); UserInfo userInfo = investSuccessMessage.getUserInfo(); InvestInfo investInfo = investSuccessMessage.getInvestInfo(); LoanDetailInfo loanDetailInfo = investSuccessMessage.getLoanDetailInfo(); if (duringActivities() && loanDetailInfo.isActivity() && loanDetailInfo.getActivityDesc().equals("早鸟专享")){ schoolExclusive(userInfo, investInfo, loanDetailInfo); } if (duringActivities() && !loanDetailInfo.getActivityType().equals("NEWBIE") && !investInfo.getTransferStatus().equals("SUCCESS") && investInfo.getStatus().equals("SUCCESS")) { activityInvestMapper.create(new ActivityInvestModel(investInfo.getInvestId(), userInfo.getLoginName(), userInfo.getUserName(), userInfo.getMobile(), investInfo.getAmount(), ActivityCategory.SCHOOL_SEASON_ACTIVITY.name())); } } catch (IOException e) { logger.error("[MQ] parse message failed: {}: {}.", this.queue(), message); } }

Target:
public void consume(String message) { logger.info("[MQ] receive message: {}: {}.", this.queue(), message); if (Strings.isNullOrEmpty(message)) { logger.error("[MQ] message is empty"); return; } Date date=DateTime.now().toDate(); if(!date.before(activitySchoolSeasonEndTime) || !date.after(activitySchoolSeasonStartTime)){ return; } try { InvestSuccessMessage investSuccessMessage = JsonConverter.readValue(message, InvestSuccessMessage.class); UserInfo userInfo = investSuccessMessage.getUserInfo(); InvestInfo investInfo = investSuccessMessage.getInvestInfo(); LoanDetailInfo loanDetailInfo = investSuccessMessage.getLoanDetailInfo(); if (loanDetailInfo.isActivity() && loanDetailInfo.getActivityDesc().equals("早鸟专享")){ schoolExclusive(userInfo, investInfo, loanDetailInfo); } if (!loanDetailInfo.getActivityType().equals("NEWBIE") && !investInfo.getTransferStatus().equals("SUCCESS") && investInfo.getStatus().equals("SUCCESS")) { activityInvestMapper.create(new ActivityInvestModel(investInfo.getInvestId(), userInfo.getLoginName(), userInfo.getUserName(), userInfo.getMobile(), investInfo.getAmount(), ActivityCategory.SCHOOL_SEASON_ACTIVITY.name())); } } catch (IOException e) { logger.error("[MQ] parse message failed: {}: {}.", this.queue(), message); } }
Source:
private void saturateCluster(FSSchedulerNode schedulerNode) { while (!Resources.isNone(schedulerNode.getUnallocatedResource())) { createDefaultContainer(); schedulerNode.allocateContainer(containers.get((int)containerNum - 1)); schedulerNode.containerStarted(containers.get((int)containerNum - 1). getContainerId()); } }

Target:
private void saturateCluster(FSSchedulerNode schedulerNode) { while (!Resources.isNone(schedulerNode.getUnallocatedResource())) { createDefaultContainer(); schedulerNode.allocateContainer(containers.get(containers.size() - 1)); schedulerNode.containerStarted(containers.get(containers.size() - 1). getContainerId()); } }
Source:
public static Driver getNextAvailableDriverFromPool() { if (driverPool.isEmpty()) { driverPool.add(new DriverSetup().instantiateDriver()); } return driverPool.remove(); }

Target:
private static Driver getNextAvailableDriverFromPool() { return driverPool.remove(); }
Source:
public Message<?> getMessage(UUID messageId) { Assert.notNull(messageId, "'messageId' must not be null"); MessageHolder messageHolder = (MessageHolder) doRetrieve(MESSAGE_KEY_PREFIX + messageId); if (messageHolder != null) { Assert.isInstanceOf(MessageHolder.class, messageHolder); return messageHolder.getMessage(); } else { return null; } }

Target:
public Message<?> getMessage(UUID messageId) { Assert.notNull(messageId, "'messageId' must not be null"); Object object = doRetrieve(MESSAGE_KEY_PREFIX + messageId); if (object != null) { return extractMessage(object); } else { return null; } }
Source:
public void call() { for (String threadToIgnore : this.threadsToIgnore) { if (Thread.currentThread().getName().matches(threadToIgnore)) { log.debug("Thread with name [" + Thread.currentThread().getName() +"] matches the " + "regex [" + threadToIgnore + "]. A span will not be created for this Thread."); this.actual.call(); return; } } Span span = this.parent; boolean created = false; if (span != null) { span = this.tracer.continueSpan(span); } else { span = this.tracer.createSpan(RXJAVA_COMPONENT); this.tracer.addTag(Span.SPAN_LOCAL_COMPONENT_TAG_NAME, RXJAVA_COMPONENT); this.tracer.addTag(this.traceKeys.getAsync().getPrefix() + this.traceKeys.getAsync().getThreadNameKey(), Thread.currentThread().getName()); created = true; } try { this.actual.call(); } finally { if (created) { this.tracer.close(span); } else { this.tracer.detach(span); } } }

Target:
public void call() { for (String threadToIgnore : this.threadsToIgnore) { String threadName = Thread.currentThread().getName(); if (threadName.matches(threadToIgnore)) { log.debug(String.format( "Thread with name [%s] matches the regex [%s]. A span will not be created for this Thread.", threadName, threadToIgnore)); this.actual.call(); return; } } Span span = this.parent; boolean created = false; if (span != null) { span = this.tracer.continueSpan(span); } else { span = this.tracer.createSpan(RXJAVA_COMPONENT); this.tracer.addTag(Span.SPAN_LOCAL_COMPONENT_TAG_NAME, RXJAVA_COMPONENT); this.tracer.addTag(this.traceKeys.getAsync().getPrefix() + this.traceKeys.getAsync().getThreadNameKey(), Thread.currentThread().getName()); created = true; } try { this.actual.call(); } finally { if (created) { this.tracer.close(span); } else { this.tracer.detach(span); } } }
Source:
public Result onResponse(Result result, Invoker<?> invoker, Invocation invocation) { String startAttach = invocation.getAttachment(TIMEOUT_FILTER_START_TIME); if (startAttach != null) { long elapsed = System.currentTimeMillis() - Long.valueOf(startAttach); if (invoker.getUrl() != null && elapsed > invoker.getUrl().getMethodParameter(invocation.getMethodName(), "timeout", Integer.MAX_VALUE)) { if (logger.isWarnEnabled()) { logger.warn("invoke time out. method: " + invocation.getMethodName() + " arguments: " + Arrays.toString(invocation.getArguments()) + " , url is " + invoker.getUrl() + ", invoke elapsed " + elapsed + " ms."); } } invocation.getAttachments().remove(TIMEOUT_FILTER_START_TIME); } return result; }

Target:
public Result onResponse(Result result, Invoker<?> invoker, Invocation invocation) { String startAttach = invocation.getAttachment(TIMEOUT_FILTER_START_TIME); if (startAttach != null) { long elapsed = System.currentTimeMillis() - Long.valueOf(startAttach); if (invoker.getUrl() != null && elapsed > invoker.getUrl().getMethodParameter(invocation.getMethodName(), "timeout", Integer.MAX_VALUE)) { if (logger.isWarnEnabled()) { logger.warn("invoke time out. method: " + invocation.getMethodName() + " arguments: " + Arrays.toString(invocation.getArguments()) + " , url is " + invoker.getUrl() + ", invoke elapsed " + elapsed + " ms."); } } } return result; }
Source:
public void validateCertificate(X509Certificate certificate, PKI.CAType caType) throws IOException { File tmpCertFile = File.createTempFile("cert-", ".pem"); try (FileWriter fw = new FileWriter(tmpCertFile, false)) { fw.write(X509Factory.BEGIN_CERT); fw.write("\n"); fw.write(b64encoder.encodeToString(certificate.getEncoded())); fw.write("\n"); fw.write(X509Factory.END_CERT); fw.flush(); List<String> commands = new ArrayList<>(); commands.add(OPENSSL); commands.add("verify"); commands.add("-CAfile"); commands.add(Paths.get(pki.getCACertsDir(caType), "ca-chain.cert.pem").toString()); commands.add("-crl_check"); commands.add("-CRLfile"); commands.add(pki.getCACRLPath(caType)); commands.add(tmpCertFile.getAbsolutePath()); executeCommand(commands, false); } catch (GeneralSecurityException ex) { throw new IOException(ex); } finally { tmpCertFile.delete(); } }

Target:
public void validateCertificate(X509Certificate certificate, PKI.CAType caType) throws IOException { File tmpCertFile = File.createTempFile("cert-", ".pem"); try (FileWriter fw = new FileWriter(tmpCertFile, false)) { fw.write(X509Factory.BEGIN_CERT); fw.write("\n"); fw.write(b64encoder.encodeToString(certificate.getEncoded())); fw.write("\n"); fw.write(X509Factory.END_CERT); fw.flush(); List<String> commands = new ArrayList<>(); commands.add(OPENSSL); commands.add("verify"); commands.add("-CAfile"); commands.add(pki.getChainOfTrustFilePath(caType).toString()); commands.add("-crl_check"); commands.add("-CRLfile"); commands.add(pki.getCACRLPath(caType).toString()); commands.add(tmpCertFile.getAbsolutePath()); executeCommand(commands, false); } catch (GeneralSecurityException ex) { throw new IOException(ex); } finally { tmpCertFile.delete(); } }
Source:
void recoverOne(RuntimeInfrastructure infra, RuntimeIdentity identity) throws ServerException { Workspace workspace; try { workspace = workspaceDao.get(identity.getWorkspaceId()); } catch (NotFoundException x) { LOG.error( "Workspace configuration is missing for the runtime '{}:{}'. Runtime won't be recovered", identity.getWorkspaceId(), identity.getEnvName()); return; } Environment environment = workspace.getConfig().getEnvironments().get(identity.getEnvName()); if (environment == null) { LOG.error( "Environment configuration is missing for the runtime '{}:{}'. Runtime won't be recovered", identity.getWorkspaceId(), identity.getEnvName()); return; } InternalRuntime runtime; try { InternalEnvironment internalEnvironment = environmentFactories.get(environment.getRecipe().getType()).create(environment); runtime = infra.prepare(identity, internalEnvironment).getRuntime(); } catch (InfrastructureException | ValidationException x) { LOG.error( "Couldn't recover runtime '{}:{}'. Error: {}", identity.getWorkspaceId(), identity.getEnvName(), x.getMessage()); return; } RuntimeState prev = runtimes.putIfAbsent(identity.getWorkspaceId(), new RuntimeState(runtime, RUNNING)); if (prev == null) { LOG.info( "Successfully recovered workspace runtime '{}'", identity.getWorkspaceId(), identity.getEnvName()); } else { LOG.error( "More than 1 runtime with id '{}:{}' found. " + "Duplicate provided by infrastructure '{}' will be skipped", identity.getWorkspaceId(), identity.getEnvName(), prev.runtime.getContext().getInfrastructure().getName(), infra.getName()); } }

Target:
void recoverOne(RuntimeInfrastructure infra, RuntimeIdentity identity) throws ServerException { Workspace workspace; try { workspace = workspaceDao.get(identity.getWorkspaceId()); } catch (NotFoundException x) { LOG.error( "Workspace configuration is missing for the runtime '{}:{}'. Runtime won't be recovered", identity.getWorkspaceId(), identity.getEnvName()); return; } Environment environment = workspace.getConfig().getEnvironments().get(identity.getEnvName()); if (environment == null) { LOG.error( "Environment configuration is missing for the runtime '{}:{}'. Runtime won't be recovered", identity.getWorkspaceId(), identity.getEnvName()); return; } InternalRuntime runtime; try { InternalEnvironment internalEnv = createInternalEnvironment(environment); runtime = infra.prepare(identity, internalEnv).getRuntime(); } catch (InfrastructureException | ValidationException | NotFoundException x) { LOG.error( "Couldn't recover runtime '{}:{}'. Error: {}", identity.getWorkspaceId(), identity.getEnvName(), x.getMessage()); return; } RuntimeState prev = runtimes.putIfAbsent(identity.getWorkspaceId(), new RuntimeState(runtime, RUNNING)); if (prev == null) { LOG.info( "Successfully recovered workspace runtime '{}'", identity.getWorkspaceId(), identity.getEnvName()); } else { LOG.error( "More than 1 runtime with id '{}:{}' found. " + "Duplicate provided by infrastructure '{}' will be skipped", identity.getWorkspaceId(), identity.getEnvName(), prev.runtime.getContext().getInfrastructure().getName(), infra.getName()); } }
Source:
public ProjectHandleResolverDTO mapProjectHandleResolver(IProjectHandleResolver resolver) { ProjectHandleResolverDTO dto = new ProjectHandleResolverDTO(); dto.setDescription(resolver.getDescription()); dto.setHandleExample(resolver.getHandleExample()); dto.setHandlePattern(resolver.getHandlePattern()); dto.setId(resolver.getId()); dto.setProjectName(resolver.getProjectName()); dto.setProjectUrl(resolver.getProjectUrl()); dto.setResolvedHandlePattern(resolver.getResolvedHandlePattern()); dto.setUsername(resolver.getUsername()); dto.setResolvedHandleExample(resolver.getResolvedHandleExample()); dto.setValidation(resolver.getValidation().toString()); System.out.println(resolver.getValidation().toString()); return dto; }

Target:
public ProjectHandleResolverDTO mapProjectHandleResolver(IProjectHandleResolver resolver) { ProjectHandleResolverDTO dto = new ProjectHandleResolverDTO(); dto.setDescription(resolver.getDescription()); dto.setHandleExample(resolver.getHandleExample()); dto.setHandlePattern(resolver.getHandlePattern()); dto.setId(resolver.getId()); dto.setProjectName(resolver.getProjectName()); dto.setProjectUrl(resolver.getProjectUrl()); dto.setResolvedHandlePattern(resolver.getResolvedHandlePattern()); dto.setUsername(resolver.getUsername()); dto.setResolvedHandleExample(resolver.getResolvedHandleExample()); dto.setValidation(resolver.getValidation()); return dto; }
Source:
public int getMinRecordLength() { return 0; }

Target:
public int getMinRecordLength() { Iterator<DataStore> iter = delegateHandler.getWritableDelegatesIterator(); int minRecordLength = Integer.MAX_VALUE; while (iter.hasNext()) { minRecordLength = Math.min(minRecordLength, iter.next().getMinRecordLength()); } return minRecordLength; }
Source:
public SSHClient getSSHClient() { Long timeout = TimeUnit.SECONDS.toMillis(Config.<Integer> GetValue(ConfigValues.ConnectToServerTimeoutInSeconds)); EngineSSHClient sshclient = new EngineSSHClient(); if (getParameters().getvds().getSSHKeyFingerprint().isEmpty()) { sshclient.setVds(getParameters().getvds()); try { getParameters().getvds().setSSHKeyFingerprint(sshclient.getHostFingerprint()); DbFacade.getInstance().getVdsStaticDao().save(getParameters().getVdsStaticData()); } catch (Exception e) { log.warnFormat( "couldn't set fingerprint for vds", e); } } else { sshclient.setVds(getParameters().getvds()); } sshclient.setHardTimeout(timeout); sshclient.setSoftTimeout(timeout); sshclient.setPassword(getParameters().getPassword()); return (SSHClient) sshclient; }

Target:
public EngineSSHClient getSSHClient() { Long timeout = TimeUnit.SECONDS.toMillis(Config.<Integer> GetValue(ConfigValues.ConnectToServerTimeoutInSeconds)); EngineSSHClient sshclient = new EngineSSHClient(); if (getParameters().getvds().getSSHKeyFingerprint().isEmpty()) { sshclient.setVds(getParameters().getvds()); try { getParameters().getvds().setSSHKeyFingerprint(sshclient.getHostFingerprint()); DbFacade.getInstance().getVdsStaticDao().save(getParameters().getVdsStaticData()); } catch (Exception e) { log.warnFormat( "couldn't set fingerprint for vds", e); } } else { sshclient.setVds(getParameters().getvds()); } sshclient.setHardTimeout(timeout); sshclient.setSoftTimeout(timeout); sshclient.setPassword(getParameters().getPassword()); return sshclient; }
Source:
public void cleanupPreCommitConditionsOnFailure() { MutableLong counter = new MutableLong(0L); PreCommitCondition failsCondition = new PreCommitCondition() { @Override public void throwIfConditionInvalid(long timestamp) { throw new TransactionFailedRetriableException("Condition failed"); } @Override public void cleanup() { counter.increment(); } }; try { wrappedSerializableTxManager.runTaskWithConditionThrowOnConflict(failsCondition, (tx, condition) -> { tx.put(TABLE, ImmutableMap.of(TEST_CELL, PtBytes.toBytes("value"))); return null; }); fail(); } catch (TransactionFailedRetriableException e) { } assertThat(counter.intValue(), is(1)); try { wrappedSerializableTxManager.runTaskWithConditionReadOnly(failsCondition, (tx, condition) -> tx.get(TABLE, ImmutableSet.of(TEST_CELL))); fail(); } catch (TransactionFailedRetriableException e) { } assertThat(counter.intValue(), is(2)); }

Target:
public void cleanupPreCommitConditionsOnFailure() { MutableLong counter = new MutableLong(0L); PreCommitCondition failsCondition = new PreCommitCondition() { @Override public void throwIfConditionInvalid(long timestamp) { throw new TransactionFailedRetriableException("Condition failed"); } @Override public void cleanup() { counter.increment(); } }; try { serializableTxManager.runTaskWithConditionThrowOnConflict(failsCondition, (tx, condition) -> { tx.put(TABLE, ImmutableMap.of(TEST_CELL, PtBytes.toBytes("value"))); return null; }); fail(); } catch (TransactionFailedRetriableException e) { } assertThat(counter.intValue(), is(1)); try { serializableTxManager.runTaskWithConditionReadOnly(failsCondition, (tx, condition) -> tx.get(TABLE, ImmutableSet.of(TEST_CELL))); fail(); } catch (TransactionFailedRetriableException e) { } assertThat(counter.intValue(), is(2)); }
Source:
private void deleteSwipeItem(int position) { if (swipeDismissListener != null && position < listView.getCount()) { swipeDismissListener.delete(position); } }

Target:
private void deleteSwipeItem(int position) { if (swipeDismissListener != null) { swipeDismissListener.delete(position); } }
Source:
private void createAPI(APIRequest apiCreationRequest, String apiName) throws APIManagerIntegrationTestException { HttpResponse apiCreationResponse = apiPublisher.addAPI(apiCreationRequest); assertEquals(apiCreationResponse.getResponseCode(), Response.Status.OK.getStatusCode(), "Response Code miss matched when creating the API"); verifyResponse(apiCreationResponse); }

Target:
private void createAPI(APIRequest apiCreationRequest, String apiName) throws APIManagerIntegrationTestException { HttpResponse apiCreationResponse = apiPublisher.addAPI(apiCreationRequest); verifyResponse(apiCreationResponse); }
Source:
public void testUnixEncodeProxyV2() { HAProxyMessageEncoder encoder = new HAProxyMessageEncoder(); EmbeddedChannel ch = new EmbeddedChannel(encoder); HAProxyMessage message = new HAProxyMessage( HAProxyProtocolVersion.V2, HAProxyCommand.PROXY, HAProxyProxiedProtocol.UNIX_STREAM, "/var/run/src.sock", "/var/run/dst.sock", 0, 0); assertTrue(ch.writeOutbound(message)); ByteBuf byteBuf = ch.readOutbound(); byte[] headerBytes = ByteBufUtil.getBytes(byteBuf, 0, 12); assertArrayEquals(BINARY_PREFIX, headerBytes); byte commandByte = byteBuf.getByte(12); assertEquals(0x02, (commandByte & 0xf0) >> 4); assertEquals(0x01, commandByte & 0x0f); byte transportByte = byteBuf.getByte(13); assertEquals(0x03, (transportByte & 0xf0) >> 4); assertEquals(0x01, transportByte & 0x0f); int sourceAddrLength = byteBuf.getUnsignedShort(14); assertEquals(216, sourceAddrLength); int srcAddrEnd = byteBuf.forEachByte(16, 108, ByteProcessor.FIND_NUL); assertEquals("/var/run/src.sock", byteBuf.slice(16, srcAddrEnd - 16).toString(CharsetUtil.US_ASCII)); int dstAddrEnd = byteBuf.forEachByte(124, 108, ByteProcessor.FIND_NUL); assertEquals("/var/run/dst.sock", byteBuf.slice(124, dstAddrEnd - 124).toString(CharsetUtil.US_ASCII)); }

Target:
public void testUnixEncodeProxyV2() { EmbeddedChannel ch = new EmbeddedChannel(INSTANCE); HAProxyMessage message = new HAProxyMessage( HAProxyProtocolVersion.V2, HAProxyCommand.PROXY, HAProxyProxiedProtocol.UNIX_STREAM, "/var/run/src.sock", "/var/run/dst.sock", 0, 0); assertTrue(ch.writeOutbound(message)); ByteBuf byteBuf = ch.readOutbound(); byte[] headerBytes = ByteBufUtil.getBytes(byteBuf, 0, 12); assertArrayEquals(BINARY_PREFIX, headerBytes); byte commandByte = byteBuf.getByte(12); assertEquals(0x02, (commandByte & 0xf0) >> 4); assertEquals(0x01, commandByte & 0x0f); byte transportByte = byteBuf.getByte(13); assertEquals(0x03, (transportByte & 0xf0) >> 4); assertEquals(0x01, transportByte & 0x0f); int addrLength = byteBuf.getUnsignedShort(14); assertEquals(TOTAL_UNIX_ADDRESS_BYTES_LENGTH, addrLength); int srcAddrEnd = byteBuf.forEachByte(16, 108, ByteProcessor.FIND_NUL); assertEquals("/var/run/src.sock", byteBuf.slice(16, srcAddrEnd - 16).toString(CharsetUtil.US_ASCII)); int dstAddrEnd = byteBuf.forEachByte(124, 108, ByteProcessor.FIND_NUL); assertEquals("/var/run/dst.sock", byteBuf.slice(124, dstAddrEnd - 124).toString(CharsetUtil.US_ASCII)); byteBuf.release(); assertFalse(ch.finish()); }
Source:
public Iterator<ObjectNode> convertObject(InputStream csvSource) throws IOException { CountInputStream countInputStream = new CountInputStream(csvSource); setCountInputStream(countInputStream); CsvSchema firstLineSchema = CsvSchema.emptySchema().withHeader(); Iterator<ObjectNode> objectItr = csvMapper.readerFor(ObjectNode.class).with(firstLineSchema) .readValues(csvSource); return objectItr; }

Target:
public Iterator<ObjectNode> convertObject(InputStream csvSource) throws IOException { CsvSchema firstLineSchema = CsvSchema.emptySchema().withHeader(); Iterator<ObjectNode> objectItr = csvMapper .readerFor(ObjectNode.class) .with(firstLineSchema) .readValues(csvSource); return objectItr; }
Source:
public AddPinComponentObject placePinInMap() { waitForElementByElement(mapFrame); driver.switchTo().frame(mapFrame); waitForElementVisibleByElement(addPinButton); addPinButton.click(); Actions actions = new Actions(driver); actions.moveToElement(mapImagesCollection.get(0)); actions.click().perform(); driver.switchTo().defaultContent(); return new AddPinComponentObject(driver); }

Target:
public AddPinComponentObject placePinInMap() { waitForElementByElement(mapFrame); driver.switchTo().frame(mapFrame); waitForElementVisibleByElement(addPinButton); addPinButton.click(); Actions actions = new Actions(driver); actions.moveToElement(mapImagesCollection.get(0)); actions.click().perform(); driver.switchTo().defaultContent(); PageObjectLogging.log("placePinInMap", "Pin was placed in map", true); return new AddPinComponentObject(driver); }
Source:
public Collection<E> get() { return container; }

Target:
Collection<E> get() { return container; }
Source:
protected void setUpLayout(Context context) { setDisplayValueFromModel(); Resources resources = context.getResources(); int marginStandard = dpFromPx(context, resources.getDimension(R.dimen.margin_standard)); int margin = marginStandard - FIELD_HORIZONTAL_MARGIN_MODIFIER; addAnswerView(answerText, margin); }

Target:
protected void setUpLayout(Context context) { setDisplayValueFromModel(); Resources resources = context.getResources(); int marginStandard = dpFromPx(context, resources.getDimensionPixelSize(R.dimen.margin_standard)); int margin = marginStandard - FIELD_HORIZONTAL_MARGIN_MODIFIER; addAnswerView(answerText, margin); }
Source:
public void saveOrUpdateShouldReturnUserId() { given(userRepository.save(userEntity)).willReturn(userEntity); Long result = userService.saveOrUpdate(detailedUserDTO); assertThat(result, is(USER_ID)); }

Target:
public void saveOrUpdateShouldReturnUserId() { given(userRepository.save(userEntity)).willReturn(userEntity); Long result = userService.saveOrUpdate(detailedUserDTO); then(modelMapper).should().map(detailedUserDTO, UserEntity.class); then(userRepository).should().save(userEntity); assertThat(result, is(USER_ID)); }
Source:
private <C extends WriteCommand, Container, Item> void handleLocalSegmentsForReadWriteManyCommand( InvocationContext ctx, C command, WriteManyCommandHelper<C, Container, Item> helper, ConsistentHash ch, MergingCompletableFuture<Object> allFuture, MutableInt offset, IntSet segments) throws Exception { Container myItems = helper.newContainer(); List<Object> remoteKeys = new ArrayList<>(); for (Item item : helper.getItems(command)) { Object key = helper.item2key(item); if (segments.contains(keyPartitioner.getSegment(key))) { helper.accumulate(myItems, item); CacheEntry cacheEntry = ctx.lookupEntry(key); if (cacheEntry == null) { if (command.hasAnyFlag(FlagBitSets.SKIP_REMOTE_LOOKUP | FlagBitSets.CACHE_MODE_LOCAL)) { entryFactory.wrapExternalEntry(ctx, key, null, false, true); } else { remoteKeys.add(key); } } } } CompletionStage<Void> retrievals = remoteGetMany(ctx, command, remoteKeys); int size = helper.containerSize(myItems); if (size == 0) { allFuture.countDown(); return; } final int myOffset = offset.value; offset.value += size; C localCommand = helper.copyForLocal(command, myItems); localCommand.setTopologyId(command.getTopologyId()); InvocationFinallyAction handler = createLocalInvocationHandler(ch, allFuture, segments, helper, MergingCompletableFuture.moveListItemsToFuture(myOffset)); if (remoteKeys.isEmpty()) { invokeNextAndFinally(ctx, localCommand, handler); } else { Object result = asyncInvokeNext(ctx, command, retrievals); makeStage(result).andFinally(ctx, command, handler); } }

Target:
private <C extends WriteCommand, Container, Item> void handleLocalSegmentsForReadWriteManyCommand( InvocationContext ctx, C command, WriteManyCommandHelper<C, Container, Item> helper, ConsistentHash ch, MergingCompletableFuture<Object> allFuture, MutableInt offset, IntSet segments) throws Exception { Container myItems = helper.newContainer(); List<Object> remoteKeys = null; for (Item item : helper.getItems(command)) { Object key = helper.item2key(item); if (segments.contains(keyPartitioner.getSegment(key))) { helper.accumulate(myItems, item); CacheEntry cacheEntry = ctx.lookupEntry(key); if (cacheEntry == null) { if (command.hasAnyFlag(FlagBitSets.SKIP_REMOTE_LOOKUP | FlagBitSets.CACHE_MODE_LOCAL)) { entryFactory.wrapExternalEntry(ctx, key, null, false, true); } else { if (remoteKeys == null) { remoteKeys = new ArrayList<>(); } remoteKeys.add(key); } } } } CompletionStage<Void> retrievals = remoteKeys != null ? remoteGetMany(ctx, command, remoteKeys) : null; int size = helper.containerSize(myItems); if (size == 0) { allFuture.countDown(); return; } final int myOffset = offset.value; offset.value += size; C localCommand = helper.copyForLocal(command, myItems); localCommand.setTopologyId(command.getTopologyId()); InvocationFinallyAction handler = createLocalInvocationHandler(ch, allFuture, segments, helper, MergingCompletableFuture.moveListItemsToFuture(myOffset)); if (retrievals == null) { invokeNextAndFinally(ctx, localCommand, handler); } else { Object result = asyncInvokeNext(ctx, command, retrievals); makeStage(result).andFinally(ctx, command, handler); } }
Source:
private static void throwIfTabLayoutIsMissing(int tabLayoutId) { if (tabLayoutId != MISSING_TAB_LAYOUT_ID) { return; } throw new MissingTabLayoutId(); }

Target:
private static void throwIfTabLayoutIsMissing(int tabLayoutId) { if (tabLayoutId != MISSING_TAB_LAYOUT_ID) { return; } throw new MissingTabLayoutIdException(); }
Source:
protected void bootstrap() { if (config != null) { PayaraConfiguredNotifier.class.cast(notifier).setConfiguration(config); } notifier.bootstrap(); }

Target:
protected synchronized void bootstrap() { if (config != null) { PayaraConfiguredNotifier.class.cast(notifier).setConfiguration(config); } if (isEnabled()) { notifier.bootstrap(); taskResult = executor.scheduleWithFixedDelay(this::run, 0, 5, TimeUnit.MILLISECONDS); } }
Source:
public boolean isValidValue(final MeasurementVariable var, final String value, final String cValueId, final boolean validateDateForDB) { if (value == null || "".equals(value.trim())) { return true; } if (var.getMinRange() != null && var.getMaxRange() != null) { if (ValidationServiceImpl.MISSING_VAL.equals(value.trim())) { return true; } return NumberUtils.isNumber(value); } else if (validateDateForDB && var != null && var.getDataTypeId() != null && var.getDataTypeId() == TermId.DATE_VARIABLE.getId()) { return DateUtil.isValidDate(value); } else if (var.getDataType() != null && var.getDataType().equalsIgnoreCase(ValidationServiceImpl.DATA_TYPE_NUMERIC)) { if (ValidationServiceImpl.MISSING_VAL.equals(value.trim())) { return true; } return NumberUtils.isNumber(value.trim()); } return true; }

Target:
public boolean isValidValue(final MeasurementVariable var, final String value, final String cValueId, final boolean validateDateForDB) { if (StringUtils.isBlank(value)) { return true; } if (var.getMinRange() != null && var.getMaxRange() != null) { return this.validateIfValueIsMissingOrNumber(value.trim()); } else if (validateDateForDB && var != null && var.getDataTypeId() != null && var.getDataTypeId() == TermId.DATE_VARIABLE.getId()) { return DateUtil.isValidDate(value); } else if (StringUtils.isNotBlank(var.getDataType()) && var.getDataType().equalsIgnoreCase(ValidationServiceImpl.DATA_TYPE_NUMERIC)) { return this.validateIfValueIsMissingOrNumber(value.trim()); } return true; }
Source:
public SegmentMetadataQueryQueryToolChest( SegmentMetadataQueryConfig config ) { this.config = config; defaultHistory = this.config.getDefaultHistory(); }

Target:
public SegmentMetadataQueryQueryToolChest( SegmentMetadataQueryConfig config ) { this.config = config; }
Source:
public void execute(JobExecutionContext context) throws JobExecutionException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Starting a deadline job"); } JobDetail jobDetail = context.getJobDetail(); JobDataMap jobData = jobDetail.getJobDataMap(); try { SchedulerContext schedulerContext = context.getScheduler().getContext(); Serializer serializer = (Serializer) schedulerContext.get(JOB_DATA_SERIALIZER); TransactionManager transactionManager = (TransactionManager) schedulerContext.get(TRANSACTION_MANAGER_KEY); ScopeAwareProvider scopeAwareComponents = (ScopeAwareProvider) schedulerContext.get(SCOPE_AWARE_RESOLVER); DeadlineMessage<?> deadlineMessage = deadlineMessage(serializer, jobData); ScopeDescriptor deadlineScope = deadlineScope(serializer, jobData); DefaultUnitOfWork<DeadlineMessage<?>> unitOfWork = DefaultUnitOfWork.startAndGet(deadlineMessage); unitOfWork.attachTransaction(transactionManager); unitOfWork.execute(() -> executeScheduledDeadline(scopeAwareComponents, deadlineMessage, deadlineScope)); if (LOGGER.isInfoEnabled()) { LOGGER.info("Job successfully executed. Deadline message processed.", deadlineMessage.getPayloadType().getSimpleName()); } } catch (Exception e) { LOGGER.error("Exception occurred during processing a deadline job [{}]", jobDetail.getDescription(), e); throw new JobExecutionException(e, true); } }

Target:
public void execute(JobExecutionContext context) throws JobExecutionException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Starting a deadline job"); } JobDetail jobDetail = context.getJobDetail(); JobDataMap jobData = jobDetail.getJobDataMap(); try { SchedulerContext schedulerContext = context.getScheduler().getContext(); Serializer serializer = (Serializer) schedulerContext.get(JOB_DATA_SERIALIZER); TransactionManager transactionManager = (TransactionManager) schedulerContext.get(TRANSACTION_MANAGER_KEY); ScopeAwareProvider scopeAwareComponents = (ScopeAwareProvider) schedulerContext.get(SCOPE_AWARE_RESOLVER); DeadlineMessage<?> deadlineMessage = deadlineMessage(serializer, jobData); ScopeDescriptor deadlineScope = deadlineScope(serializer, jobData); DefaultUnitOfWork<DeadlineMessage<?>> unitOfWork = DefaultUnitOfWork.startAndGet(deadlineMessage); unitOfWork.attachTransaction(transactionManager); unitOfWork.execute(() -> executeScheduledDeadline(scopeAwareComponents, deadlineMessage, deadlineScope)); if (LOGGER.isInfoEnabled()) { LOGGER.info("Job successfully executed. Deadline message processed.", deadlineMessage.getPayloadType().getSimpleName()); } } catch (Exception e) { if (findException(e, t -> t instanceof AxonNonTransientException).isPresent()) { LOGGER.error("Non transient exception occurred during processing a deadline job [{}]", jobDetail.getDescription(), e); throw new JobExecutionException(e); } LOGGER.warn("Transient exception occurred during processing a deadline job [{}]", jobDetail.getDescription(), e); throw new JobExecutionException(e, REFIRE_IMMEDIATELY); } }
Source:
Map<String, Object> getAvailableTypes() { List<Map<String, String>> availableTypes = this.userCreatableMetacardTypesList .stream() .map(UserCreatableMetacardTypes::getAvailableTypes) .flatMap(Collection::stream) .distinct() .map(s -> Collections.singletonMap("metacardType", s)) .collect(Collectors.toList()); return Collections.singletonMap("availabletypes", availableTypes); }

Target:
Map<String, Object> getAvailableTypes() { List<Map<String, Object>> availableTypes = this.userCreatableMetacardTypeList .stream() .map(this::convertUserCreatableMetacardTypeToMap) .collect(Collectors.toList()); return Collections.singletonMap("availabletypes", availableTypes); }
Source:
protected void configureServlets() { install(new FactoryModule() { @Override protected void configure() { factory(ChangeDetailFactory.Factory.class); factory(PatchSetDetailFactory.Factory.class); } }); rpc(ChangeDetailServiceImpl.class); }

Target:
protected void configureServlets() { install(new FactoryModule() { @Override protected void configure() { factory(PatchSetDetailFactory.Factory.class); } }); rpc(ChangeDetailServiceImpl.class); }
Source:
public static void writeJavaScriptUrl(final Response response, final CharSequence url, final String id, boolean defer, String charset, boolean async) { response.write("<script "); HeaderItemAttributeMap attributes = new HeaderItemAttributeMap(); attributes.add(HeaderItemAttribute.TYPE, "text/javascript"); attributes.add(HeaderItemAttribute.SCRIPT_SRC, url.toString()); if (id != null) { attributes.add(HeaderItemAttribute.ID, String.valueOf(Strings.escapeMarkup(id))); } if (defer) { attributes.add(HeaderItemAttribute.SCRIPT_DEFER, "defer"); } if (async) { attributes.add(HeaderItemAttribute.SCRIPT_ASYNC, "async"); } if (charset != null) { attributes.add("charset", Strings.escapeMarkup(charset).toString()); } response.write(attributes.toString()); response.write("></script>"); response.write("\n"); }

Target:
public static void writeJavaScriptUrl(final Response response, final CharSequence url, final String id, boolean defer, String charset, boolean async) { response.write("<script "); AttributeMap attributes = new AttributeMap(); attributes.put(ATTR_TYPE, "text/javascript"); attributes.put(ATTR_SCRIPT_SRC, UrlEncoder.FULL_URL_INSTANCE.encode(String.valueOf(url), "UTF-8")); if (id != null) { attributes.put(ATTR_ID, id); } if (defer) { attributes.put(ATTR_SCRIPT_DEFER, "defer"); } if (async) { attributes.put(ATTR_SCRIPT_ASYNC, "async"); } if (charset != null) { attributes.put("charset", charset); } response.write(attributes.toString()); response.write("></script>"); response.write("\n"); }
Source:
private void comparePlanTree(AbstractPlanNode calcitePlanNode, AbstractPlanNode voltdbPlanNode, Map<String, String> ignoreMap) { PlanNodeTree calcitePlanTree = new PlanNodeTree(calcitePlanNode); PlanNodeTree voltdbPlanTree = new PlanNodeTree(voltdbPlanNode); String calcitePlanTreeJSON = calcitePlanTree.toJSONString(); String voltdbPlanTreeJSON = voltdbPlanTree.toJSONString(); if (ignoreMap != null) { for (Map.Entry<String, String> ignore : ignoreMap.entrySet()) { calcitePlanTreeJSON = calcitePlanTreeJSON.replace(ignore.getKey(), ignore.getValue()); } } assertEquals(voltdbPlanTreeJSON, calcitePlanTreeJSON); }

Target:
private void comparePlanTree(AbstractPlanNode calcitePlanNode, AbstractPlanNode voltdbPlanNode, Map<String, String> ignoreMap) { PlanNodeTree calcitePlanTree = new PlanNodeTree(calcitePlanNode); PlanNodeTree voltdbPlanTree = new PlanNodeTree(voltdbPlanNode); String calcitePlanTreeJSON = calcitePlanTree.toJSONString(); String voltdbPlanTreeJSON = voltdbPlanTree.toJSONString(); for (Map.Entry<String, String> ignore : ignoreMap.entrySet()) { calcitePlanTreeJSON = calcitePlanTreeJSON.replace(ignore.getKey(), ignore.getValue()); } assertEquals(voltdbPlanTreeJSON, calcitePlanTreeJSON); }
Source:
public static void main(String[] arg){ int lport; String rhost; int rport; try{ JSch jsch=new JSch(); String host; if(arg.length>0){ host=arg[0]; } else{ host=JOptionPane.showInputDialog("Enter username@hostname", System.getProperty("user.name")+ "@localhost"); } String user=host.substring(0, host.indexOf('@')); host=host.substring(host.indexOf('@')+1); Session session=jsch.getSession(user, host, 22); String foo=JOptionPane.showInputDialog("Enter -L port:host:hostport", "port:host:hostport"); lport=Integer.parseInt(foo.substring(0, foo.indexOf(':'))); foo=foo.substring(foo.indexOf(':')+1); rhost=foo.substring(0, foo.indexOf(':')); rport=Integer.parseInt(foo.substring(foo.indexOf(':')+1)); UserInfo ui=new MyUserInfo(); session.setUserInfo(ui); session.connect(); int assigned_port=session.setPortForwardingL(lport, rhost, rport); System.out.println("localhost:"+assigned_port+" -> "+rhost+":"+rport); } catch(Exception e){ System.out.println(e); } }

Target:
public static void main(String[] arg){ int lport; String rhost; int rport; try{ JSch jsch=new JSch(); String host = null; if(arg.length>0){ host=arg[0]; } else{ host=JOptionPane.showInputDialog("Enter username@hostname", System.getProperty("user.name")+ "@localhost"); } String user=host.substring(0, host.indexOf('@')); host=host.substring(host.indexOf('@')+1); Session session=jsch.getSession(user, host, 22); String foo=JOptionPane.showInputDialog("Enter -L port:host:hostport", "port:host:hostport"); lport=Integer.parseInt(foo.substring(0, foo.indexOf(':'))); foo=foo.substring(foo.indexOf(':')+1); rhost=foo.substring(0, foo.indexOf(':')); rport=Integer.parseInt(foo.substring(foo.indexOf(':')+1)); UserInfo ui=new MyUserInfo(); session.setUserInfo(ui); session.connect(); int assigned_port=session.setPortForwardingL(lport, rhost, rport); System.out.println("localhost:"+assigned_port+" -> "+rhost+":"+rport); } catch(Exception e){ System.out.println(e); } }
Source:
public void testHTTPListenerAfterRejoin() throws Exception { if (!VoltDB.instance().getConfig().m_isEnterprise) { return; } VoltProjectBuilder builder = new VoltProjectBuilder(); builder.setSecurityEnabled(false, false); builder.setHTTPDPort(0); builder.setJSONAPIEnabled(true); LocalCluster cluster = new LocalCluster("rejoin.jar", 2, 2, 1, BackendTarget.NATIVE_EE_JNI, true); try { boolean success = cluster.compile(builder); assertTrue(success); cluster.startUp(); String url = "<LINK_0>" + cluster.httpPort(0) + "/deployment"; try { getUrlOverJSON(url, null, null, null, 200, "application/json"); } catch (HttpHostConnectException e) { fail("HTTP Listener is not open when the node is on"); } cluster.killSingleHost(0); Thread.sleep(1000); url = "<LINK_0>" + cluster.httpPort(0) + "/deployment"; try { getUrlOverJSON(url, null, null, null, 200, "application/json"); fail("HTTP Listener is not closed when the node is down."); } catch (HttpHostConnectException e) { assertTrue(e.toString().contains("Connection refused")); } cluster.recoverOne(0, 0, "", true); Thread.sleep(1000); url = "<LINK_0>" + cluster.httpPort(2) + "/deployment"; try { getUrlOverJSON(url, null, null, null, 200, "application/json"); } catch (HttpHostConnectException e) { fail("HTTP Listener is not open after the node has rejoined."); } } catch (Exception e) { e.printStackTrace(); } finally { cluster.shutDown(); } }

Target:
public void testHTTPListenerAfterRejoin() throws Exception { if (!VoltDB.instance().getConfig().m_isEnterprise) { return; } final long TIMEOUT_THRESHOLD = 60000; VoltProjectBuilder builder = new VoltProjectBuilder(); builder.setSecurityEnabled(false, false); builder.setJSONAPIEnabled(true); LocalCluster cluster = new LocalCluster("rejoin.jar", 2, 3, 1, BackendTarget.NATIVE_EE_JNI, true); try { boolean success = cluster.compile(builder); assertTrue(success); cluster.setHttpPortEnabled(true); cluster.startUp(); long startTime = System.currentTimeMillis(); int port0 = cluster.httpPort(0), port1 = cluster.httpPort(1), port2 = cluster.httpPort(2); while ( !canAccessHttpPort(port0)|| !canAccessHttpPort(port1) || !canAccessHttpPort(port2)) { if (System.currentTimeMillis() - startTime >= TIMEOUT_THRESHOLD) { fail("Local cluster failed to start up"); } Thread.sleep(200); } assertTrue("Http port failed to open when the node is on", canAccessHttpPort(port0)); cluster.killSingleHost(0); assertFalse("Http port failed to close when the node is offline", canAccessHttpPort(port0)); cluster.recoverOne(0, 0, "", true); startTime = System.currentTimeMillis(); port0 = cluster.httpPort(3); while ( !canAccessHttpPort(port0)|| !canAccessHttpPort(port1) || !canAccessHttpPort(port2)) { if (System.currentTimeMillis() - startTime >= TIMEOUT_THRESHOLD) { fail("Local cluster failed to rejoin"); } Thread.sleep(200); } assertTrue("Http port failed to open when the node is rejoined", canAccessHttpPort(port0)); Thread.sleep(1000); } finally { try {cluster.shutDown();} catch (Exception e) } }
Source:
public void ensureIdFieldTest() throws Exception { EntityMetadata e = new EntityMetadata("testEntity"); e.setVersion(new Version("1.0.0", null, "some text blah blah")); e.setStatus(MetadataStatus.ACTIVE); e.setDataStore(new MongoDataStore(null, null, "testCollectionIndex2")); e.getFields().put(new SimpleField("field1", StringType.TYPE)); ObjectField o = new ObjectField("field2"); o.getFields().put(new SimpleField("x", IntegerType.TYPE)); e.getFields().put(o); e.getEntityInfo().setDefaultVersion("1.0.0"); Assert.assertNull(e.getFields().getField("_id")); controller.beforeCreateNewSchema(null,e); SimpleField id=(SimpleField)e.getFields().getField("_id"); Assert.assertNotNull(id); Assert.assertEquals(StringType.TYPE,id.getType()); }

Target:
public void ensureIdFieldTest() throws Exception { EntityMetadata e = new EntityMetadata("testEntity"); e.setVersion(new Version("1.0.0", null, "some text blah blah")); e.setStatus(MetadataStatus.ACTIVE); e.setDataStore(new MongoDataStore(null, null, "testCollectionIndex2")); e.getFields().put(new SimpleField("field1", StringType.TYPE)); ObjectField o = new ObjectField("field2"); o.getFields().put(new SimpleField("x", IntegerType.TYPE)); e.getFields().put(o); e.getEntityInfo().setDefaultVersion("1.0.0"); Assert.assertNull(e.getFields().getField("_id")); controller.beforeCreateNewSchema(null,e); SimpleField id=(SimpleField)e.getFields().getField("_id"); Assert.assertNotNull(id); Assert.assertEquals(StringType.TYPE,id.getType()); Assert.assertEquals(0,id.getConstraints().size()); }
Source:
public void testListLocations() { assertFalse(Iterables.isEmpty(adapter.listLocations())); }

Target:
public void testListLocations() { assertFalse(Iterables.isEmpty(adapter.listLocations()), "locations must not be empty"); }
Source:
void handleCallback(final Callback[] callbacks, final int index) throws UnsupportedCallbackException, IOException { Callback callback = callbacks[index]; if (callback instanceof ExtendedChoiceCallback) { ExtendedChoiceCallback extendedChoiceCallback = (ExtendedChoiceCallback) callback; if (choice == null) { extendedChoiceCallback.setSelectedIndex(extendedChoiceCallback.getDefaultChoice()); return; } else { String[] choices = extendedChoiceCallback.getChoices(); for (int i = 0; i < choices.length; i++) { if (choice.equals(choices[i])) { extendedChoiceCallback.setSelectedIndex(i); return; } } } } super.handleCallback(callbacks, index); }

Target:
void handleCallback(final Callback[] callbacks, final int index) throws UnsupportedCallbackException, IOException { Callback callback = callbacks[index]; if (callback instanceof ChoiceCallback) { ChoiceCallback choiceCallback = (ChoiceCallback) callback; if (matchPredicate.test(choiceCallback.getClass(), choiceCallback.getPrompt())) { if (choice == null) { choiceCallback.setSelectedIndex(choiceCallback.getDefaultChoice()); return; } else { String[] choices = choiceCallback.getChoices(); for (int i = 0; i < choices.length; i++) { if (choice.equals(choices[i])) { choiceCallback.setSelectedIndex(i); return; } } } } } super.handleCallback(callbacks, index); }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { delegate.doFilter(request, response, chain); }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { controller.onNewRequest(); try { chain.doFilter(request, response); } finally { controller.onRequestEnd(); } }
Source:
public static PcapFile getPcapFile(Path filePath) throws IOException, BadPcapFileException { SeekableByteChannel fFileChannel; if (Files.notExists(filePath) || !Files.isRegularFile(filePath) || Files.size(filePath) < PcapFileValues.GLOBAL_HEADER_SIZE) { throw new BadPcapFileException("Bad Pcap File."); } if (!Files.isReadable(filePath)) { throw new BadPcapFileException("File is not readable."); } try { fFileChannel = checkNotNull(Files.newByteChannel(filePath)); FileChannel f = (FileChannel) fFileChannel; ByteBuffer header = ByteBuffer.allocate(PcapFileValues.PCAPNG_BLOCK_HEADER_SIZE); header.clear(); header.order(ByteOrder.LITTLE_ENDIAN); f.read(header); header.flip(); int blockType = header.getInt(); f.close(); if (blockType == PcapFileValues.PCAPNG_SHB) { return new PcapNgFile(filePath); } return new PcapOldFile(filePath); } catch (Exception e) { return new PcapOldFile(filePath); } }

Target:
public static PcapFile getPcapFile(Path filePath) throws IOException, BadPcapFileException { if (Files.notExists(filePath) || !Files.isRegularFile(filePath) || Files.size(filePath) < PcapFileValues.GLOBAL_HEADER_SIZE) { throw new BadPcapFileException("Bad Pcap File."); } if (!Files.isReadable(filePath)) { throw new BadPcapFileException("File is not readable."); } FileChannel f; try { f = (FileChannel) checkNotNull(Files.newByteChannel(filePath)); ByteBuffer header = ByteBuffer.allocate(PcapFileValues.PCAPNG_BLOCK_HEADER_SIZE); header.order(ByteOrder.LITTLE_ENDIAN); f.read(header); header.flip(); int blockType = header.getInt(); f.close(); if (blockType == PcapFileValues.PCAPNG_SHB) { return new PcapNgFile(filePath); } return new PcapOldFile(filePath); } catch (Exception e) { throw new BadPcapFileException("Bad Pcap File."); } }
Source:
private UndertowRootDefinition() { super(UndertowExtension.SUBSYSTEM_PATH, UndertowExtension.getResolver(), UndertowSubsystemAdd.INSTANCE, new ReloadRequiredRemoveStepHandler(){ @Override protected void performRemove(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { DefaultDeploymentMappingProvider.instance().clear(); super.performRemove(context, operation, model); } }); }

Target:
private UndertowRootDefinition() { super(UndertowExtension.SUBSYSTEM_PATH, UndertowExtension.getResolver(), new UndertowSubsystemAdd(APPLICATION_SECURITY_DOMAIN.getKnownSecurityDomainPredicate()), ReloadRequiredRemoveStepHandler.INSTANCE); }
Source:
public void validate(List<String> errors) { for (int i=0; i < getRowCount(); ++i) { String error = errors.get(i); Element element = getRowElement(i); boolean valid = StringUtils.isEmpty(error); element.setTitle(valid ? null : error); element.getStyle().setOutlineStyle(valid ? OutlineStyle.NONE : OutlineStyle.SOLID); element.getStyle().setOutlineColor("red"); element.getStyle().setOutlineWidth(1, Unit.PX); } }

Target:
public void validate(List<String> errors) { for (int i=0; i < getRowCount(); ++i) { String error = errors.get(i); Element element = getRowElement(i); boolean valid = StringUtils.isEmpty(error); element.setTitle(valid ? null : error); if (!valid) { element.addClassName(style.invalidRow()); } else { element.removeClassName(style.invalidRow()); } } }