auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Status delete(final String table, final String key) { try { final Response searchResponse = search(table, key); final int statusCode = searchResponse.getStatusLine().getStatusCode(); if (statusCode == 404) { return Status.NOT_FOUND; } else if (statusCode != 200) { return Status.ERROR; } final Map<String, Object> map = map(searchResponse); @SuppressWarnings("unchecked") final Map<String, Object> hits = (Map<String, Object>)map.get("hits"); final int total = (int)hits.get("total"); if (total == 0) { return Status.NOT_FOUND; } @SuppressWarnings("unchecked") final Map<String, Object> hit = (Map<String, Object>)((List<Object>)hits.get("hits")).get(0); final Response deleteResponse = restClient.performRequest("DELETE", "/" + indexKey + "/" + table + "/" + hit.get("_id")); if (deleteResponse.getStatusLine().getStatusCode() != 200) { return Status.ERROR; } if (!isRefreshNeeded) { synchronized (this) { isRefreshNeeded = true; } } return Status.OK; } catch (final Exception e) { <START> e.printStackTrace(); <END> return Status.ERROR; } }</code><technical_language>Exception#printStackTrace stderr default</technical_language>

Target:
public Status delete(final String table, final String key) { try { final Response searchResponse = search(table, key); final int statusCode = searchResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_NOT_FOUND) { return Status.NOT_FOUND; } else if (statusCode != HttpStatus.SC_OK) { return Status.ERROR; } final Map<String, Object> map = map(searchResponse); @SuppressWarnings("unchecked") final Map<String, Object> hits = (Map<String, Object>)map.get("hits"); final int total = (int)hits.get("total"); if (total == 0) { return Status.NOT_FOUND; } @SuppressWarnings("unchecked") final Map<String, Object> hit = (Map<String, Object>)((List<Object>)hits.get("hits")).get(0); final Response deleteResponse = restClient.performRequest("DELETE", "/" + indexKey + "/" + table + "/" + hit.get("_id")); if (deleteResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { return Status.ERROR; } if (!isRefreshNeeded) { synchronized (this) { isRefreshNeeded = true; } } return Status.OK; } catch (final Exception e) { e.printStackTrace(); return Status.ERROR; } }
Source:
<code>void getters() { assertEquals("getValue", getterName(Object.class, "value")); assertEquals("isBlue", getterName(Boolean.TYPE, "isBlue")); <START> assertEquals("isBlue", getterName(Boolean.TYPE, "blue")); <END> assertEquals("getBlue", getterName(Boolean.class, "blue")); assertEquals("getIsBlue", getterName(Boolean.class, "isBlue")); }</code><technical_language>Oh, I this! boolean.class though</technical_language>

Target:
void getters() { assertEquals("getValue", getterName(Object.class, "value")); assertEquals("isBlue", getterName(boolean.class, "isBlue")); assertEquals("isBlue", getterName(boolean.class, "blue")); assertEquals("getBlue", getterName(Boolean.class, "blue")); assertEquals("getIsBlue", getterName(Boolean.class, "isBlue")); }
Source:
<code>public void testDeleteCompletedWorkflowForcefully() throws Exception { String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder = new Workflow.Builder(workflowName); JobConfig.Builder jobBuilder0 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(1).setWorkflow(workflowName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); JobConfig.Builder jobBuilder1 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(1).setWorkflow(workflowName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); JobConfig.Builder jobBuilder2 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(1).setWorkflow(workflowName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); builder.addParentChildDependency("JOB0", "JOB1"); builder.addParentChildDependency("JOB0", "JOB2"); builder.addJob("JOB0", jobBuilder0); builder.addJob("JOB1", jobBuilder1); builder.addJob("JOB2", jobBuilder2); _driver.start(builder.build()); boolean isWorkflowCompleted = TestHelper.verify(() -> { WorkflowContext wCtx1 = _driver.getWorkflowContext(workflowName); return (wCtx1 != null && wCtx1.getWorkflowState() == TaskState.COMPLETED); }, 60 * 1000); Assert.assertTrue(isWorkflowCompleted); Assert.assertNotNull(_driver.getWorkflowConfig(workflowName)); Assert.assertNotNull(_driver.getWorkflowContext(workflowName)); Assert.assertNotNull(admin.getResourceIdealState(CLUSTER_NAME, workflowName)); admin.enableCluster(CLUSTER_NAME, false); <START> Thread.sleep(Disable_Delay); <END> _driver.delete(workflowName, true); Thread.sleep(DELETE_DELAY); admin.enableCluster(CLUSTER_NAME, true); Assert.assertNull(_driver.getWorkflowConfig(workflowName)); Assert.assertNull(_driver.getWorkflowContext(workflowName)); Assert.assertNull(admin.getResourceIdealState(CLUSTER_NAME, workflowName)); }</code><technical_language>Avoid Thread.sleep</technical_language>

Target:
public void testDeleteCompletedWorkflowForcefully() throws Exception { String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder = createCustomWorkflow(workflowName, SHORT_EXECUTION_TIME, "0"); _driver.start(builder.build()); _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); Assert.assertNotNull(_driver.getWorkflowConfig(workflowName)); Assert.assertNotNull(_driver.getWorkflowContext(workflowName)); Assert.assertNotNull(_admin.getResourceIdealState(CLUSTER_NAME, workflowName)); _controller.syncStop(); _driver.delete(workflowName, true); boolean isWorkflowDeleted = TestHelper.verify(() -> { WorkflowConfig wfcfg = _driver.getWorkflowConfig(workflowName); WorkflowContext wfctx = _driver.getWorkflowContext(workflowName); IdealState is = _admin.getResourceIdealState(CLUSTER_NAME, workflowName); return (wfcfg == null && wfctx == null && is == null); }, 60 * 1000); Assert.assertTrue(isWorkflowDeleted); }
Source:
<code>private synchronized void loadColumnDefintions(VitroRequest vitroRequest) { if (!loadedColumnDefinitions) { loadedColumnDefinitions = true; ConfigurationProperties properties = ConfigurationProperties.getBean(vitroRequest); if (properties != null) { String groupsDefsStr = properties.getProperty("histogram.groups"); if (!StringUtils.isEmpty(groupsDefsStr)) { Map<String, String[]> loadedGroupsTypeMap = new HashMap<>(); String[] loadedGroups = groupsDefsStr.split("\\s*,\\s*"); for (String group : loadedGroups) { if (StringUtils.isEmpty(group)) { log.error("Error in groups definition for publications count: " + groupsDefsStr); return; } String typeStr = properties.getProperty("histogram.types.for." + group); <START> String[] types = null; <END> if (StringUtils.isEmpty(typeStr)) { log.error("Error in type definition for publication count: histogram.types.for." + group); return; } loadedGroupsTypeMap.put(group, typeStr.split("\\s*,\\s*")); } pubsGroups = loadedGroups; groupTypeMap = loadedGroupsTypeMap; } } } }</code><technical_language>This local variable appears unused. Suggestion remove</technical_language>

Target:
private synchronized void loadColumnDefintions(VitroRequest vitroRequest) { if (!loadedColumnDefinitions) { loadedColumnDefinitions = true; ConfigurationProperties properties = ConfigurationProperties.getBean(vitroRequest); if (properties != null) { String groupsDefsStr = properties.getProperty("histogram.groups"); if (!StringUtils.isEmpty(groupsDefsStr)) { Map<String, String[]> loadedGroupsTypeMap = new HashMap<>(); String[] loadedGroups = groupsDefsStr.split("\\s*,\\s*"); for (String group : loadedGroups) { if (StringUtils.isEmpty(group)) { log.error("Error in groups definition for publications count: " + groupsDefsStr); return; } String typeStr = properties.getProperty("histogram.types.for." + group); if (StringUtils.isEmpty(typeStr)) { log.error("Error in type definition for publication count: histogram.types.for." + group); return; } loadedGroupsTypeMap.put(group, typeStr.split("\\s*,\\s*")); } pubsGroups = loadedGroups; groupTypeMap = loadedGroupsTypeMap; } } } }
Source:
<code>private boolean synchronizeParticipantUrlWithCoordinator(final ParticipantInformation participantInformation) { final String participantUrl = getParticipantUrl(participantInformation.getId()); <START> Client client = ClientBuilder.newClient(); <END> Link participantLink = Link.fromUri(participantUrl).title(TxLinkNames.PARTICIPANT_RESOURCE).rel(TxLinkNames.PARTICIPANT_RESOURCE).type(TxMediaType.PLAIN_MEDIA_TYPE).build(); Link terminatorLink = Link.fromUri(participantUrl).title(TxLinkNames.PARTICIPANT_TERMINATOR).rel(TxLinkNames.PARTICIPANT_TERMINATOR).type(TxMediaType.PLAIN_MEDIA_TYPE).build(); Response response = client.target(participantInformation.getRecoveryURL()).request().header("Link", participantLink).get(); try { if (response.getStatus() == 404) { return false; } } catch (Exception e) { LOG.warn(e.getMessage(), e); return false; } return true; }</code><technical_language>This created needed. This variable reused</technical_language>

Target:
private boolean synchronizeParticipantUrlWithCoordinator(final ParticipantInformation participantInformation) { final String participantUrl = getParticipantUrl(participantInformation.getId()); Client client = ClientBuilder.newClient(); Link participantLink = Link.fromUri(participantUrl).title(TxLinkNames.PARTICIPANT_RESOURCE).rel(TxLinkNames.PARTICIPANT_RESOURCE).type(TxMediaType.PLAIN_MEDIA_TYPE).build(); Link terminatorLink = Link.fromUri(participantUrl).title(TxLinkNames.PARTICIPANT_TERMINATOR).rel(TxLinkNames.PARTICIPANT_TERMINATOR).type(TxMediaType.PLAIN_MEDIA_TYPE).build(); Response response = client.target(participantInformation.getRecoveryURL()).request() .header("Link", participantLink).header("Link", terminatorLink).put(null); try { if (response.getStatus() == 404) { return false; } } catch (Exception e) { LOG.warn(e.getMessage(), e); return false; } return true; }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpSession session = req.getSession(); if (!FiltersHelper.isAuthenticated(req)) { chain.doFilter(request, response); String headerValue = req.getHeader("Authorization"); <START> if (headerValue != null && headerValue.startsWith("Basic")) { <END> String credentials = headerValue.substring("Basic".length()).trim(); String userPass = new String(Base64.decodeBase64(credentials), Charset.defaultCharset().toString()); String[] creds = userPass.split(":", 2); if (creds != null && creds.length == 2) { storeCredentialsOnSession(session, creds[0], creds[1], getSeparator(creds[0])); } } } chain.doFilter(request, response); }</code><technical_language>"Basic "</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; if (!FiltersHelper.isAuthenticated(req)) { chain.doFilter(request, response); String headerValue = req.getHeader("Authorization"); if (headerValue != null && headerValue.startsWith("Basic ")) { String credentials = headerValue.substring("Basic".length()); String userPass = new String(Base64.decodeBase64(credentials), Charset.defaultCharset().toString()); String[] creds = userPass.split(":", 2); if (creds != null && creds.length == 2) { handleCredentials(request, creds[0], creds[1], getSeparator(creds[0])); } } } chain.doFilter(request, response); }
Source:
<code>public String toString(T pojo) { try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); ObjectWriter writer = mapper.writer(); return writer.writeValueAsString(pojo); } catch (IOException e) { <START> DTThrowable.wrapIfChecked(e); <END> } return null; }</code><technical_language>This is specific this PR in general, consider Throwables.propagate() instead</technical_language>

Target:
public String toString(T pojo) { try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); ObjectWriter writer = mapper.writer(); return writer.writeValueAsString(pojo); } catch (IOException e) { throw Throwables.propagate(e); } }
Source:
<code>boolean removeBlobStore(BlobStore store) { boolean result; if (compactionExecutor == null) { stores.remove(store); result = true; <START> } else { <END> if (!compactionExecutor.getStoresDisabledCompaction().contains(store)) { logger.error("Fail to remove store ({}) from compaction manager because compaction of it is still enabled", store); result = false; } else { compactionExecutor.removeBlobStore(store); result = true; } } return result; }</code><technical_language>I remove this nested else else if (!compact..</technical_language>

Target:
boolean removeBlobStore(BlobStore store) { if (compactionExecutor == null) { stores.remove(store); return true; } else if (!compactionExecutor.getStoresDisabledCompaction().contains(store)) { logger.error("Fail to remove store ({}) from compaction manager because compaction is still enabled on it", store); return false; } compactionExecutor.removeBlobStore(store); return true; }
Source:
<code>public String complaint() { <START> return "Waaaas!? Wie kannst du nur... oh warte, diese Beatmap? Eigentlich ist die da weil ich sie hasse und ich dich testen wollte. Bist du nicht froh etwas mit mir gemeinsam zu haben?"; <END> }</code><technical_language>dich auf die Probe stellen wollte other German... > Freust du dich nicht etwas mit Flows a IMO</technical_language>

Target:
public String complaint() { return "Waaaas!? Wie kannst du nur... oh warte, diese Beatmap? Eigentlich ist die da weil ich sie hasse und ich dich auf die Probe stellen wollte. Freust du dich nicht etwas mit mir gemeinsam zu haben?"; }
Source:
<code>private void startHttpClient(HttpClient client) { if (httpClient == null) { httpClient = new HttpClient(); } <START> if (!client.isStarted()) { <END> try { httpClient.start(); } catch (Exception e1) { logger.warn("Can not start HttpClient", e1); } } }</code><technical_language>Do mix 'httpClient' client intention this way</technical_language>

Target:
private void startHttpClient(HttpClient client) { if (!client.isStarted()) { try { client.start(); } catch (Exception e1) { logger.warn("Can not start HttpClient !", e1); } } }
Source:
<code>private SMREntryList next(OpaqueStreamIterator stream) { List<SMREntry> list = new ArrayList<>(); int currentSize = 0; if (lastEntry != null) { <START> list.addAll(lastEntry); <END> currentSize += calculateSize(lastEntry); lastEntry = null; } try { while (stream.iterator.hasNext() && currentSize < maxDataSize) { OpaqueEntry entry = (OpaqueEntry) stream.iterator.next(); stream.maxVersion = Math.max(stream.maxVersion, entry.getVersion()); List<SMREntry> currentSMREntries = entry.getEntries().get(stream.uuid); int currentEntrySize = calculateSize(currentSMREntries); if (currentSize + currentEntrySize > maxDataSize) { lastEntry = currentSMREntries; break; } list.addAll(entry.getEntries().get(stream.uuid)); currentSize += currentEntrySize; } } catch (TrimmedException e) { log.error("Catch an TrimmedException exception ", e); throw e; } log.trace("CurrentSize lastEntrySize maxDataMsgSize {}", currentSize, lastEntry == null ? 0 : calculateSize(lastEntry), maxDataMsgSize); return new SMREntryList(currentSize, list); }</code><technical_language>rename list entries similar</technical_language>

Target:
private SMREntryList next(OpaqueStreamIterator stream) { List<SMREntry> smrList = new ArrayList<>(); int currentMsgSize = 0; try { while (currentMsgSize < maxDataSizePerMsg) { if (lastEntry != null) { List<SMREntry> smrEntries = lastEntry.getEntries().get(stream.uuid); if (smrEntries != null) { int currentEntrySize = calculateSize(smrEntries); if (currentEntrySize > DEFAULT_LOG_REPLICATION_DATA_MSG_SIZE) { log.error("The current entry size is bigger than the maxDataSizePerMsg supported", currentEntrySize, DEFAULT_LOG_REPLICATION_DATA_MSG_SIZE); } else if (currentEntrySize > maxDataSizePerMsg) { log.warn("The current entry size is bigger than the configured maxDataSizePerMsg {}", currentEntrySize, maxDataSizePerMsg); } if (currentEntrySize + currentMsgSize > maxDataSizePerMsg && currentMsgSize != 0) { break; } smrList.addAll(smrEntries); currentMsgSize += currentEntrySize; stream.maxVersion = Math.max(stream.maxVersion, lastEntry.getVersion()); } lastEntry = null; } if (stream.iterator.hasNext()) { lastEntry = (OpaqueEntry) stream.iterator.next(); } if (lastEntry == null) { break; } } } catch (TrimmedException e) { log.error("Catch an TrimmedException exception ", e); throw e; } log.info("CurrentMsgSize lastEntrySize maxDataSizePerMsg {}", currentMsgSize, lastEntry == null ? 0 : calculateSize(lastEntry.getEntries().get(stream.uuid)), maxDataSizePerMsg); return new SMREntryList(currentMsgSize, smrList); }
Source:
<code>public ListenableFuture<Boolean> setMetricsCacheLocation( TopologyMaster.MetricsCacheLocation location, String topologyName) { client.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework arg0, ConnectionState arg1) { if (arg1 == ConnectionState.RECONNECTED || arg1 == ConnectionState.CONNECTED) { LOG.info("zk session state changed to " + arg1); <START> createNode( <END> StateLocation.METRICSCACHE_LOCATION, topologyName, location.toByteArray(), true); } } }); return createNode( StateLocation.METRICSCACHE_LOCATION, topologyName, location.toByteArray(), true); }</code><technical_language>QQ: Do need delete node</technical_language>

Target:
public ListenableFuture<Boolean> setMetricsCacheLocation( TopologyMaster.MetricsCacheLocation location, String topologyName) { client.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework arg0, ConnectionState arg1) { if (arg1 != ConnectionState.CONNECTED) { throw new RuntimeException("Unexpected state change to: " + arg1.name()); } } }); return createNode( StateLocation.METRICSCACHE_LOCATION, topologyName, location.toByteArray(), true); }
Source:
<code>public void testValidateQuestionDetails_noValidationError_errorListShouldBeEmpty() { ______TS("Success case: No validation errors"); FeedbackMcqQuestionDetails mcqDetails = new FeedbackMcqQuestionDetails(); HashMap<String, String[]> requestParams = new HashMap<>(); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_TYPE, new String[] { "MCQ" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_TEXT, new String[] { "mcq question text" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_GENERATED_OPTIONS, new String[] { "NONE" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_NUMBEROFCHOICECREATED, new String[] { "2" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQCHOICE + "-0", new String[] { "Choice 1" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQCHOICE + "-1", new String[] { "Choice 2" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_WEIGHTS_ASSIGNED, new String[] { "on" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_WEIGHT + "-0", new String[] { "1.22" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_WEIGHT + "-1", new String[] { "1.55" }); assertTrue(mcqDetails.extractQuestionDetails(requestParams, FeedbackQuestionType.MCQ)); assertTrue(mcqDetails.hasAssignedWeights()); List<String> errors = mcqDetails.validateQuestionDetails(dummySessionToken); assertEquals(0, errors.size()); <START> } <END></code><technical_language>forget cover if conditions in validateQuestionDetails. coverage CI in IDE</technical_language>

Target:
public void testValidateQuestionDetails_noValidationError_errorListShouldBeEmpty() { FeedbackMcqQuestionDetails mcqDetails = new FeedbackMcqQuestionDetails(); HashMap<String, String[]> requestParams = new HashMap<>(); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_TYPE, new String[] { "MCQ" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_TEXT, new String[] { "mcq question text" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_GENERATED_OPTIONS, new String[] { "NONE" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_NUMBEROFCHOICECREATED, new String[] { "2" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQCHOICE + "-0", new String[] { "Choice 1" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQCHOICE + "-1", new String[] { "Choice 2" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_HAS_WEIGHTS_ASSIGNED, new String[] { "on" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_WEIGHT + "-0", new String[] { "1.22" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_WEIGHT + "-1", new String[] { "1.55" }); assertTrue(mcqDetails.extractQuestionDetails(requestParams, FeedbackQuestionType.MCQ)); assertTrue(mcqDetails.hasAssignedWeights()); List<String> errors = mcqDetails.validateQuestionDetails(dummySessionToken); assertEquals(0, errors.size()); }
Source:
<code>public StudentAttributes regenerateStudentRegistrationKey(String courseId, String email) throws EntityDoesNotExistException, RegenerateStudentException { try { StudentAttributes originalStudent = studentsDb.getStudentForEmail(courseId, email); if (originalStudent == null) { throw new EntityDoesNotExistException("Student does not exist: [" + courseId + "/" + email + "]"); } studentsDb.deleteStudent(courseId, email); StudentAttributes updatedStudent = studentsDb.createEntity(originalStudent); if (updatedStudent.getKey().equals(originalStudent.getKey())) { <START> throw new RegenerateStudentException("Regenerated student has same registration key as original student."); <END> } return updatedStudent; } catch (InvalidParametersException | EntityAlreadyExistsException e) { Assumption.fail("Regenerating registration key shall not cause: " + e.getMessage()); } return null; }</code><technical_language>this block, new student entity persisted DB. Is safe? - If I understand correctly, this chance if key (which is supposedly RNG-generated) is identical. If is case, retries</technical_language>

Target:
public StudentAttributes regenerateStudentRegistrationKey(String courseId, String email) throws EntityDoesNotExistException, RegenerateStudentException { StudentAttributes originalStudent = studentsDb.getStudentForEmail(courseId, email); if (originalStudent == null) { throw new EntityDoesNotExistException("Student does not exist: [" + courseId + "/" + email + "]"); } return studentsDb.regenerateEntityKey(originalStudent); }
Source:
<code>private boolean isValidNotificationSignature(String payload, String signatureHeader) { boolean isValid = false; for (String webhookSigningSecret : stripeGatewayConfig.getWebhookSigningSecrets()) { if (isValidNotificationSignature(payload, signatureHeader, webhookSigningSecret)) { isValid = true; <START> break; <END> } } if (isValid) { return true; } else { logger.warn("Could not verify Stripe authentication header"); return false; } }</code><technical_language>this var isValid = stripeGatewayConfig.getWebhookSigningSecrets() .stream() .anyMatch(s -> isValidNotificationSignature(payload, signatureHeader, s));</technical_language>

Target:
private boolean isValidNotificationSignature(String payload, String signatureHeader) { boolean isValid = stripeGatewayConfig.getWebhookSigningSecrets() .stream() .anyMatch(s -> isValidNotificationSignature(payload, signatureHeader, s)); if (isValid) { return true; } else { logger.warn("Could not verify Stripe authentication header"); return false; } }
Source:
<code>private Future<ProcessResult> startProcessor(final TaskSource taskSource, final Schema schema, final int index) { return executor.submit(new Callable<ProcessResult>() { public ProcessResult call() { runningThreadCount.getAndIncrement(); final ExecutorTask task = taskSource.loadTask(ExecutorTask.class); final InputPlugin in = newInputPlugin(task); final OutputPlugin out = newOutputPlugin(task); TransactionalPageOutput tran = out.open(task.getOutputTask(), schema, index); boolean committed = false; try { CommitReport inReport = in.run(task.getInputTask(), schema, index, tran); CommitReport outReport = tran.commit(); committed = true; return new ProcessResult(inReport, outReport); } finally { if (!committed) { tran.abort(); } tran.close(); <START> runningThreadCount.getAndDecrement(); <END> } } }); }</code><technical_language>out.open tran.abort thorw exceptions. Call getAndIncrement() right try { && getAndDecrement() right finally {, another try-finally block</technical_language>

Target:
private Future<ProcessResult> startProcessor(final TaskSource taskSource, final Schema schema, final int index) { return executor.submit(new Callable<ProcessResult>() { public ProcessResult call() { try { runningTaskCount.getAndIncrement(); final ExecutorTask task = taskSource.loadTask(ExecutorTask.class); final InputPlugin in = newInputPlugin(task); final OutputPlugin out = newOutputPlugin(task); TransactionalPageOutput tran = out.open(task.getOutputTask(), schema, index); boolean committed = false; try { CommitReport inReport = in.run(task.getInputTask(), schema, index, tran); CommitReport outReport = tran.commit(); committed = true; return new ProcessResult(inReport, outReport); } finally { if (!committed) { tran.abort(); } tran.close(); } } finally { runningTaskCount.getAndDecrement(); completedTaskCount.getAndIncrement(); } } }); }
Source:
<code>public Response updateFields(@PathParam("typeId") final String typeId, final String fieldsJson, @Context final HttpServletRequest req) throws DotDataException, DotSecurityException { final InitDataObject initData = this.webResource.init(null, false, req, false, null); final User user = initData.getUser(); Response response = null; try { final List<Field> fields = new JsonFieldTransformer(fieldsJson).asList(); for (Field field : fields) { fieldAPI.save(field, user); } final List<Field> contentTypeFields = fieldAPI.byContentTypeId(typeId); response = Response.ok(new ResponseEntityView(new JsonFieldTransformer(contentTypeFields).mapList())).build(); <START> } catch (DotStateException e) { <END> response = ExceptionMapperUtil.createResponse(null, "Field is not valid ("+ e.getMessage() +")"); } catch (NotFoundInDbException e) { response = ExceptionMapperUtil.createResponse(e, Response.Status.NOT_FOUND); } catch (Exception e) { response = ExceptionMapperUtil.createResponse(e, Response.Status.INTERNAL_SERVER_ERROR); } return response; }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') log rethrow this exception. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public Response updateFields(@PathParam("typeId") final String typeId, final String fieldsJson, @Context final HttpServletRequest req) throws DotDataException, DotSecurityException { final InitDataObject initData = this.webResource.init(null, false, req, false, null); final User user = initData.getUser(); Response response = null; try { final List<Field> fields = new JsonFieldTransformer(fieldsJson).asList(); for (final Field field : fields) { fieldAPI.save(field, user); } final List<Field> contentTypeFields = fieldAPI.byContentTypeId(typeId); response = Response.ok(new ResponseEntityView(new JsonFieldTransformer(contentTypeFields).mapList())).build(); } catch (DotStateException e) { response = ExceptionMapperUtil.createResponse(null, "Field is not valid ("+ e.getMessage() +")"); } catch (NotFoundInDbException e) { response = ExceptionMapperUtil.createResponse(e, Response.Status.NOT_FOUND); } catch (Exception e) { response = ExceptionMapperUtil.createResponse(e, Response.Status.INTERNAL_SERVER_ERROR); } return response; }
Source:
<code>private Object[] arraysOfDepth( int n ) { <START> return n == 0 ? new Object[]{"hej"} : arraysOfDepth( n-1 ); <END> }</code><technical_language>This wrap nest arrays. returns array recursion base case</technical_language>

Target:
private Object[] arraysOfDepth( int n ) { return n == 0 ? new Object[]{"hej"} : new Object[]{arraysOfDepth( n-1 )}; }
Source:
<code>private static boolean isWindows() { <START> return System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("win"); <END> }</code><technical_language>matches: "Darwin", I some OpenJDK builds identify OS X as</technical_language>

Target:
private static boolean isWindows() { return System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("windows"); }
Source:
<code>public void testUpdateCacheForNeverUpdatedTable() throws Exception { String tableName = generateUniqueName(); String fullTableName = INDEX_DATA_SCHEMA + QueryConstants.NAME_SEPARATOR + tableName; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); AtomicBoolean isSysMutexEmpty = new AtomicBoolean(true); ExecutorService executorService = Executors.newFixedThreadPool(5, new ThreadFactoryBuilder().setDaemon(true) .setNameFormat("check-sys-mutex-count-%d").build()); Connection connForMutex = DriverManager.getConnection(getUrl(), props); <START> for (int i = 0; i < 5; i++) { <END> executorService.submit(new SystemMutexCaller(isSysMutexEmpty, connForMutex)); } Thread.sleep(500); try (Connection conn = DriverManager.getConnection(getUrl(), props)) { conn.createStatement().execute("create table " + fullTableName + TestUtil.TEST_TABLE_SCHEMA); conn.createStatement().execute("ALTER TABLE " + fullTableName + " SET UPDATE_CACHE_FREQUENCY=NEVER"); } assertTrue("Mutex should not have been acquired", isSysMutexEmpty.get()); try { executorService.shutdown(); connForMutex.close(); executorService.awaitTermination(5, TimeUnit.SECONDS); } catch (Exception ignored) { } helpTestUpdateCache(fullTableName, new int[] {0, 0}, false); }</code><technical_language>a good idea phoenix connection multiple threads is thread-safe</technical_language>

Target:
public void testUpdateCacheForNeverUpdatedTable() throws Exception { String tableName = generateUniqueName(); String fullTableName = INDEX_DATA_SCHEMA + QueryConstants.NAME_SEPARATOR + tableName; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); AtomicBoolean isSysMutexEmpty = new AtomicBoolean(true); ExecutorService executorService = Executors.newFixedThreadPool(5, new ThreadFactoryBuilder().setDaemon(true) .setNameFormat("check-sys-mutex-count-%d").build()); for (int i = 0; i < 5; i++) { executorService.submit(new SystemMutexCaller(isSysMutexEmpty, props, INDEX_DATA_SCHEMA, tableName)); } Thread.sleep(500); try (Connection conn = DriverManager.getConnection(getUrl(), props)) { conn.createStatement().execute("create table " + fullTableName + TestUtil.TEST_TABLE_SCHEMA); conn.createStatement().execute("ALTER TABLE " + fullTableName + " SET UPDATE_CACHE_FREQUENCY=NEVER"); } assertTrue("Mutex should not have been acquired", isSysMutexEmpty.get()); try { executorService.shutdown(); executorService.awaitTermination(5, TimeUnit.SECONDS); } catch (Exception e) { LOGGER.debug("Error during ExecutorService shutdown"); } helpTestUpdateCache(fullTableName, new int[] {0, 0}, false); }
Source:
<code><START> public static Map<SchemaTableName, ElasticsearchTableDescription> createElasticsearchTableDescriptions(File tableDescriptionDir, String defaultSchema, Set<String> tableNames, JsonCodec<ElasticsearchTableDescription> tableDescriptionCodec) <END> { ImmutableMap.Builder<SchemaTableName, ElasticsearchTableDescription> builder = ImmutableMap.builder(); log.debug("Loading elasticsearch table definitions from %s", tableDescriptionDir.getAbsolutePath()); try { for (File file : listFiles(tableDescriptionDir)) { if (file.isFile() && file.getName().endsWith(".json")) { ElasticsearchTableDescription table = tableDescriptionCodec.fromJson(readAllBytes(file.toPath())); String schemaName = firstNonNull(table.getSchemaName(), defaultSchema); log.debug("Elasticsearch table %s.%s: %s", schemaName, table.getTableName(), table); builder.put(new SchemaTableName(schemaName, table.getTableName()), table); } } Map<SchemaTableName, ElasticsearchTableDescription> tableDefinitions = builder.build(); log.debug("Loaded Table definitions: %s", tableDefinitions.keySet()); builder = ImmutableMap.builder(); for (String definedTable : tableNames) { SchemaTableName tableName; tableName = parseTableName(definedTable); if (!tableDefinitions.containsKey(tableName)) { throw new IOException("Missing table definition for: " + tableName); } ElasticsearchTableDescription elasticsearchTable = tableDefinitions.get(tableName); builder.put(tableName, elasticsearchTable); } return builder.build(); } catch (IOException e) { log.warn(e, "Error: "); throw new UncheckedIOException(e); } }</code><technical_language>put parameter a separate line, currently this is long</technical_language>

Target:
public static Map<SchemaTableName, ElasticsearchTableDescription> createElasticsearchTableDescriptions( File tableDescriptionDir, String defaultSchema, Set<String> tableNames, JsonCodec<ElasticsearchTableDescription> tableDescriptionCodec) { ImmutableMap.Builder<SchemaTableName, ElasticsearchTableDescription> builder = ImmutableMap.builder(); try { for (File file : listFiles(tableDescriptionDir)) { if (file.isFile() && file.getName().endsWith(".json")) { ElasticsearchTableDescription table = tableDescriptionCodec.fromJson(readAllBytes(file.toPath())); String schemaName = firstNonNull(table.getSchemaName(), defaultSchema); builder.put(new SchemaTableName(schemaName, table.getTableName()), table); } } Map<SchemaTableName, ElasticsearchTableDescription> tableDefinitions = builder.build(); builder = ImmutableMap.builder(); for (String definedTable : tableNames) { SchemaTableName tableName = parseTableName(definedTable); if (!tableDefinitions.containsKey(tableName)) { throw new PrestoException(ELASTIC_SEARCH_TABLE_DEFINITION_ERROR, "Missing table definition for: " + tableName); } ElasticsearchTableDescription elasticsearchTable = tableDefinitions.get(tableName); builder.put(tableName, elasticsearchTable); } return builder.build(); } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
<code>public void startupShouldNotFailOnRuntimeExceptionOnlineListener() { <START> Assert.assertEquals(1, RuntimeExceptionOnOnlineListener.onOnlineCount); <END> }</code><technical_language>suggestion assertEquals(1, RuntimeExceptionOnOnlineListener.onOnlineCount);</technical_language>

Target:
public void startupShouldNotFailOnRuntimeExceptionOnlineListener() { assertEquals(1, RuntimeExceptionOnOnlineListener.onOnlineCount); }
Source:
<code>public static FluidStack loadFluidStackFromNBT(NBTTagCompound nbt) { if (nbt == null) { return null; } FluidStack stack; if (nbt.hasKey("Fluid", Constants.NBT.TAG_STRING)) { ResourceLocation fluid = new ResourceLocation(nbt.getString("Fluid")); if (!ForgeRegistries.FLUIDS.containsKey(fluid)) { return null; } else { stack = new FluidStack(ForgeRegistries.FLUIDS.getValue(fluid), nbt.getInteger("Amount")); } } else if (nbt.hasKey("FluidName", Constants.NBT.TAG_STRING)) { String fluidName = nbt.getString("FluidName").toLowerCase(); <START> Fluid fluid = null; <END> for (Fluid f : ForgeRegistries.FLUIDS.getValues()) { if (f.getRegistryName().getResourcePath().equals(fluidName)); { fluid = f; continue; } } if (fluid == null) { return null; } else { stack = new FluidStack(fluid, nbt.getInteger("Amount")); } } else { return null; } if (nbt.hasKey("Tag")) { stack.tag = nbt.getCompoundTag("Tag"); } return stack; }</code><technical_language>missed</technical_language>

Target:
public static FluidStack loadFluidStackFromNBT(NBTTagCompound nbt) { if (nbt == null) { return null; } FluidStack stack; if (nbt.hasKey("Fluid", Constants.NBT.TAG_STRING)) { ResourceLocation fluid = new ResourceLocation(nbt.getString("Fluid")); if (!ForgeRegistries.FLUIDS.containsKey(fluid)) { return null; } else { stack = new FluidStack(ForgeRegistries.FLUIDS.getValue(fluid), nbt.getInteger("Amount")); } } else if (nbt.hasKey("FluidName", Constants.NBT.TAG_STRING)) { String fluidName = nbt.getString("FluidName").toLowerCase(Locale.ENGLISH); Fluid fluid = null; for (Fluid f : ForgeRegistries.FLUIDS.getValues()) { if (f.getRegistryName().getResourcePath().equals(fluidName)); { fluid = f; continue; } } if (fluid == null) { return null; } else { stack = new FluidStack(fluid, nbt.getInteger("Amount")); } } else { return null; } if (nbt.hasKey("Tag")) { stack.tag = nbt.getCompoundTag("Tag"); } return stack; }
Source:
<code>public List<? extends Module> getJacksonModules() { return ImmutableList.<Module>of( new SimpleModule("IndexingServiceFirehoseModule") .registerSubtypes( new NamedType(EventReceiverFirehoseFactory.class, "receiver"), <START> new NamedType(DruidFirehoseFactory.class, "druid") <END> ) ); }</code><technical_language>ingest segment firehose</technical_language>

Target:
public List<? extends Module> getJacksonModules() { return ImmutableList.<Module>of( new SimpleModule("IndexingServiceFirehoseModule") .registerSubtypes( new NamedType(EventReceiverFirehoseFactory.class, "receiver"), new NamedType(IngestSegmentFirehoseFactory.class, "ingestSegment") ) ); }
Source:
<code>public static DockerClientConfigBuilder populateConfigBuilder(DockerClientConfigBuilder builder) { builder.withVersion(""); builder.withDockerCertPath(""); dockerHostEnv = System.getenv("DOCKER_HOST"); dockerCertPathEnv = System.getenv("DOCKER_CERT_PATH"); dockerHostPrp = properties.getProperty("docker.io.url"); dockerCertPathPrp = properties.getProperty("docker.io.dockerCertPath"); dockerUri = "unix:/ if (dockerHostEnv != null) { dockerUri = dockerHostEnv; } else if (dockerHostPrp != null) { dockerUri = dockerHostPrp; builder.withProperties(properties); } if (dockerCertPathPrp != null && new File(dockerCertPathPrp).exists()) { dockerCertPath = dockerCertPathPrp; } if (dockerCertPathEnv != null && new File(dockerCertPathEnv).exists()) { dockerCertPath = dockerCertPathEnv; } <START> builder.withUri(dockerUri.replace("tcp", "https")); <END> if (dockerCertPath != null) { builder.withDockerCertPath(dockerCertPath); } return builder; }</code><technical_language>in case of setting Docker host properties precedence while in case of cert path environment variable takes precedence</technical_language>

Target:
public static DockerClientConfigBuilder populateConfigBuilder(DockerClientConfigBuilder builder) { builder.withVersion(""); builder.withDockerCertPath(""); dockerHostEnv = environment.get("DOCKER_HOST"); dockerCertPathEnv = environment.get("DOCKER_CERT_PATH"); dockerHostPrp = properties.getProperty("docker.io.url"); dockerCertPathPrp = properties.getProperty("docker.io.dockerCertPath"); dockerUri = "unix:/ if (dockerHostEnv != null) { dockerUri = dockerHostEnv; } else if (dockerHostPrp != null) { dockerUri = dockerHostPrp; builder.withProperties(properties); } if (dockerCertPathPrp != null && new File(dockerCertPathPrp).exists()) { dockerCertPath = dockerCertPathPrp; } if (dockerCertPathEnv != null && new File(dockerCertPathEnv).exists()) { dockerCertPath = dockerCertPathEnv; } builder.withUri(dockerUri.replace("tcp", "https")); if (dockerCertPath != null) { builder.withDockerCertPath(dockerCertPath); } return builder; }
Source:
<code>public void applyTo(GradleConnector connector) { connector.forProjectDirectory(this.rootDir); connector.useGradleUserHomeDir(this.gradleUserHome); <START> if (this.gradleDistribution instanceof LocalGradleDistribution) { <END> connector.useInstallation(((LocalGradleDistribution)this.gradleDistribution).getLocation()); } else if (this.gradleDistribution instanceof RemoteGradleDistribution) { connector.useDistribution(((RemoteGradleDistribution)this.gradleDistribution).getUrl()); } else if (this.gradleDistribution instanceof FixedVersionGradleDistribution) { connector.useGradleVersion(((FixedVersionGradleDistribution)this.gradleDistribution).getVersion()); } else if (this.gradleDistribution instanceof WrapperGradleDistribution) { connector.useBuildDistribution(); } else { throw new GradlePluginsRuntimeException("Invalid distribution type: " + this.gradleDistribution); } }</code><technical_language>GradleDistribution applyTo(Connector)</technical_language>

Target:
public void applyTo(GradleConnector connector) { connector.forProjectDirectory(this.rootDir); connector.useGradleUserHomeDir(this.gradleUserHome); this.gradleDistribution.apply(connector); }
Source:
<code>public static void getLatency(Long latency){ Long innerLatency; if (latency != (long) minimum) { innerLatency = latency; } else { innerLatency = getDelayFromXml(); } try { <START> Thread.sleep(innerLatency); <END> } catch (InterruptedException e) { e.printStackTrace(); } }</code><technical_language>Please consider using: TimeUnit.MILLISECONDS.sleep(innerLatency); is clear is unit of time want wait</technical_language>

Target:
public static void getLatency(Long latency) { Long innerLatency; if (latency != (long) minimum) { innerLatency = latency; } else { innerLatency = getDelayFromXml(); } try { TimeUnit.MILLISECONDS.sleep(innerLatency); }catch (Exception e){ log.error("faild to to run getLatency error is:{}", e); } }
Source:
<code>protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { Boolean accessAllowed = super.isAccessAllowed(request, response, mappedValue) || !this.isLoginRequest(request, response) && this <START> .isPermissive(mappedValue); <END> if (accessAllowed) { accessAllowed = false; for (Cookie cookie : ((ShiroHttpServletRequest) request).getCookies()) { if (cookie.getName().equals("hadoop-jwt")) { accessAllowed = true; break; } } } return accessAllowed; }</code><technical_language>realign this line - merge previous</technical_language>

Target:
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { Boolean accessAllowed = super.isAccessAllowed(request, response, mappedValue) || !isLoginRequest(request, response) && isPermissive(mappedValue); if (accessAllowed) { accessAllowed = false; KnoxJwtRealm knoxJwtRealm = null; for (Object realm : SecurityUtils.getRealmsList()) { if (realm instanceof KnoxJwtRealm) { knoxJwtRealm = (KnoxJwtRealm) realm; break; } } if (knoxJwtRealm != null) { for (Cookie cookie : ((ShiroHttpServletRequest) request).getCookies()) { if (cookie.getName().equals(knoxJwtRealm.getCookieName())) { if (knoxJwtRealm.validateToken(cookie.getValue())) { accessAllowed = true; } break; } } } else { LOGGER.error("Looks like this filter is enabled without enabling KnoxJwtRealm, please refer" + " to <LINK_0>" + "#knox-sso"); } } return accessAllowed; }
Source:
<code>private <T> T deserializeManagementResponse(Message message, Class<T> deserializedType) { if (!(message.getBody() instanceof AmqpValue)) { throw logger.logExceptionAsError(new IllegalArgumentException( "Expected message.getBody() to be AmqpValue, but is: " + message.getBody())); } final AmqpValue body = (AmqpValue) message.getBody(); if (!(body.getValue() instanceof Map)) { throw logger.logExceptionAsError(new IllegalArgumentException( "Expected message.getBody().getValue() to be of type Map")); } final Map<?, ?> amqpBody = (Map<?, ?>) body.getValue(); if (deserializedType == PartitionProperties.class) { return (T) toPartitionProperties(amqpBody); } else if (deserializedType == EventHubProperties.class) { return (T) toEventHubProperties(amqpBody); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( <START> "Class '%s' is not a supported deserializable type.", deserializedType))); <END> } }</code><technical_language>this part of messages.properties</technical_language>

Target:
private <T> T deserializeManagementResponse(Message message, Class<T> deserializedType) { if (!(message.getBody() instanceof AmqpValue)) { throw logger.logExceptionAsError(new IllegalArgumentException( "Expected message.getBody() to be AmqpValue, but is: " + message.getBody())); } final AmqpValue body = (AmqpValue) message.getBody(); if (!(body.getValue() instanceof Map)) { throw logger.logExceptionAsError(new IllegalArgumentException( "Expected message.getBody().getValue() to be of type Map")); } final Map<?, ?> amqpBody = (Map<?, ?>) body.getValue(); if (deserializedType == PartitionProperties.class) { return (T) toPartitionProperties(amqpBody); } else if (deserializedType == EventHubProperties.class) { return (T) toEventHubProperties(amqpBody); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( Messages.CLASS_NOT_A_SUPPORTED_TYPE, deserializedType))); } }
Source:
<code>public static boolean beginCount(URL url, String methodName, int max) { RpcStatus appStatus = getStatus(url); RpcStatus methodStatus = getStatus(url, methodName); <START> if (max > 0 && methodStatus.active.incrementAndGet() > max) { <END> methodStatus.active.decrementAndGet(); return false; } else { appStatus.active.incrementAndGet(); return true; } }</code><technical_language>If add max>0 in condition issue in finally block reducing endCount irrespective of max value. e.g. 1)max is 0 in RpcStatus.java's count increment counter in ActiveLimitFilter's invoke's finally block reducing final for single invocation landed -1 active count. I including max>0 adding java } finally { if (max > 0) { RpcStatus.endCount(url, methodName, System.currentTimeMillis() - begin, isSuccess); synchronized (count) { count.notifyAll(); } } } In ActiveLimitFilter work, I beleive rewrite this more clear suggest. I another issue (not of changes), in a scenario if max>0 (in RpcStatus.java) get satisfied (or lets max>0 condition is present in code earlier version) methodStatus.active.incrementAndGet() > max return false code of else block executing increment count. for call eventually incrementing counter twice. Do feel this a another problem in future?Correct if understanding correct</technical_language>

Target:
public static boolean beginCount(URL url, String methodName, int max) { max = (max <= 0) ? Integer.MAX_VALUE : max; RpcStatus appStatus = getStatus(url); RpcStatus methodStatus = getStatus(url, methodName); if (methodStatus.active.incrementAndGet() > max) { methodStatus.active.decrementAndGet(); return false; } else { appStatus.active.incrementAndGet(); return true; } }
Source:
<code>public final static byte[] decrypt(byte[] key, byte[] nonce, byte[] a, byte[] c, int numAuthenticationBytes) throws GeneralSecurityException { Cipher cipher = threadLocalCipher.get(); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, KEY_TYPE)); int lengthM = c.length - numAuthenticationBytes; <START> int blockSize = cipher.getBlockSize(); <END> byte[] decrypted = new byte[lengthM]; byte[] T = new byte[numAuthenticationBytes]; BlockCipher blockCiper = new BlockCipher(cipher, nonce); int blockNo = 0; byte[] block = blockCiper.updateBlock(blockNo++); for (int i = 0; i < numAuthenticationBytes; ++i) { T[i] = (byte) (c[lengthM + i] ^ block[i]); } for (int i = 0; i < lengthM;) { block = blockCiper.updateBlock(blockNo++); int blockEnd = i + blockSize; if (blockEnd > lengthM) { blockEnd = lengthM; } for (int j = 0; i < blockEnd; ++i, ++j) { decrypted[i] = (byte) (c[i] ^ block[j]); } } MacCipher macCipher = new MacCipher(cipher, nonce, a, decrypted, numAuthenticationBytes); byte[] mac = macCipher.getMac(); if (Arrays.equals(T, mac)) { return decrypted; } else { throw new InvalidMacException(mac, T); } }</code><technical_language>if Cipher.getInstance(CIPHER_NAME) failed next line raise NPE. handle this in a</technical_language>

Target:
public final static byte[] decrypt(byte[] key, byte[] nonce, byte[] a, byte[] c, int numAuthenticationBytes) throws GeneralSecurityException { Cipher cipher = CipherManager.getInstance(CIPHER_NAME); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, KEY_TYPE)); int lengthM = c.length - numAuthenticationBytes; int blockSize = cipher.getBlockSize(); byte[] decrypted = new byte[lengthM]; byte[] T = new byte[numAuthenticationBytes]; BlockCipher blockCiper = new BlockCipher(cipher, nonce); int blockNo = 0; byte[] block = blockCiper.updateBlock(blockNo++); for (int i = 0; i < numAuthenticationBytes; ++i) { T[i] = (byte) (c[lengthM + i] ^ block[i]); } for (int i = 0; i < lengthM;) { block = blockCiper.updateBlock(blockNo++); int blockEnd = i + blockSize; if (blockEnd > lengthM) { blockEnd = lengthM; } for (int j = 0; i < blockEnd; ++i, ++j) { decrypted[i] = (byte) (c[i] ^ block[j]); } } MacCipher macCipher = new MacCipher(cipher, nonce, a, decrypted, numAuthenticationBytes); byte[] mac = macCipher.getMac(); if (Arrays.equals(T, mac)) { return decrypted; } else { throw new InvalidMacException(mac, T); } }