auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected List<String[]> getHeaders(final String mapping) { List<String[]> corsHeaders = headerMap.get(mapping); if (null == corsHeaders) { synchronized (this.getClass()) { corsHeaders = headerMap.get(mapping); if (null == corsHeaders) { final List<String[]> newHeaders = new ArrayList<>(); Config.subset(CORS_PREFIX + "." + mapping).forEachRemaining(key -> { newHeaders.add(new String[] { fixHeaderCase(key.replace(CORS_PREFIX, "")), Config.getStringProperty(CORS_PREFIX + "." + mapping + "." + key, null) }); }); corsHeaders = ImmutableList.copyOf(newHeaders); headerMap.put(mapping, corsHeaders); } } } if (corsHeaders.isEmpty() && !CORS_DEFAULT.equals(mapping)) { return getHeaders(CORS_DEFAULT); } return corsHeaders; }

Target:
protected List<String[]> getHeaders(final String mapping) { List<String[]> corsHeaders = headerMap.containsKey(mapping) ? headerMap.get(mapping) : headerMap.get(CORS_DEFAULT); return corsHeaders != null ? corsHeaders : ImmutableList.of() ; }
Source:
public void setupOnce() { cacheManagerMock = new CacheManagerMock(); cacheManagerMock.addCache(CACHE_NAME); cacheManager = new JCacheCacheManager(cacheManagerMock.getCacheManager()); cacheManager.afterPropertiesSet(); transactionalCacheManager = new JCacheCacheManager(true, cacheManagerMock.getCacheManager()); transactionalCacheManager.afterPropertiesSet(); }

Target:
public void setupOnce() { cacheManagerMock = new CacheManagerMock(); cacheManagerMock.addCache(CACHE_NAME); cacheManager = new JCacheCacheManager(cacheManagerMock.getCacheManager()); cacheManager.setTransactionAware(false); cacheManager.afterPropertiesSet(); transactionalCacheManager = new JCacheCacheManager(cacheManagerMock.getCacheManager()); transactionalCacheManager.setTransactionAware(true); transactionalCacheManager.afterPropertiesSet(); }
Source:
public String getKieDeploymentDescriptorText(final String path) { return loadKieTextFromJar(path, META_INF, "kie-deployment-descriptor.xml"); }

Target:
public String getKieDeploymentDescriptorText(final String path) { return loadKieTextFromJar(path, META_INF, KIE_DEPLOYMENT_DESCRIPTOR_XML); }
Source:
protected boolean validateFields() { try { String trimmedRegex = getRegexTextField().getText().trim(); if (trimmedRegex.trim().isEmpty()) return false; if (regexes != null && regexes.contains(trimmedRegex)) { throw new IllegalArgumentException(TEXT_ALREADY_EXIST_INVALID_REGEX_DIALOG); } Pattern.compile(trimmedRegex, Pattern.CASE_INSENSITIVE); } catch (IllegalArgumentException e) { JOptionPane.showMessageDialog( this, MessageFormat.format(TEXT_INVALID_REGEX_DIALOG, e.getLocalizedMessage()), TITLE_INVALID_REGEX_DIALOG, JOptionPane.INFORMATION_MESSAGE); getRegexTextField().requestFocusInWindow(); return false; } return true; }

Target:
protected boolean validateFields() { String trimmedRegex = getRegexTextField().getText().trim(); if (regexes != null && regexes.contains(trimmedRegex)) { JOptionPane.showMessageDialog( this, TEXT_ALREADY_EXIST_INVALID_REGEX_DIALOG, TITLE_ALREADY_EXIST_INVALID_REGEX_DIALOG, JOptionPane.INFORMATION_MESSAGE); getRegexTextField().requestFocusInWindow(); return false; } try { Pattern.compile(trimmedRegex, Pattern.CASE_INSENSITIVE); } catch (PatternSyntaxException e) { JOptionPane.showMessageDialog( this, MessageFormat.format(TEXT_INVALID_REGEX_DIALOG, e.getLocalizedMessage()), TITLE_INVALID_REGEX_DIALOG, JOptionPane.INFORMATION_MESSAGE); getRegexTextField().requestFocusInWindow(); return false; } return true; }
Source:
public CalculationRequirements requirements() { return CalculationRequirements.EMPTY; }

Target:
public CalculationRequirements requirements() { return CalculationRequirements.empty(); }
Source:
public void testGoodHBaseName() { BigtableClusterName bigtableClusterName = new BigtableClusterName("some-project", "some-zone", "some-cluster"); String bigtableTableName = bigtableClusterName.toTableNameStr("some-table"); String hbaseName = bigtableClusterName.toTableId(bigtableTableName); Assert.assertEquals("some-table", hbaseName); }

Target:
public void testGoodHBaseName() { BigtableClusterName bigtableClusterName = new BigtableClusterName("some-project", "some-zone", "some-cluster"); String bigtableTableName = bigtableClusterName.toTableNameStr("some-table"); String tableId = bigtableClusterName.toTableId(bigtableTableName); Assert.assertEquals("some-table", tableId); }
Source:
public Result visit(TDataType node, Parameter parameter) { if (Objects.nonNull(node.getDerivedFrom()) && !validateTypeIsDefined(node.getDerivedFrom(), typeVisitor.getDataTypes())) { String msg = "The parent type \"" + node.getDerivedFrom() + "\" is undefined! \n" + print(parameter.getContext()); setException(new InvalidParentType(msg)); } if (Objects.nonNull(node.getDerivedFrom()) && (Defaults.YAML_TYPES.contains(node.getDerivedFrom().getLocalPart()) || Defaults.TOSCA_TYPES.contains(node.getDerivedFrom().getLocalPart()) ) && !node.getProperties().isEmpty()) { String msg = "The native data type \"" + parameter.getKey() + "\" cannot be extended with properties! \n" + print(parameter.getContext()); setException(new InvalidNativeTypeExtend(msg)); } super.visit(node, parameter); return null; }

Target:
public Result visit(TDataType node, Parameter parameter) { validateEntityType(node, parameter, typeVisitor.getDataTypes()); if (Objects.nonNull(node.getDerivedFrom()) && (Defaults.YAML_TYPES.contains(node.getDerivedFrom().getLocalPart()) || Defaults.TOSCA_TYPES.contains(node.getDerivedFrom().getLocalPart()) ) && !node.getProperties().isEmpty()) { String msg = "The native data type \"" + parameter.getKey() + "\" cannot be extended with properties! \n" + print(parameter.getContext()); setException(new InvalidNativeTypeExtend(msg)); } super.visit(node, parameter); return null; }
Source:
protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__VM_SLA_POLICY); addCanDoActionMessage(VdcBllMessages.VAR__ACTION__UPDATE_VM_SLA_POLICY); }

Target:
protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__UPDATE_SLA_POLICY); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM); }
Source:
protected StringBuilder createCountSelect(SearchCriteria<?> sc, final boolean whereClause) { if (sc == null) return null; StringBuilder sql; Pair<GroupBy<?, ?, ?>, List<Object>> groupBys = sc.getGroupBy(); if (groupBys != null) { final SqlGenerator generator = new SqlGenerator(_entityBeanType); sql = new StringBuilder(generator.buildCountSqlWithGroupBy(groupBys.first())); } else { sql = new StringBuilder(_count); } if (!whereClause) { sql.delete(sql.length() - (_discriminatorClause == null ? 6 : 4), sql.length()); } return sql; }

Target:
protected StringBuilder createCountSelect(SearchCriteria<?> sc, final boolean whereClause) { StringBuilder sql = new StringBuilder(_count); if (sc != null) { Pair<GroupBy<?, ?, ?>, List<Object>> groupBys = sc.getGroupBy(); if (groupBys != null) { final SqlGenerator generator = new SqlGenerator(_entityBeanType); sql = new StringBuilder(generator.buildCountSqlWithGroupBy(groupBys.first())); } } if (!whereClause) { sql.delete(sql.length() - (_discriminatorClause == null ? 6 : 4), sql.length()); } return sql; }
Source:
public void test_wrong_decision() throws IOException { final DMNRuntime runtime = roundTripUnmarshalMarshalThenUnmarshalDMN(this.getClass().getResourceAsStream("/wrong_decision.dmn")); DMNModel dmnModel = runtime.getModels().get(0); assertTrue(dmnModel.hasErrors()); DMNMessage m0 = dmnModel.getMessages(DMNMessage.Severity.ERROR).get(0); System.out.println(m0); assertTrue("expected a message identifying the problem on a decision named 'my decision'", m0.getMessage().startsWith("No expression defined for name 'my decision'")); DecisionNode d0 = dmnModel.getDecisionById("_cce32679-9395-444d-a4bf-96af8ee727a0"); org.kie.dmn.model.api.Expression d0le = d0.getDecision().getExpression(); assertTrue(d0le instanceof org.kie.dmn.model.api.LiteralExpression); assertNull(((org.kie.dmn.model.api.LiteralExpression) d0le).getText()); DMNMarshaller m = new DMNMarshaller(new XMLEncoderDiagramMetadataMarshaller(), applicationFactoryManager); Graph<?, ?> g = m.unmarshall(null, this.getClass().getResourceAsStream("/wrong_decision.dmn")); Node<?, ?> decisionNode = g.getNode("_cce32679-9395-444d-a4bf-96af8ee727a0"); assertNodeContentDefinitionIs(decisionNode, Decision.class); View<Decision> view = ((View<Decision>) decisionNode.getContent()); Expression expression = view.getDefinition().getExpression(); assertNotNull(expression); assertEquals(LiteralExpression.class, expression.getClass()); LiteralExpression le = (LiteralExpression) expression; assertNull(le.getText()); }

Target:
public void test_wrong_decision() throws IOException { final DMNRuntime runtime = roundTripUnmarshalMarshalThenUnmarshalDMN(this.getClass().getResourceAsStream("/wrong_decision.dmn")); DMNModel dmnModel = runtime.getModels().get(0); assertTrue(dmnModel.hasErrors()); DMNMessage m0 = dmnModel.getMessages(DMNMessage.Severity.ERROR).get(0); assertTrue("expected a message identifying the problem on a decision named 'my decision'", m0.getMessage().startsWith("No expression defined for name 'my decision'")); DecisionNode d0 = dmnModel.getDecisionById("_cce32679-9395-444d-a4bf-96af8ee727a0"); org.kie.dmn.model.api.Expression d0le = d0.getDecision().getExpression(); assertTrue(d0le instanceof org.kie.dmn.model.api.LiteralExpression); assertNull(((org.kie.dmn.model.api.LiteralExpression) d0le).getText()); DMNMarshaller m = new DMNMarshaller(new XMLEncoderDiagramMetadataMarshaller(), applicationFactoryManager); Graph<?, ?> g = m.unmarshall(null, this.getClass().getResourceAsStream("/wrong_decision.dmn")); Node<?, ?> decisionNode = g.getNode("_cce32679-9395-444d-a4bf-96af8ee727a0"); assertNodeContentDefinitionIs(decisionNode, Decision.class); View<Decision> view = ((View<Decision>) decisionNode.getContent()); Expression expression = view.getDefinition().getExpression(); assertNotNull(expression); assertEquals(LiteralExpression.class, expression.getClass()); LiteralExpression le = (LiteralExpression) expression; assertNull(le.getText()); }
Source:
public AddBondParameters(Guid vdsId, String bondName, Network network, String[] nics, int vladId) { this(vdsId, bondName, network, nics); setVlanId(vladId); privateBootProtocol = NetworkBootProtocol.NONE; }

Target:
public AddBondParameters(Guid vdsId, String bondName, Network network, String[] nics, int vladId) { this(vdsId, bondName, network, nics); setVlanId(vladId); }
Source:
public void setVisible(boolean visible) { boolean previous = this.visible; if ( previous && !visible ) { sendToAffected( removePacket() ); } else if ( !previous && visible ) { sendToAffected( addPacket() ); } this.visible = visible; }

Target:
public void setVisible(boolean visible) { boolean previous = this.visible; if ( previous && !visible ) { sendToAffected( removePacket ); } else if ( !previous && visible ) { sendToAffected( addPacket() ); } this.visible = visible; }
Source:
public ContainerSummaryRequiredException(Item item) { super("Container summary not found so equivalence is being rerun on container with id: " + item.getContainer().getId() + "and then item with id: " + item.getId()); this.item = item; }

Target:
public ContainerSummaryRequiredException(Item item) { super("Container summary not found so equivalence needs to be run on container with id: " + item.getContainer().getId() + "and then item with id: " + item.getId()); this.item = item; }
Source:
public Object eval(Object[] args, EvaluationContext ec) { if(!locationUpdatesRequested) requestLocationUpdates(); if(location == null) return ""; return location.getDisplayText(); }

Target:
public Object eval(Object[] args, EvaluationContext ec) { if (!locationUpdatesRequested) { requestLocationUpdates(); } if (location == null) { return ""; } return location.getDisplayText(); }
Source:
protected String doInBackground(String... params) { String response = ""; Map<String, String> request_params = new HashMap<String, String>(); request_params.put("grant_type", "refresh_token"); request_params.put("refresh_token", token.getRefreshToken()); request_params.put("scope", "PRODUCTION"); APIUtilities apiUtilities = new APIUtilities(); apiUtilities.setEndPoint(IdentityProxy.getInstance().getAccessTokenURL()); apiUtilities.setHttpMethod("POST"); apiUtilities.setRequestParamsMap(request_params); Map<String, String> headers = new HashMap<String, String>(); Log.e("proxy", IdentityProxy.clientID + ":" + IdentityProxy.clientSecret); String authorizationString = "Basic " + new String( Base64.encodeBase64((IdentityProxy.clientID + ":" + IdentityProxy.clientSecret).getBytes()) ); headers.put("Authorization", authorizationString); headers.put("Content-Type", "application/x-www-form-urlencoded"); Map<String, String> response_params = ServerApiAccess.postDataAPI(apiUtilities, headers); response = response_params.get("response"); responseCode = response_params.get("status"); Log.d(TAG, response); return response; }

Target:
protected String doInBackground(String... params) { String response = null; Map<String, String> requestParams = new HashMap<String, String>(); requestParams.put(Constants.GRANT_TYPE, Constants.REFRESH_TOKEN); requestParams.put(Constants.REFRESH_TOKEN, token.getRefreshToken()); requestParams.put(SCOPE_LABEL, PRODUCTION_LABEL); EndPointInfo apiUtilities = new EndPointInfo(); apiUtilities.setEndPoint(IdentityProxy.getInstance().getAccessTokenURL()); apiUtilities.setHttpMethod(HTTP_METHODS.POST); apiUtilities.setRequestParamsMap(requestParams); byte[] credentials = Base64.encodeBase64((IdentityProxy.clientID + COLON + IdentityProxy.clientSecret).getBytes()); String encodedCredentials = new String(credentials); Map<String, String> headers = new HashMap<String, String>(); String authorizationString = Constants.AUTHORIZATION_MODE + encodedCredentials; headers.put(Constants.AUTHORIZATION_HEADER, authorizationString); headers.put(Constants.CONTENT_TYPE_HEADER, Constants.DEFAULT_CONTENT_TYPE); Map<String, String> responseParams = null; try { responseParams = ServerUtilities.postDataAPI(apiUtilities, headers); } catch (IDPTokenManagerException e) { Log.e(TAG, "Failed to contact server." + e); } response = responseParams.get(Constants.SERVER_RESPONSE_BODY); responseCode = responseParams.get(Constants.SERVER_RESPONSE_STATUS); return response; }
Source:
private Answer executeRequest(ShutDownVpcVspCommand cmd) { try { isNuageVspElementLoaded(); _nuageVspElementClient.shutdownVpc(cmd.getDomainUuid(), cmd.getVpcUuid(), cmd.getDomainTemplateName()); return new ShutDownVpcVspAnswer(cmd, true, "Shutdown VPC " + cmd.getVpcUuid()); } catch (Exception e) { s_logger.error("Failure during " + cmd, e); return new ShutDownVpcVspAnswer(cmd, e); } }

Target:
private Answer executeRequest(ShutDownVpcVspCommand cmd) { try { isNuageVspElementLoaded(); _nuageVspElementClient.shutdownVpc(cmd.getDomainUuid(), cmd.getVpcUuid(), cmd.getDomainTemplateName()); return new Answer(cmd, true, "Shutdown VPC " + cmd.getVpcUuid() + " on Nuage VSD " + _hostName); } catch (ExecutionException | ConfigurationException e) { s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e); return new Answer(cmd, e); } }
Source:
public void registerStageTaskRecoveryCallback(StageTaskRecoveryCallback stageTaskRecoveryCallback) { checkState(!this.stageTaskRecoveryCallback.isPresent(), "stageTaskRecoveryCallback should only be registered once"); this.stageTaskRecoveryCallback = Optional.of(stageTaskRecoveryCallback); }

Target:
public synchronized void registerStageTaskRecoveryCallback(StageTaskRecoveryCallback stageTaskRecoveryCallback) { checkState(!this.stageTaskRecoveryCallback.isPresent(), "stageTaskRecoveryCallback should be registered only once"); this.stageTaskRecoveryCallback = Optional.of(requireNonNull(stageTaskRecoveryCallback, "stageTaskRecoveryCallback is null")); }
Source:
public void populate(CoreSession session) throws ClientException { UserManager um = Framework.getLocalService(UserManager.class); Framework.doPrivileged(() -> { if (um != null) { createUsersAndGroups(um); } }); }

Target:
public void populate(CoreSession session) throws ClientException { UserManager um = Framework.getLocalService(UserManager.class); if (um != null) { Framework.doPrivileged(() -> createUsersAndGroups(um)); } }
Source:
private String getDistanceLabel(Location otherLocation) { final int distance = getDistance(otherLocation); if (showImperial) { final double feet = distance * METER_TO_FEET; if (feet < ONE_THOUSAND) { return getString(R.string.nearby_distance_in_feet, (int)feet); } else { return getString(R.string.nearby_distance_in_miles, feet / ONE_MILE); } } else { if (distance < ONE_THOUSAND) { return getString(R.string.nearby_distance_in_meters, distance); } else { return getString(R.string.nearby_distance_in_kilometers, distance / ONE_KM_D); } } }

Target:
private String getDistanceLabel(Location otherLocation) { final int meters = getDistance(otherLocation); if (showImperial) { final double feet = meters * METER_TO_FEET; if (feet < ONE_THOUSAND) { return getString(R.string.nearby_distance_in_feet, (int)feet); } else { return getString(R.string.nearby_distance_in_miles, feet / ONE_MILE); } } else { if (meters < ONE_THOUSAND) { return getString(R.string.nearby_distance_in_meters, meters); } else { return getString(R.string.nearby_distance_in_kilometers, meters / ONE_THOUSAND_D); } } }
Source:
protected Response addVm(VmStatic staticVm, VM vm, Guid storageDomainId, Guid templateId) { VmManagementParametersBase params = new VmManagementParametersBase(staticVm); params.setVmPayload(getPayload(vm)); if (vm.isSetMemoryPolicy() && vm.getMemoryPolicy().isSetBallooning()) { params.setBalloonEnabled(vm.getMemoryPolicy().isBallooning()); } params.setStorageDomainId(storageDomainId); params.setDiskInfoDestinationMap(getDisksToClone(vm.getDisks(), templateId)); params.setMakeCreatorExplicitOwner(shouldMakeCreatorExplicitOwner()); if (vm.isSetConsoleDeviceEnabled()) { params.setConsoleEnabled(vm.isConsoleDeviceEnabled()); } return performCreate(VdcActionType.AddVm, params, new QueryIdResolver<Guid>(VdcQueryType.GetVmByVmId, IdQueryParameters.class)); }

Target:
protected Response addVm(VmStatic staticVm, VM vm, Guid storageDomainId, Guid templateId) { VmManagementParametersBase params = new VmManagementParametersBase(staticVm); params.setVmPayload(getPayload(vm)); if (vm.isSetMemoryPolicy() && vm.getMemoryPolicy().isSetBallooning()) { params.setBalloonEnabled(vm.getMemoryPolicy().isBallooning()); } params.setStorageDomainId(storageDomainId); params.setDiskInfoDestinationMap(getDisksToClone(vm.getDisks(), templateId)); params.setMakeCreatorExplicitOwner(shouldMakeCreatorExplicitOwner()); params.setConsoleEnabled(vm.isSetConsole() && vm.getConsole().isSetEnabled() ? vm.getConsole().isEnabled() : !getConsoleDevicesForEntity(templateId).isEmpty()); return performCreate(VdcActionType.AddVm, params, new QueryIdResolver<Guid>(VdcQueryType.GetVmByVmId, IdQueryParameters.class)); }
Source:
public void completesTerminationFutureExceptionallyIfActorFails() throws Exception { final ActorSystem actorSystem = actorSystemResource.getActorSystem(); final ActorRef supervisor = SupervisorActor.startSupervisorActor(actorSystem); final SupervisorActor.StartAkkaRpcActorResponse startResponse = SupervisorActor.startAkkaRpcActor( supervisor, terminationFuture -> Props.create(SimpleActor.class, terminationFuture), "foobar"); final SupervisorActor.ActorRegistration actorRegistration = startResponse.orElseThrow(cause -> new AssertionError("Expected the start to succeed.", cause)); final CompletableFuture<Void> terminationFuture = actorRegistration.getTerminationFuture(); assertThat(terminationFuture.isDone(), is(false)); final CompletableFuture<Terminated> actorSystemTerminationFuture = actorSystem.getWhenTerminated().toCompletableFuture(); final FlinkException cause = new FlinkException("Test cause."); actorRegistration.getActorRef().tell(Fail.exceptionally(cause), ActorRef.noSender()); try { terminationFuture.get(); fail("Expected the termination future being completed exceptionally"); } catch (ExecutionException expected) { final Throwable ignored = ExceptionUtils.findThrowable(expected, e -> e.equals(cause)) .orElseThrow(() -> new FlinkException("Unexpected exception", expected)); } actorSystemTerminationFuture.join(); }

Target:
public void completesTerminationFutureExceptionallyIfActorFails() throws Exception { final ActorSystem actorSystem = actorSystemResource.getActorSystem(); final ActorRef supervisor = SupervisorActor.startSupervisorActor(actorSystem, actorSystem.getDispatcher()); final SupervisorActor.ActorRegistration actorRegistration = startAkkaRpcActor(supervisor, "foobar"); final CompletableFuture<Void> terminationFuture = actorRegistration.getTerminationFuture(); assertThat(terminationFuture.isDone(), is(false)); final CompletableFuture<Terminated> actorSystemTerminationFuture = actorSystem.getWhenTerminated().toCompletableFuture(); final FlinkException cause = new FlinkException("Test cause."); actorRegistration.getActorRef().tell(Fail.exceptionally(cause), ActorRef.noSender()); try { terminationFuture.get(); fail("Expected the termination future being completed exceptionally"); } catch (ExecutionException expected) { ExceptionUtils.findThrowable(expected, e -> e.equals(cause)) .orElseThrow(() -> new FlinkException("Unexpected exception", expected)); } actorSystemTerminationFuture.join(); }
Source:
private byte[] doCipherAction( byte[] data, byte[] additionalAuthData, byte[] keyBytes, byte[] ivBytes, int opmode) throws AEADBadTagException { try { ByteBuffer secretKeyAndSaltBuffer = ByteBuffer.wrap(keyBytes); byte[] secretKeyBytes = new byte[keyBytes.length - SALT_LEN]; byte[] salt = new byte[SALT_LEN]; secretKeyAndSaltBuffer.get(secretKeyBytes); secretKeyAndSaltBuffer.get(salt); SecretKeySpec key = new SecretKeySpec(secretKeyBytes, getAlgorithmName()); ByteBuffer nonceBuffer = ByteBuffer.allocate(SALT_LEN + ivBytes.length); nonceBuffer.put(salt); nonceBuffer.put(ivBytes); GCMParameterSpec gcmParams = new GCMParameterSpec(mChecksumLen * 8, nonceBuffer.array()); mCipher.init(opmode, key, gcmParams); mCipher.updateAAD(additionalAuthData); ByteBuffer inputBuffer = ByteBuffer.wrap(data); int outputLen = data.length; if (opmode == Cipher.ENCRYPT_MODE) outputLen += mChecksumLen; ByteBuffer outputBuffer = ByteBuffer.allocate(outputLen); mCipher.doFinal(inputBuffer, outputBuffer); return outputBuffer.array(); } catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | ShortBufferException e) { if (e instanceof AEADBadTagException) { throw (AEADBadTagException) e; } String errorMessage = Cipher.ENCRYPT_MODE == opmode ? "Failed to encrypt data: " : "Failed to decrypt data: "; throw new IllegalArgumentException(errorMessage, e); } }

Target:
private byte[] doCipherAction( byte[] data, byte[] additionalAuthData, byte[] keyBytes, byte[] ivBytes, int opmode) throws AEADBadTagException { try { ByteBuffer secretKeyAndSaltBuffer = ByteBuffer.wrap(keyBytes); byte[] secretKeyBytes = new byte[keyBytes.length - mSaltLen]; byte[] salt = new byte[mSaltLen]; secretKeyAndSaltBuffer.get(secretKeyBytes); secretKeyAndSaltBuffer.get(salt); SecretKeySpec key = new SecretKeySpec(secretKeyBytes, getAlgorithmName()); ByteBuffer nonceBuffer = ByteBuffer.allocate(mSaltLen + ivBytes.length); nonceBuffer.put(salt); nonceBuffer.put(ivBytes); GCMParameterSpec gcmParams = new GCMParameterSpec(mChecksumLen * 8, nonceBuffer.array()); mCipher.init(opmode, key, gcmParams); mCipher.updateAAD(additionalAuthData); ByteBuffer inputBuffer = ByteBuffer.wrap(data); int outputLen = data.length; if (opmode == Cipher.ENCRYPT_MODE) outputLen += mChecksumLen; ByteBuffer outputBuffer = ByteBuffer.allocate(outputLen); mCipher.doFinal(inputBuffer, outputBuffer); return outputBuffer.array(); } catch (AEADBadTagException e) { throw (AEADBadTagException) e; } catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | ShortBufferException e) { String errorMessage = Cipher.ENCRYPT_MODE == opmode ? "Failed to encrypt data: " : "Failed to decrypt data: "; throw new IllegalArgumentException(errorMessage, e); } }
Source:
public void close() throws IOException { if(!completedFiles.isEmpty()) { for(File file: completedFiles) { file.delete(); } throw new ISE(String.format("%d writers needs to be closed before closing smoosher.", filesInProcess.size())); } if (currOut != null) { currOut.close(); } File metaFile = metaFile(baseDir); try (Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(metaFile), Charsets.UTF_8))) { out.write(String.format("v1,%d,%d", maxChunkSize, outFiles.size())); out.write("\n"); for (Map.Entry<String, Metadata> entry : internalFiles.entrySet()) { final Metadata metadata = entry.getValue(); out.write( joiner.join( entry.getKey(), metadata.getFileNum(), metadata.getStartOffset(), metadata.getEndOffset() ) ); out.write("\n"); } } }

Target:
public void close() throws IOException { if (!completedFiles.isEmpty() || !filesInProcess.isEmpty()) { for (File file: completedFiles) { file.delete(); } for (File file: filesInProcess) { file.delete(); } throw new ISE(String.format("%d writers needs to be closed before closing smoosher.", filesInProcess.size() + completedFiles.size())); } if (currOut != null) { currOut.close(); } File metaFile = metaFile(baseDir); try (Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(metaFile), Charsets.UTF_8))) { out.write(String.format("v1,%d,%d", maxChunkSize, outFiles.size())); out.write("\n"); for (Map.Entry<String, Metadata> entry : internalFiles.entrySet()) { final Metadata metadata = entry.getValue(); out.write( joiner.join( entry.getKey(), metadata.getFileNum(), metadata.getStartOffset(), metadata.getEndOffset() ) ); out.write("\n"); } } }
Source:
public void handle(String tenantId, List<T> items) throws Exception { List<R> results = null; List<T> retries = null; Exception lastException = null; processor.initialise(tenantId, items); if (processor.getType() == ProcessorType.ManyToMany) { try { results = processor.processManyToMany(tenantId, items); } catch (Exception e) { retries = items; } } else { for (int i = 0; i < items.size(); i++) { try { if (processor.getType() == ProcessorType.OneToMany) { List<R> result = processor.processOneToMany(tenantId, items.get(i)); if (resultHandler != null && result != null && !result.isEmpty()) { if (results == null) { results = new ArrayList<R>(); } results.addAll(result); } } else { R result = processor.processOneToOne(tenantId, items.get(i)); if (resultHandler != null && result != null) { if (results == null) { results = new ArrayList<R>(); } results.add(result); } } } catch (Exception e) { if (retryHandler != null) { if (retries == null) { retries = new ArrayList<T>(); } retries.add(items.get(i)); lastException = e; } } } } processor.cleanup(tenantId, items); if (results != null && !results.isEmpty()) { resultHandler.handle(tenantId, results); } if (retries != null && !retries.isEmpty()) { if (getRetryCount() > 0) { retryHandler.handle(tenantId, retries); } else { throw lastException; } } }

Target:
public void handle(String tenantId, List<T> items) throws Exception { List<R> results = null; List<T> retries = null; Exception lastException = null; processor.initialise(tenantId, items); long startTime = 0; if (perfLog.isLoggable(Level.FINEST)) { startTime = System.currentTimeMillis(); } if (processor.getType() == ProcessorType.ManyToMany) { try { results = processor.processManyToMany(tenantId, items); } catch (Exception e) { retries = items; } } else { for (int i = 0; i < items.size(); i++) { try { if (processor.getType() == ProcessorType.OneToMany) { List<R> result = processor.processOneToMany(tenantId, items.get(i)); if (resultHandler != null && result != null && !result.isEmpty()) { if (results == null) { results = new ArrayList<R>(); } results.addAll(result); } } else { R result = processor.processOneToOne(tenantId, items.get(i)); if (resultHandler != null && result != null) { if (results == null) { results = new ArrayList<R>(); } results.add(result); } } } catch (Exception e) { if (retryHandler != null) { if (retries == null) { retries = new ArrayList<T>(); } retries.add(items.get(i)); lastException = e; } } } } if (perfLog.isLoggable(Level.FINEST)) { perfLog.finest("Performance: invoked processor +processor.getClass().getSimpleName()+ duration=" + (System.currentTimeMillis() - startTime) + "ms"); } processor.cleanup(tenantId, items); if (results != null && !results.isEmpty()) { resultHandler.handle(tenantId, results); } if (retries != null && !retries.isEmpty()) { if (getRetryCount() > 0) { retryHandler.handle(tenantId, retries); } else { throw lastException; } } }
Source:
public IStatus validateBeforeSet(Object value) { final BundleContext bundleContext = FrameworkUtil .getBundle(getClass()) .getBundleContext(); final ServiceReference<PreSetValidationService> serviceReference = bundleContext .getServiceReference(PreSetValidationService.class); final PreSetValidationService service = bundleContext.getService(serviceReference); if (service == null) { return Status.OK_STATUS; } final Diagnostic result = service.validate(eStructuralFeature, value); if (result.getSeverity() == Diagnostic.OK) { return Status.OK_STATUS; } final VDiagnostic vDiagnostic = VViewFactory.eINSTANCE.createDiagnostic(); vDiagnostic.getDiagnostics().add(result); vElement.setDiagnostic(vDiagnostic); return BasicDiagnostic.toIStatus(result); }

Target:
public IStatus validateBeforeSet(Object value) { final BundleContext bundleContext = FrameworkUtil .getBundle(getClass()) .getBundleContext(); final ServiceReference<PreSetValidationService> serviceReference = bundleContext .getServiceReference(PreSetValidationService.class); if (serviceReference == null) { return super.validateBeforeSet(value); } try { final PreSetValidationService service = bundleContext.getService(serviceReference); if (service == null) { return super.validateBeforeSet(value); } final Diagnostic result = service.validate(eStructuralFeature, value); if (result.getSeverity() == Diagnostic.OK) { return Status.OK_STATUS; } final VDiagnostic vDiagnostic = VViewFactory.eINSTANCE.createDiagnostic(); vDiagnostic.getDiagnostics().add(result); vElement.setDiagnostic(vDiagnostic); return BasicDiagnostic.toIStatus(result); } finally { bundleContext.ungetService(serviceReference); } }
Source:
public void testTaskManagerTimeoutDoesNotRemoveSlots() throws Exception { final Time taskManagerTimeout = Time.milliseconds(10L); final ResourceManagerId resourceManagerId = ResourceManagerId.generate(); final ResourceID resourceID = ResourceID.generate(); final CompletableFuture<InstanceID> releaseResourceFuture = new CompletableFuture<>(); final ResourceActions resourceActions = new TestingResourceActionsBuilder() .setReleaseResourceConsumer((instanceId, ignored) -> releaseResourceFuture.complete(instanceId)) .build(); final TaskExecutorGateway taskExecutorGateway = new TestingTaskExecutorGatewayBuilder().createTestingTaskExecutorGateway(); final TaskExecutorConnection taskExecutorConnection = new TaskExecutorConnection(resourceID, taskExecutorGateway); final SlotStatus slotStatus = createEmptySlotStatus(new SlotID(resourceID, 0), ResourceProfile.fromResources(1.0, 1)); final SlotReport initialSlotReport = new SlotReport(slotStatus); try (final SlotManager slotManager = createSlotManagerBuilder() .setTaskManagerTimeout(taskManagerTimeout) .setRedundantSlotNum(0) .buildAndStartWithDirectExec(resourceManagerId, resourceActions)) { slotManager.registerTaskManager(taskExecutorConnection, initialSlotReport); assertEquals(1, slotManager.getNumberRegisteredSlots()); assertThat(releaseResourceFuture.get(), is(taskExecutorConnection.getInstanceID())); assertEquals(1, slotManager.getNumberRegisteredSlots()); slotManager.unregisterTaskManager(taskExecutorConnection.getInstanceID(), TEST_EXCEPTION); assertEquals(0, slotManager.getNumberRegisteredSlots()); } }

Target:
public void testTaskManagerTimeoutDoesNotRemoveSlots() throws Exception { final Time taskManagerTimeout = Time.milliseconds(10L); final ResourceManagerId resourceManagerId = ResourceManagerId.generate(); final ResourceID resourceID = ResourceID.generate(); final CompletableFuture<InstanceID> releaseResourceFuture = new CompletableFuture<>(); final ResourceActions resourceActions = new TestingResourceActionsBuilder() .setReleaseResourceConsumer((instanceId, ignored) -> releaseResourceFuture.complete(instanceId)) .build(); final TaskExecutorGateway taskExecutorGateway = new TestingTaskExecutorGatewayBuilder().createTestingTaskExecutorGateway(); final TaskExecutorConnection taskExecutorConnection = new TaskExecutorConnection(resourceID, taskExecutorGateway); final SlotStatus slotStatus = createEmptySlotStatus(new SlotID(resourceID, 0), ResourceProfile.fromResources(1.0, 1)); final SlotReport initialSlotReport = new SlotReport(slotStatus); try (final SlotManager slotManager = createSlotManagerBuilder() .setTaskManagerTimeout(taskManagerTimeout) .setRedundantTaskManagerNum(0) .buildAndStartWithDirectExec(resourceManagerId, resourceActions)) { slotManager.registerTaskManager(taskExecutorConnection, initialSlotReport); assertEquals(1, slotManager.getNumberRegisteredSlots()); assertThat(releaseResourceFuture.get(), is(taskExecutorConnection.getInstanceID())); assertEquals(1, slotManager.getNumberRegisteredSlots()); slotManager.unregisterTaskManager(taskExecutorConnection.getInstanceID(), TEST_EXCEPTION); assertEquals(0, slotManager.getNumberRegisteredSlots()); } }
Source:
public void addAdminUserToOrganization( UserInfo user, OrganizationInfo organization, boolean email ) throws Exception { if ( ( user == null ) || ( organization == null ) ) { return; } EntityManager em = emf.getEntityManager( smf.getManagementAppId() ); if(em.getCollection(organization.getUuid() ,"users",Query.fromQL( "select * where uuid ="+user.getUuid() ),Level.IDS ).size() >0){ logger.trace( "Found value: already in collection",user.getName() ); return; } em.addToCollection(new SimpleEntityRef(Group.ENTITY_TYPE, organization.getUuid()), "users", new SimpleEntityRef(User.ENTITY_TYPE, user.getUuid())); if ( email ) { sendAdminUserInvitedEmail( user, organization ); } }

Target:
public void addAdminUserToOrganization( UserInfo user, OrganizationInfo organization, boolean email ) throws Exception { if ( ( user == null ) || ( organization == null ) ) { return; } EntityManager em = emf.getEntityManager( smf.getManagementAppId() ); if(em.getCollection(organization.getUuid() ,"users",Query.fromQL( "select * where uuid ="+user.getUuid() ),Level.IDS ).size() >0){ if(logger.isDebugEnabled()) { logger.debug( "Found value: already in collection", user.getName() ); } return; } em.addToCollection(new SimpleEntityRef(Group.ENTITY_TYPE, organization.getUuid()), "users", new SimpleEntityRef(User.ENTITY_TYPE, user.getUuid())); if ( email ) { sendAdminUserInvitedEmail( user, organization ); } }
Source:
public RedisConfiguration(ConfigurationPropertyReader propertyReader) { String host = propertyReader.property( OgmProperties.HOST, String.class ) .withDefault( DEFAULT_HOST ) .getValue(); Integer port = propertyReader.property( OgmProperties.PORT, Integer.class ) .withValidator( Validators.PORT ) .withDefault( null ) .getValue(); hosts = HostParser.parse( host, port, DEFAULT_PORT ); databaseNumber = propertyReader.property( OgmProperties.PORT, Integer.class ) .withValidator( Validators.PORT ) .withDefault( RedisURI.DEFAULT_REDIS_PORT ) .getValue(); this.password = propertyReader.property( OgmProperties.PASSWORD, String.class ).getValue(); }

Target:
public RedisConfiguration(ConfigurationPropertyReader propertyReader) { String host = propertyReader.property( OgmProperties.HOST, String.class ) .withDefault( DEFAULT_HOST ) .getValue(); this.hosts = HostParser.parse( host, null, DEFAULT_PORT ); this.databaseNumber = propertyReader.property( OgmProperties.DATABASE, Integer.class ) .withValidator( DATABASE_VALIDATOR ) .withDefault( DEFAULT_DATABASE ) .getValue(); this.password = propertyReader.property( OgmProperties.PASSWORD, String.class ).getValue(); this.timeout = propertyReader .property( RedisProperties.TIMEOUT, Integer.class ) .withDefault( (int) DEFAULT_TIMEOUT ) .getValue(); this.ssl = propertyReader .property( RedisProperties.SSL, boolean.class ) .withDefault( false ) .getValue(); }
Source:
public String removeQualifierFromRuleText( String ruleText ) { if( ruleText.startsWith( "%" ) && ruleText.endsWith( "%" ) ) { return ruleText.substring( 1, ruleText.length() - 1 ); } else if( ruleText.startsWith( "%" ) ) { return ruleText.substring( 1 ); } else if( ruleText.endsWith( "%" ) ) { return ruleText.substring( 0, ruleText.length() - 1 ); } else { return ruleText; } }

Target:
public String removeQualifierFromRuleText( String ruleText ) { String rule = ruleText; if( rule.startsWith( "%" ) ) { rule = rule.substring( 1 ); } if( rule.endsWith( "%" ) ) { rule = rule.substring( 0, rule.length() - 1 ); } return rule; }
Source:
public Map<Cell, Value> getRows(TableReference tableRef, Iterable<byte[]> rows, ColumnSelection columnSelection, long timestamp) { return maybeLog(() -> delegate.getRows(tableRef, rows, columnSelection, timestamp), (logger, stopwatch) -> logger.log( "Call to KVS.getRows on table requesting columns from rows took ms ", tableRef, columnSelection.allColumnsSelected() ? "all" : Iterables.size(columnSelection.getSelectedColumns()), Iterables.size(rows), stopwatch.elapsed(TimeUnit.MILLISECONDS)), (logger, result) -> { long sizeInBytes = 0; for (Entry<Cell, Value> entry : result.entrySet()) { sizeInBytes += Cells.getApproxSizeOfCell(entry.getKey()) + entry.getValue().getContents().length; } logger.log("and returned bytes.", sizeInBytes); }); }

Target:
public Map<Cell, Value> getRows(TableReference tableRef, Iterable<byte[]> rows, ColumnSelection columnSelection, long timestamp) { return maybeLog(() -> delegate.getRows(tableRef, rows, columnSelection, timestamp), (logger, stopwatch) -> logger.log( "Call to KVS.getRows on table requesting columns from rows took ms ", tableRef, columnSelection.allColumnsSelected() ? "all" : Iterables.size(columnSelection.getSelectedColumns()), Iterables.size(rows), stopwatch.elapsed(TimeUnit.MILLISECONDS)), logCellResultSize(0L)); }
Source:
public ChainFilter() { this(RowFilter.Chain.newBuilder()); }

Target:
private ChainFilter() { this(RowFilter.Chain.newBuilder()); }
Source:
public FeatureFinderMetaboDetector(File mzMLFile) throws FeatureFinderMetaboException { this.mzMLFile = mzMLFile; FEATURE_XML_FILE = new File(mzMLFile.getName() + "featureXML"); OPENMS_FEATURE_FINDER_METABO_LIBRARY_NAME = FeatureFinderMetaboLocator.findFeatureFinderMetabo(); }

Target:
public FeatureFinderMetaboDetector(File mzMLFile) throws MSDKException { this.mzMLFile = mzMLFile; FEATURE_XML_FILE = new File(System.getProperty("java.io.tmpdir") + UUID.randomUUID() + ".featureXML"); OPENMS_FEATURE_FINDER_METABO_LIBRARY_NAME = FeatureFinderMetaboLocator.findFeatureFinderMetabo(); mzMLFILE_PATH = mzMLFile.getAbsolutePath(); FEATURE_XML_FILE_PATH = FEATURE_XML_FILE.getAbsolutePath(); }
Source:
public Identity decode(final byte[] bytes) throws IOException { final String[] parts = new Utf8String(bytes).asString().split(";"); final Map<String, String> map = new HashMap<>(parts.length); for (int idx = 1; idx < parts.length; ++idx) { final String[] pair = parts[idx].split("="); try { map.put(pair[0], CcPlain.decode(pair[1])); } catch (final IllegalArgumentException ex) { throw new DecodingException(ex); } } return new Identity.Simple(CcPlain.decode(parts[0]), map); }

Target:
public Identity decode(final byte[] bytes) throws IOException { final List<Text> parts = new ListOf<>( new SplitText( new Utf8String(bytes), ";" ) ); final Map<String, String> map = new HashMap<>(parts.size()); for (int idx = 1; idx < parts.size(); ++idx) { final List<Text> pair = new ListOf<>( new SplitText(parts.get(idx), "=") ); try { map.put( new UncheckedText(pair.get(0)).asString(), CcPlain.decode(new UncheckedText(pair.get(1)).asString()) ); } catch (final IllegalArgumentException ex) { throw new DecodingException(ex); } } return new Identity.Simple( CcPlain.decode( new UncheckedText(parts.get(0)).asString() ), map ); }
Source:
public void testAddDropColumn() throws Exception { Connection conn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL); conn.setAutoCommit(true); try { conn.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " (tenant_id, id, tenant_col) values ('" + TENANT_ID + "', 1, 'Viva Las Vegas')"); conn.createStatement().execute("alter table " + TENANT_TABLE_NAME + " add tenant_col2 char(1) null"); int count = conn.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " (tenant_id, id, tenant_col2) values ('" + TENANT_ID + "', 2, 'a')"); ResultSet rs = conn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME); rs.next(); assertEquals(2, rs.getInt(1)); rs = conn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME + " where tenant_col2 = 'a'"); rs.next(); assertEquals(1, rs.getInt(1)); conn.createStatement().execute("alter table " + TENANT_TABLE_NAME + " drop column tenant_col"); rs = conn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME + ""); rs.next(); assertEquals(2, rs.getInt(1)); try { rs = conn.createStatement().executeQuery("select tenant_col from TENANT_TABLE"); } catch (ColumnNotFoundException expected) } finally { conn.close(); } }

Target:
public void testAddDropColumn() throws Exception { Connection conn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL); conn.setAutoCommit(true); try { conn.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " (id, tenant_col) values (1, 'Viva Las Vegas')"); conn.createStatement().execute("alter table " + TENANT_TABLE_NAME + " add tenant_col2 char(1) null"); conn.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " (id, tenant_col2) values (2, 'a')"); ResultSet rs = conn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME); rs.next(); assertEquals(2, rs.getInt(1)); rs = conn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME + " where tenant_col2 = 'a'"); rs.next(); assertEquals(1, rs.getInt(1)); conn.createStatement().execute("alter table " + TENANT_TABLE_NAME + " drop column tenant_col"); rs = conn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME + ""); rs.next(); assertEquals(2, rs.getInt(1)); try { rs = conn.createStatement().executeQuery("select tenant_col from TENANT_TABLE"); fail(); } catch (ColumnNotFoundException expected) } finally { conn.close(); } }
Source:
private String determineJdbcUrl() { StringBuilder url = new StringBuilder(); if (StringUtils.hasText(getJdbcUrl())) { url.append(getJdbcUrl()); } else { url.append("jdbc:mysql://"); url.append(getHost()).append(":").append(getPort()); url.append("/").append(getDb()); url.append("?autoReconnect=true"); url.append("&useSSL=").append(isUseSsl()); url.append("&useUnicode=yes&characterEncoding=UTF-8"); } return url.toString(); }

Target:
private String determineJdbcUrl() { if (StringUtils.hasText(getJdbcUrl())) { return getJdbcUrl(); } StringBuilder url = new StringBuilder(); url.append("jdbc:mysql://"); url.append(getHost()).append(":").append(getPort()); url.append("/").append(getDb()); url.append("?autoReconnect=true"); url.append("&useSSL=").append(isUseSsl()); url.append("&useUnicode=yes&characterEncoding=UTF-8"); return url.toString(); }
Source:
public static String getPlayerNameFromUUID(UUID uuid) { PlayerProfileCache cache = MinecraftServer.getServer().func_152358_ax(); GameProfile maybeGameProfile = cache.func_152652_a( uuid ); if ( maybeGameProfile != null ) { return maybeGameProfile.getName(); } return null; }

Target:
public static String getPlayerNameFromUUID(UUID uuid) { return UsernameCache.getLastKnownUsername(uuid); }
Source:
public void sendRequest(Exchange exchange,final Request request) { if (request.getMID() == Message.NONE) { request.setMID(currendMID.getAndIncrement()%(1<<16)); } KeyMID idByMID = new KeyMID(request.getMID()); KeyToken idByToken; if (request.getToken() == null) { idByToken = createUnusedToken(); request.setToken(idByToken.token); if (exchange.getRequest() != null && exchange.getRequest().getToken() == null) exchange.getRequest().setToken(idByToken.token); } else { idByToken = new KeyToken(request.getToken()); if (!(exchange.getFailedTransmissionCount()>0 || request.getOptions().hasBlock1() || request.getOptions().hasBlock2() || request.getOptions().hasObserve()) && exchangesByToken.get(idByToken) != null) { LOGGER.log(Level.WARNING, "Manual token overrides existing open request: {0}", idByToken); } } if ( request.getOptions().hasObserve() && request.getOptions().getObserve() == 0 && !request.getOptions().hasBlock2()) { observeRequestStore.add(request); request.addMessageObserver(new MessageObserverAdapter() { @Override public void onCancel() { observeRequestStore.remove(request.getToken()); } @Override public void onReject() { observeRequestStore.remove(request.getToken()); } @Override public void onTimeout() { observeRequestStore.remove(request.getToken()); } }); } exchange.setObserver(exchangeObserver); LOGGER.log(Level.FINE, "Tracking open request using {0}, {1}", new Object[]{idByMID, idByToken}); exchangesByMID.put(idByMID, exchange); exchangesByToken.put(idByToken, exchange); }

Target:
public void sendRequest(Exchange exchange,final Request request) { if (request.getMID() == Message.NONE) { request.setMID(currendMID.getAndIncrement()%(1<<16)); } KeyMID idByMID = new KeyMID(request.getMID()); KeyToken idByToken; if (request.getToken() == null) { idByToken = createUnusedToken(); request.setToken(idByToken.token); if (exchange.getRequest() != null && exchange.getRequest().getToken() == null) exchange.getRequest().setToken(idByToken.token); } else { idByToken = new KeyToken(request.getToken()); if (!(exchange.getFailedTransmissionCount()>0 || request.getOptions().hasBlock1() || request.getOptions().hasBlock2() || request.getOptions().hasObserve()) && exchangesByToken.get(idByToken) != null) { LOGGER.log(Level.WARNING, "Manual token overrides existing open request: {0}", idByToken); } } if (request.getOptions().hasObserve() && request.getOptions().getObserve() == 0 && (!request.getOptions().hasBlock2() || request.getOptions().getBlock2().getNum() == 0 && !request.getOptions().getBlock2().isM())) { observationStore.add(new Observation(request, null)); request.addMessageObserver(new MessageObserverAdapter() { @Override public void onCancel() { observationStore.remove(request.getToken()); } @Override public void onReject() { observationStore.remove(request.getToken()); } @Override public void onTimeout() { observationStore.remove(request.getToken()); } }); } exchange.setObserver(exchangeObserver); LOGGER.log(Level.FINE, "Tracking open request using {0}, {1}", new Object[]{idByMID, idByToken}); exchangesByMID.put(idByMID, exchange); exchangesByToken.put(idByToken, exchange); }