auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private HTMLPageUrl getHtmlPageAsset(final PageContext context, final Host host, final HttpServletRequest request) throws DotDataException, DotSecurityException { HTMLPageUrl htmlPageUrl = null; for (final SearchPageFunction pageSearcher : pageSearchers) { final Optional<HTMLPageUrl> optional = pageSearcher.search(context, host, request); if (optional.isPresent()) { htmlPageUrl = optional.get(); break; } } if(htmlPageUrl == null ){ throw new HTMLPageAssetNotFoundException(context.getPageUri()); } checkPagePermission(context, htmlPageUrl.htmlPage); return htmlPageUrl; }

Target:
private HTMLPageUrl getHtmlPageAsset(final PageContext context, final Host host, final HttpServletRequest request) throws DotDataException, DotSecurityException { Optional<HTMLPageUrl> htmlPageUrlOptional = findPageByContext(host, context); if (!htmlPageUrlOptional.isPresent()) { htmlPageUrlOptional = findByURLMap(context, host, request); } if(!htmlPageUrlOptional.isPresent()){ throw new HTMLPageAssetNotFoundException(context.getPageUri()); } final HTMLPageUrl htmlPageUrl = htmlPageUrlOptional.get(); checkPagePermission(context, htmlPageUrl.htmlPage); return htmlPageUrl; }
Source:
protected FreeIpaDownscaleContext createFlowContext(FlowParameters flowParameters, StateContext<DownscaleState, DownscaleFlowEvent> stateContext, P payload) { Stack stack = stackService.getByIdWithListsInTransaction(payload.getResourceId()); MDCBuilder.buildMdcContext(stack); Location location = location(region(stack.getRegion())); CloudContext cloudContext = new CloudContext(stack.getId(), stack.getName(), stack.getCloudPlatform(), stack.getCloudPlatform(), location, stack.getOwner(), stack.getOwner(), stack.getAccountId()); CloudCredential cloudCredential = credentialConverter.convert(credentialService.getCredentialByEnvCrn(stack.getEnvironmentCrn())); CloudStack cloudStack = cloudStackConverter.convert(stack); Map<Object, Object> variables = stateContext.getExtendedState().getVariables(); List<String> instanceIds = extractInstanceIds(payload, variables); String operationId = extractOperationId(payload, variables); FreeIpa freeIpa = freeIpaService.findByStackId(stack.getId()); List<String> hosts = getHosts(stack, instanceIds, variables); return new FreeIpaDownscaleContext(flowParameters, stack, cloudContext, cloudCredential, cloudStack, instanceIds, freeIpa, operationId, hosts); }

Target:
protected StackContext createFlowContext(FlowParameters flowParameters, StateContext<DownscaleState, DownscaleFlowEvent> stateContext, P payload) { Stack stack = stackService.getByIdWithListsInTransaction(payload.getResourceId()); MDCBuilder.buildMdcContext(stack); Location location = location(region(stack.getRegion())); CloudContext cloudContext = new CloudContext(stack.getId(), stack.getName(), stack.getCloudPlatform(), stack.getCloudPlatform(), location, stack.getOwner(), stack.getOwner(), stack.getAccountId()); CloudCredential cloudCredential = credentialConverter.convert(credentialService.getCredentialByEnvCrn(stack.getEnvironmentCrn())); CloudStack cloudStack = cloudStackConverter.convert(stack); return new StackContext(flowParameters, stack, cloudContext, cloudCredential, cloudStack); }
Source:
public void testCopyScriptsInTargetDirectory() throws IOException { File f = new File(this.folder.newFolder(), "toto.properties"); Utils.writeStringInto( "id: tid\nprop: value\nhandler: h", f ); TestApplicationTemplate appT = new TestApplicationTemplate(); Utils.writeStringInto( "#!/bin/bash\necho Bonjour le monde cruel > toto.txt", new File( f.getParentFile(), "toto.sh" )); Utils.writeStringInto( "#!/bin/bash\necho touch toto.txt", new File( f.getParentFile(), "titi-script.py" )); File targetDir = new File( this.configurationMngr.getWorkingDirectory(), ConfigurationUtils.TARGETS + "/tid" ); Assert.assertFalse( targetDir.exists()); String targetId = this.mngr.createTarget( f, appT ); Assert.assertEquals( "tid", targetId ); Assert.assertTrue( targetDir.exists()); Assert.assertEquals( 4, targetDir.list().length); File toto = new File( targetDir, "toto.sh"); File titi = new File( targetDir, "titi-script.py"); Assert.assertTrue(toto.exists()); Assert.assertTrue(titi.exists()); }

Target:
public void testCopyScriptsInTargetDirectory() throws IOException { File f = new File(this.folder.newFolder(), "toto.properties"); Utils.writeStringInto( "id: tid\nprop: value\nhandler: h", f ); TestApplicationTemplate appT = new TestApplicationTemplate(); Utils.writeStringInto( "#!/bin/bash\necho Bonjour le monde cruel > toto.txt", new File( f.getParentFile(), "toto.sh" )); Utils.writeStringInto( "#!/bin/bash\ntouch titi.txt", new File( f.getParentFile(), "titi.sh" )); Utils.writeStringInto( "#!/bin/bash\necho tototo", new File( f.getParentFile(), "toto-script.sh" )); File targetDir = new File( this.configurationMngr.getWorkingDirectory(), ConfigurationUtils.TARGETS + "/tid" ); Assert.assertFalse( targetDir.exists()); String targetId = this.mngr.createTarget( f, appT ); Assert.assertEquals( "tid", targetId ); Assert.assertTrue( targetDir.exists()); Assert.assertEquals( 4, targetDir.list().length); File toto = new File( targetDir, "toto.sh"); File titi = new File( targetDir, "titi.sh"); File totoMain = new File( targetDir, "toto-script.sh"); Assert.assertTrue(toto.exists()); Assert.assertFalse(titi.exists()); Assert.assertTrue(totoMain.exists()); }
Source:
static BearerTokenCredential parseBearerTokenType(ConfigurationXMLStreamReader reader) throws ConfigXMLParseException { final int attributeCount = reader.getAttributeCount(); String value = null; for (int i = 0; i < attributeCount; i ++) { checkAttributeNamespace(reader, i); switch (reader.getAttributeLocalName(i)) { case "value": { if (value != null) throw reader.unexpectedAttribute(i); value = reader.getAttributeValue(i); break; } default: } } if (value == null) { throw missingAttribute(reader, "value"); } while (reader.hasNext()) { final int tag = reader.nextTag(); if (tag == START_ELEMENT) { throw reader.unexpectedElement(); } else if (tag == END_ELEMENT) { return new BearerTokenCredential(value); } else { throw reader.unexpectedContent(); } } throw reader.unexpectedDocumentEnd(); }

Target:
static BearerTokenCredential parseBearerTokenType(ConfigurationXMLStreamReader reader) throws ConfigXMLParseException { String value = requireSingleAttribute(reader, "value"); while (reader.hasNext()) { final int tag = reader.nextTag(); if (tag == START_ELEMENT) { throw reader.unexpectedElement(); } else if (tag == END_ELEMENT) { return new BearerTokenCredential(value); } else { throw reader.unexpectedContent(); } } throw reader.unexpectedDocumentEnd(); }
Source:
public SubscriptionInfo(final int version, final int latestSupportedVersion, final UUID processId, final Set<TaskId> prevTasks, final Set<TaskId> standbyTasks, final String userEndPoint) { validateVersions(version, latestSupportedVersion); final SubscriptionInfoData data = new SubscriptionInfoData(); data.setVersion(version); if (version >= 3) { data.setLatestSupportedVersion(latestSupportedVersion); } data.setProcessId(processId); data.setPrevTasks(prevTasks.stream().map(t -> { final SubscriptionInfoData.TaskId taskId = new SubscriptionInfoData.TaskId(); taskId.setTopicGroupId(t.topicGroupId); taskId.setPartition(t.partition); return taskId; }).collect(Collectors.toList())); data.setStandbyTasks(standbyTasks.stream().map(t -> { final SubscriptionInfoData.TaskId taskId = new SubscriptionInfoData.TaskId(); taskId.setTopicGroupId(t.topicGroupId); taskId.setPartition(t.partition); return taskId; }).collect(Collectors.toList())); if (version >= 2) { data.setUserEndPoint(userEndPoint == null ? new byte[0] : userEndPoint.getBytes(StandardCharsets.UTF_8)); } this.data = data; }

Target:
public SubscriptionInfo(final int version, final int latestSupportedVersion, final UUID processId, final Set<TaskId> prevTasks, final Set<TaskId> standbyTasks, final String userEndPoint) { validateVersions(version, latestSupportedVersion); final SubscriptionInfoData data = new SubscriptionInfoData(); data.setVersion(version); if (version >= 2) { data.setUserEndPoint(userEndPoint == null ? new byte[0] : userEndPoint.getBytes(StandardCharsets.UTF_8)); } if (version >= 3) { data.setLatestSupportedVersion(latestSupportedVersion); } data.setProcessId(processId); data.setPrevTasks(prevTasks.stream().map(t -> { final SubscriptionInfoData.TaskId taskId = new SubscriptionInfoData.TaskId(); taskId.setTopicGroupId(t.topicGroupId); taskId.setPartition(t.partition); return taskId; }).collect(Collectors.toList())); data.setStandbyTasks(standbyTasks.stream().map(t -> { final SubscriptionInfoData.TaskId taskId = new SubscriptionInfoData.TaskId(); taskId.setTopicGroupId(t.topicGroupId); taskId.setPartition(t.partition); return taskId; }).collect(Collectors.toList())); this.data = data; }
Source:
void populate(final int row, final PluginInfo plugin) { CheckBox checkBox = new CheckBox(); table.setWidget(row, 1, checkBox); table.setText(row, 2, plugin.name()); table.setText(row, 3, plugin.version()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().iconCell()); fmt.addStyleName(row, 2, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 3, Gerrit.RESOURCES.css().dataCell()); setRowItem(row, plugin); }

Target:
void populate(final int row, final PluginInfo plugin) { table.setText(row, 1, plugin.name()); table.setText(row, 2, plugin.version()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 2, Gerrit.RESOURCES.css().dataCell()); setRowItem(row, plugin); }
Source:
public Object[] getNodes() { List<EObject> nodes = new ArrayList<>(); metaModelAdapter = ExtensionPointHelper.getTraceMetamodelAdapter().get(); if (currentSelection.get(0) instanceof EObject) { EObject object = (EObject) currentSelection.get(0); connections = metaModelAdapter.getTransitivelyConnectedElements(object, traceModel); for (Connection c : connections) { nodes.add(c.getOrigin()); nodes.addAll(c.getTargets()); } } return nodes.stream().distinct().collect(Collectors.toList()).toArray(); }

Target:
public Object[] getNodes() { List<EObject> nodes = new ArrayList<>(); if (currentSelection.get(0) instanceof EObject) { EObject object = (EObject) currentSelection.get(0); connections = metaModelAdapter.getTransitivelyConnectedElements(object, traceModel); for (Connection c : connections) { nodes.add(c.getOrigin()); nodes.addAll(c.getTargets()); } } return nodes.stream().distinct().collect(Collectors.toList()).toArray(); }
Source:
public static String combine(String head, List<ParametersSet> params) { StringBuilder combined_params = new StringBuilder(""); if (params != null) { for (ParametersSet ps : params) { for (Parameter param : ps.getParameters()) { combined_params.append(String.format(MATRIX_PARAMETER_TEMPLATE, param.getName(), param.getValue())); } } } combined_params.insert(0, head); return combined_params.toString(); }

Target:
public static String combine(String head, List<ParametersSet> params) { StringBuilder combined_params = new StringBuilder(); if (params != null) { for (ParametersSet ps : params) { for (Parameter param : ps.getParameters()) { combined_params.append(String.format(MATRIX_PARAMETER_TEMPLATE, param.getName(), param.getValue())); } } } combined_params.insert(0, head); return combined_params.toString(); }
Source:
public void testAssignment() throws ParseException { final String net_id = "assistant1"; final String password = "assistant1"; final AssignmentView view = openLoginScreen() .login(net_id, password) .listAssistingCourses() .get(0).click() .listGroups() .get(0).click() .toAssignmentView() .listAssignments() .get(0).click(); final AssignmentView.Assignment assignment = view.getAssignment(); assertEquals("Student Two", assignment.getAuthor()); }

Target:
public void testAssignment() throws ParseException { final AssignmentView view = openLoginScreen() .login(ASSISTANT_USERNAME, ASSISTANT_PASSWORD) .listAssistingCourses() .get(0).click() .listGroups() .get(0).click() .toAssignmentView() .listAssignments() .get(1).click(); final CourseEdition course = courseEditions.find(1); final Group group = groups.find(course).get(0); final Delivery modelDelivery = deliveries.find(group,2L); final Assignment modelAssignment = modelDelivery.getAssignment(); final AssignmentView.Assignment viewAssignment = view.getAssignment(); assertEquals(modelDelivery.getCreatedUser().getName(), viewAssignment.getAuthor()); assertEquals(modelAssignment.getName(), viewAssignment.getName()); assertEquals(modelDelivery.getState(), viewAssignment.getStatus()); }
Source:
public void flush() throws IOException { if (getDepth() == 0 && (localsLocked || lstAppendEnabled)) { unsafeFlush(); } }

Target:
public void flush() throws IOException { if (getDepth() == 0 && !user.hasAnnotations() && (localsLocked || lstAppendEnabled)) { unsafeFlush(); } }
Source:
public InvokeFuture<EhcacheEntityResponse> invokeAsync(EhcacheEntityMessage message, boolean replicate) throws MessageCodecException { InvokeFuture<EhcacheEntityResponse> invoke; if (clientId == null) { throw new IllegalStateException("Client ID cannot be null"); } if (replicate) { message.setId(sequenceGenerator.getAndIncrement()); invoke = endpoint.beginInvoke().message(message).replicate(true).invoke(); } else { invoke = endpoint.beginInvoke().message(message).replicate(false).invoke(); } return invoke; }

Target:
public InvokeFuture<EhcacheEntityResponse> invokeAsync(EhcacheEntityMessage message, boolean replicate) throws MessageCodecException { InvokeFuture<EhcacheEntityResponse> invoke; getClientId(); if (replicate) { message.setId(sequenceGenerator.getAndIncrement()); } return endpoint.beginInvoke().message(message).replicate(replicate).invoke(); }
Source:
public void shouldFailVerificationOnMethodArgument() throws Exception { mock.clear(); mock.add("foo"); verify(mock).clear(); try { verify(mock).add("bar"); } catch (AssertionError expected) { return; } fail(); }

Target:
public void shouldFailVerificationOnMethodArgument() throws Exception { mock.clear(); mock.add("foo"); verify(mock).clear(); assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() { verify(mock).add("bar"); } }).isInstanceOf(ArgumentsAreDifferent.class); }
Source:
protected void encode(ChannelHandlerContext ctx, OnDemandResponse response, ByteBuf buf) { int fs = response.getFs(); int folder = response.getFolder(); ByteBuf container = response.getChunkData(); buf.writeByte(fs); buf.writeShort(folder); int compression = container.readUnsignedByte(); if (response.getPriority() == OnDemandRequest.Priority.LOW) { compression |= 0x80; } buf.writeByte(compression); int bytes = container.readableBytes(); if (bytes > 508) bytes = 508; buf.writeBytes(container.readBytes(bytes)); for (; ; ) { bytes = container.readableBytes(); if (bytes == 0) { break; } else if (bytes > 511) bytes = 511; buf.writeByte(0xFF); final var payload = container.readBytes(bytes); buf.writeBytes(payload); payload.release(); } }

Target:
protected void encode(ChannelHandlerContext ctx, OnDemandResponse response, ByteBuf buf) { int fs = response.getFs(); int folder = response.getFolder(); ByteBuf container = response.getChunkData(); buf.writeByte(fs); buf.writeShort(folder); int compression = container.readUnsignedByte(); if (response.getPriority() == OnDemandRequest.Priority.LOW) { compression |= PREFTECH; } buf.writeByte(compression); buf.writeBytes(container.readBytes(Math.min(ENTRY_PAYLOAD_START, container.readableBytes()))); int bytes; while ((bytes = Math.min(ENTRY_PAYLOAD, container.readableBytes())) != 0) { buf.writeByte(ENTRY_DELIMITER); final var payload = container.readBytes(bytes); buf.writeBytes(payload); payload.release(); } }
Source:
protected void assertL1GetWithConcurrentUpdate(final Cache<Object, String> nonOwnerCache, Cache<Object, String> ownerCache, final Object key, String originalValue, String updateValue) throws InterruptedException, ExecutionException, TimeoutException, BrokenBarrierException { CyclicBarrier barrier = new CyclicBarrier(2); addBlockingInterceptorBeforeTx(nonOwnerCache, barrier, GetKeyValueCommand.class); try { Future<String> future = nonOwnerCache.getAsync(key); barrier.await(1, TimeUnit.SECONDS); assertEquals(originalValue, ownerCache.put(key, updateValue)); asyncWait(key, PutKeyValueCommand.class, ownerCache); barrier.await(); assertEquals(originalValue, future.get(1, TimeUnit.SECONDS)); removeAllBlockingInterceptorsFromCache(nonOwnerCache); assertIsNotInL1(nonOwnerCache, key); assertEquals(updateValue, nonOwnerCache.get(key)); assertIsInL1(nonOwnerCache, key); } finally { removeAllBlockingInterceptorsFromCache(nonOwnerCache); } }

Target:
protected void assertL1GetWithConcurrentUpdate(final Cache<Object, String> nonOwnerCache, Cache<Object, String> ownerCache, final Object key, String originalValue, String updateValue) throws InterruptedException, ExecutionException, TimeoutException, BrokenBarrierException { CyclicBarrier barrier = new CyclicBarrier(2); addBlockingInterceptorBeforeTx(nonOwnerCache, barrier, GetKeyValueCommand.class); try { Future<String> future = nonOwnerCache.getAsync(key); barrier.await(5, TimeUnit.SECONDS); assertEquals(originalValue, ownerCache.put(key, updateValue)); barrier.await(5, TimeUnit.SECONDS); assertEquals(originalValue, future.get(5, TimeUnit.SECONDS)); removeAllBlockingInterceptorsFromCache(nonOwnerCache); assertIsNotInL1(nonOwnerCache, key); assertEquals(updateValue, nonOwnerCache.get(key)); assertIsInL1(nonOwnerCache, key); } finally { removeAllBlockingInterceptorsFromCache(nonOwnerCache); } }
Source:
private void validate(final MultivaluedMap<String, String> data) throws NullPointerException { if (!data.containsKey("EmailAddress")) { throw new NullPointerException("Email address can not be null."); } else if (!data.containsKey("Password")) { throw new NullPointerException("Password can not be null."); } String emailAddress = data.getFirst("EmailAddress"); try { InternetAddress emailAddr = new InternetAddress(emailAddress); emailAddr.validate(); } catch (AddressException ex) { String msg = String.format("Provided email address %s is not valid",emailAddress); if (logger.isDebugEnabled()) { logger.debug(msg); } throw new IllegalArgumentException(msg); } String clientLogin = data.getFirst("EmailAddress").split("@")[0]; for (char ch: ClientLoginConstrains.NOT_ALLOWED_CHARS) { if (clientLogin.indexOf(ch) > -1) { String msg = String.format("Login %s contains invalid character: %s ",data.getFirst("Login"), ch); if (logger.isDebugEnabled()) { logger.debug(msg); } throw new IllegalArgumentException(msg); } } }

Target:
private void validate(final MultivaluedMap<String, String> data) throws NullPointerException { if (!data.containsKey("EmailAddress")) { throw new NullPointerException("Email address can not be null."); } else if (!data.containsKey("Password")) { throw new NullPointerException("Password can not be null."); } String emailAddress = data.getFirst("EmailAddress"); try { InternetAddress emailAddr = new InternetAddress(emailAddress); emailAddr.validate(); } catch (AddressException ex) { String msg = String.format("Provided email address %s is not valid",emailAddress); if (logger.isDebugEnabled()) { logger.debug(msg); } throw new IllegalArgumentException(msg); } String clientLogin = data.getFirst("EmailAddress").split("@")[0]; if (!ClientLoginConstrains.isValidClientLogin(clientLogin)) { String msg = String.format("Login %s contains invalid character(s) ",clientLogin); if (logger.isDebugEnabled()) { logger.debug(msg); } throw new IllegalArgumentException(msg); } }
Source:
private File makeGesturesDirectory(String directory) { File dir = new File(directory); dir.mkdirs(); if (!dir.isDirectory()) { log.warn("Gestures directory doest not exist, will create it.", directory); return null; } return dir; }

Target:
private File makeGesturesDirectory(String directory) { File dir = new File(directory); dir.mkdirs(); if (!dir.isDirectory()) { log.warn("Gestures directory doest not exist.", directory); return null; } return dir; }
Source:
private StatementRank getStatementRank(int intRank) { StatementRank result = StatementRank.NORMAL; if (intRank < 1) { result = StatementRank.DEPRECATED; } else if (intRank > 1) { result = StatementRank.PREFERRED; } return result; }

Target:
private StatementRank getStatementRank(int intRank) { switch (intRank) { case 0: return StatementRank.DEPRECATED; case 1: return StatementRank.NORMAL; case 2: return StatementRank.PREFERRED; default: throw new IllegalArgumentException("Unknown statement rank " + intRank); } }
Source:
private void reportToServer(String tokenString){ isReportting = true; RequestTranscation transcation = createUploadRequestTranscation(tokenString); if (transcation == null){ return; } byte[] logData = getLogData(); if (logData == null && logData.length == 9){ return; } transcation.reportLog(logData, X_Log_Client_Id, true, new RequestTranscation.RequestCompleteHandler() { @Override public void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics requestMetrics, JSONObject response) { if (responseInfo.isOK()){ lastReportTime = new Date().getTime(); if (X_Log_Client_Id == null && responseInfo.responseHeader != null && responseInfo.responseHeader.get("x-log-client-id") != null){ X_Log_Client_Id = responseInfo.responseHeader.get("x-log-client-id"); } cleanTempLogFile(); } isReportting = false; } }); }

Target:
private void reportToServer(String tokenString){ isReporting = true; RequestTransaction transaction = createUploadRequestTransaction(tokenString); if (transaction == null){ return; } byte[] logData = getLogData(); if (logData == null && logData.length == 9){ return; } transaction.reportLog(logData, X_Log_Client_Id, true, new RequestTransaction.RequestCompleteHandler() { @Override public void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics requestMetrics, JSONObject response) { if (responseInfo.isOK()){ lastReportTime = new Date().getTime(); if (X_Log_Client_Id == null && responseInfo.responseHeader != null && responseInfo.responseHeader.get("x-log-client-id") != null){ X_Log_Client_Id = responseInfo.responseHeader.get("x-log-client-id"); } cleanTempLogFile(); } isReporting = false; } }); }
Source:
public int getRateLimiterAspectOrder() { return Ordered.LOWEST_PRECEDENCE - 1; }

Target:
public int getRateLimiterAspectOrder() { return rateLimiterAspectOrder; }
Source:
protected String encrypt(String clearText) { try { Logger.d(TAG, "Started encrypt"); final byte[] bytes = clearText != null ? clearText.getBytes() : new byte[0]; SecretKey secretKey = getSecretKeyForAPI(); Cipher pbeCipher = Cipher.getInstance(CIPHER_ALGORITHM); IvParameterSpec ivSpec = new IvParameterSpec(IV); pbeCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); String encrypted = new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP), AuthenticationConstants.ENCODING_UTF8); Logger.d(TAG, "Finished encryption"); return encrypted; } catch (Exception e) { Logger.e(TAG, "It failed to use encryption", "", ADALError.ENCRYPTION_FAILED); } return clearText; }

Target:
protected String encrypt(String clearText) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException, NoSuchPaddingException { Logger.d(TAG, "Starting encryption"); if (StringExtensions.IsNullOrBlank(clearText)) { throw new IllegalArgumentException("input is empty or null"); } loadSecretKeyForAPI(); final byte[] blobVersion = sBlobVersion.getBytes(AuthenticationConstants.ENCODING_UTF8); final byte[] bytes = clearText.getBytes(AuthenticationConstants.ENCODING_UTF8); byte[] iv = new byte[DATA_KEY_LENGTH]; mRandom.nextBytes(iv); IvParameterSpec ivSpec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); Mac mac = Mac.getInstance(MAC_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, sKey, ivSpec); byte[] encrypted = cipher.doFinal(bytes); mac.init(sMacKey); mac.update(blobVersion); mac.update(encrypted); mac.update(iv); byte[] macDigest = mac.doFinal(); byte[] blobVerAndEncryptedDataAndIVAndMacDigest = new byte[blobVersion.length + encrypted.length + iv.length + macDigest.length]; System.arraycopy(blobVersion, 0, blobVerAndEncryptedDataAndIVAndMacDigest, 0, blobVersion.length); System.arraycopy(encrypted, 0, blobVerAndEncryptedDataAndIVAndMacDigest, blobVersion.length, encrypted.length); System.arraycopy(iv, 0, blobVerAndEncryptedDataAndIVAndMacDigest, blobVersion.length + encrypted.length, iv.length); System.arraycopy(macDigest, 0, blobVerAndEncryptedDataAndIVAndMacDigest, blobVersion.length + encrypted.length + iv.length, macDigest.length); String encryptedText = new String(Base64.encode(blobVerAndEncryptedDataAndIVAndMacDigest, Base64.NO_WRAP), AuthenticationConstants.ENCODING_UTF8); Logger.d(TAG, "Finished encryption"); return ENCODE_VERSION + encryptedText; }
Source:
private List<String> sanitiseUserIndexPaths(List<String> userIndexPaths) { List<String> sanitisedUserIndexPaths = new ArrayList<>(); for (String userIndexPath : userIndexPaths) { if (PathUtils.getName(userIndexPath).equals(PurgeOldVersionUtils.OAK_INDEX)) { sanitisedUserIndexPaths.add(userIndexPath); } else if (PathUtils.getName(PathUtils.getParentPath(userIndexPath)).equals(PurgeOldVersionUtils.OAK_INDEX)) { sanitisedUserIndexPaths.add(IndexName.parse(userIndexPath).getBaseName()); } else { throw new RuntimeException(userIndexPath + " indexpath is not valid"); } } return sanitisedUserIndexPaths; }

Target:
private List<String> sanitiseUserIndexPaths(List<String> userIndexPaths) { List<String> sanitisedUserIndexPaths = new ArrayList<>(); for (String userIndexPath : userIndexPaths) { if (PathUtils.getName(userIndexPath).equals(PurgeOldVersionUtils.OAK_INDEX)) { sanitisedUserIndexPaths.add(userIndexPath); } else if (PathUtils.getName(PathUtils.getParentPath(userIndexPath)).equals(PurgeOldVersionUtils.OAK_INDEX)) { sanitisedUserIndexPaths.add(IndexName.parse(userIndexPath).getBaseName()); } else { throw new IllegalArgumentException(userIndexPath + " indexpath is not valid"); } } return sanitisedUserIndexPaths; }
Source:
public void removeWidget(String pageCode, int pos) throws ApsSystemException { try { Widget widget = this.getDraftPage(pageCode).getWidgets()[pos]; super.removeWidget(pageCode, pos); String stringId = widget != null && widget.getConfig() != null ? widget.getConfig().getProperty(KieBpmSystemConstants.WIDGET_PARAM_DATA_UX_ID) : null; if (stringId != null) { int modelId = Integer.valueOf(stringId); DataObjectModel model = new DataObjectModel(); model.setId(modelId); this.getDataObjectModelManager().removeDataObjectModel(model); } } catch (Throwable t) { String message = "Error removing the widget from the page '" + pageCode + "' in the frame " + pos; _kielogger.error("Error removing the widget from the page '{}' in the frame {}", pageCode, pos, t); throw new ApsSystemException(message, t); } }

Target:
public void removeWidget(String pageCode, int pos) throws ApsSystemException { try { Widget widget = this.getDraftPage(pageCode).getWidgets()[pos]; super.removeWidget(pageCode, pos); String stringId = null; if (widget != null && widget.getConfig() != null) { stringId = widget.getConfig().getProperty(KieBpmSystemConstants.WIDGET_PARAM_DATA_UX_ID); } if (stringId != null) { int modelId = Integer.valueOf(stringId); DataObjectModel model = new DataObjectModel(); model.setId(modelId); this.getDataObjectModelManager().removeDataObjectModel(model); } } catch (Throwable t) { String message = "Error removing the widget from the page '" + pageCode + "' in the frame " + pos; _kielogger.error("Error removing the widget from the page '{}' in the frame {}", pageCode, pos, t); throw new ApsSystemException(message, t); } }
Source:
public Object getParent(Object element) { Object toReturn = null; if (element instanceof AttributeLineElement) { toReturn = ((AttributeLineElement) element).getParent(); } else if (element instanceof AttributeMatch) { AttributeMatch match = (AttributeMatch) element; toReturn = match.getArtifact(); } else if (element instanceof Artifact) { Artifact resource = (Artifact) element; try { toReturn = resource.getParent(); if (toReturn == null && resource.isNotRootedInDefaultRoot()) { toReturn = orphanParent; } } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex); if (ex instanceof MultipleArtifactsExist) { toReturn = multiParent; } } } return toReturn; }

Target:
public Object getParent(Object element) { Object toReturn = null; if (element instanceof AttributeLineElement) { toReturn = ((AttributeLineElement) element).getParent(); } else if (element instanceof AttributeMatch) { AttributeMatch match = (AttributeMatch) element; toReturn = match.getArtifact(); } else if (element instanceof Artifact) { Artifact resource = (Artifact) element; try { toReturn = resource.getParent(); if (toReturn == null && resource.isNotRootedInDefaultRoot()) { toReturn = orphanParent; } } catch (MultipleArtifactsExist ex) { toReturn = multiParent; } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex); } } return toReturn; }
Source:
public final Object copyAs(final String source, final String dest, final SBlock fail) { try { Files.copy(Paths.get(source), Paths.get(dest), new CopyOption[0]); } catch (IOException e) { fail.getMethod().invoke(new Object[] {fail, e.toString()}); } return Nil.nilObject; }

Target:
public final Object copyAs(final String source, final String dest, final SBlock fail) { try { Files.copy(Paths.get(source), Paths.get(dest), new CopyOption[0]); } catch (IOException e) { dispatchHandler.executeDispatch(new Object[] {fail, e.toString()}); } return Nil.nilObject; }
Source:
public InSessionPageStore(IPageStore delegate, int maxPages, ISerializer serializer) { super(delegate); this.serializer = Args.notNull(serializer, "serializer"); this.maxPages = maxPages; }

Target:
public InSessionPageStore(IPageStore delegate, int maxPages, ISerializer serializer) { this(delegate, serializer, () -> new CountLimitedData(maxPages)); }
Source:
public void testComplexJSONParsing() throws Exception { final String[] jsonPaths = { "expensive:$.expensive", "bicycle_color:$.store.bicycle.color", "bicycle_price:$.store.bicycle.price", "window:$.store.window" }; MockEmitter<StructuredRecord> emitter = new MockEmitter<>(); JSONParser.Config config = new JSONParser.Config("body", com.google.common.base.Joiner.on(",").join(jsonPaths), OUTPUT3.toString()); Transform<StructuredRecord, StructuredRecord> transform = new JSONParser(config); MockPipelineConfigurer mockPipelineConfigurer = new MockPipelineConfigurer(INPUT1); transform.configurePipeline(mockPipelineConfigurer); transform.initialize(null); transform.transform(StructuredRecord.builder(INPUT1) .set("body", json) .build(), emitter); Assert.assertEquals(10, emitter.getEmitted().get(0).get("expensive")); Assert.assertEquals("red", emitter.getEmitted().get(0).get("bicycle_color")); Assert.assertEquals(19.95, emitter.getEmitted().get(0).get("bicycle_price")); }

Target:
public void testComplexJSONParsing() throws Exception { final String[] jsonPaths = { "expensive:$.expensive", "bicycle_color:$.store.bicycle.color", "bicycle_price:$.store.bicycle.price", "window:$.store.window" }; MockEmitter<StructuredRecord> emitter = new MockEmitter<>(); JSONParser.Config config = new JSONParser.Config("body", Joiner.on(",").join(jsonPaths), OUTPUT3.toString()); Transform<StructuredRecord, StructuredRecord> transform = new JSONParser(config); MockPipelineConfigurer mockPipelineConfigurer = new MockPipelineConfigurer(INPUT1); transform.configurePipeline(mockPipelineConfigurer); transform.initialize(null); transform.transform(StructuredRecord.builder(INPUT1) .set("body", json) .build(), emitter); Assert.assertEquals(10, emitter.getEmitted().get(0).get("expensive")); Assert.assertEquals("red", emitter.getEmitted().get(0).get("bicycle_color")); Assert.assertEquals(19.95, emitter.getEmitted().get(0).get("bicycle_price")); }
Source:
public HttpModelControllerClient(String host, int port, String username, String password, int timeoutMillis) { target = new HttpHost(host, port, "http"); credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(username, password)); RequestConfig.Builder configBuilder = RequestConfig.copy(RequestConfig.DEFAULT); if (timeoutMillis != NO_TIMEOUT) { configBuilder.setConnectTimeout(timeoutMillis).setSocketTimeout(timeoutMillis); } requestConfig = configBuilder.build(); url = String.format("http://%s:%s/management", host, port); }

Target:
HttpModelControllerClient(String host, int port, String username, String password, int timeoutMillis) throws IOException { url = "http://" + host + ":" + port + "/management"; RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); if (timeoutMillis != NO_TIMEOUT) { requestConfigBuilder .setConnectTimeout(timeoutMillis) .setSocketTimeout(timeoutMillis); } requestConfig = requestConfigBuilder.build(); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .build(); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (username != null && password != null) { credentialsProvider.setCredentials( new AuthScope(host, port, getManagementRealm(url), AuthSchemes.DIGEST), new UsernamePasswordCredentials(username, password)); } client = HttpClients.custom() .setConnectionManager(new PoolingHttpClientConnectionManager(registry)) .setDefaultCredentialsProvider(credentialsProvider) .setDefaultRequestConfig(requestConfig) .build(); }
Source:
public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); pageLoadStrategy.onSaveInstanceState(outState); outState.putParcelableArrayList("tabList", tabList); }

Target:
public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); pageLoadStrategy.onSaveInstanceState(outState); outState.putParcelableArrayList(TAB_LIST_KEY, tabList); }
Source:
public void should_reprepare_statement_with_keyspace_on_the_fly() { try (CqlSession session = SessionUtils.newSession(ccmRule)) { executeDdl( session, String.format( "CREATE TABLE IF NOT EXISTS %s.bar (k int primary key)", sessionRule.keyspace())); PreparedStatement pst = session.prepare( SimpleStatement.newInstance("SELECT * FROM bar WHERE k=?") .setKeyspace(sessionRule.keyspace())); executeDdl(session, String.format("DROP TABLE %s.bar", sessionRule.keyspace())); executeDdl( session, String.format("CREATE TABLE %s.bar (k int primary key)", sessionRule.keyspace())); session.execute(pst.bind(0)); } }

Target:
public void should_reprepare_statement_with_keyspace_on_the_fly() { try (CqlSession session = SessionUtils.newSession(ccmRule)) { executeDdl( session, String.format( "CREATE TABLE IF NOT EXISTS %s.bar (k int primary key)", sessionRule.keyspace())); PreparedStatement pst = session.prepare( SimpleStatement.newInstance("SELECT * FROM bar WHERE k=?") .setKeyspace(sessionRule.keyspace())); executeDdl(session, String.format("DROP TABLE %s.bar", sessionRule.keyspace())); executeDdl( session, String.format("CREATE TABLE %s.bar (k int primary key)", sessionRule.keyspace())); assertThat(preparedStatementExistsOnServer(session, pst.getId())).isFalse(); session.execute(pst.bind(0)); assertThat(preparedStatementExistsOnServer(session, pst.getId())).isTrue(); } }
Source:
void configureRequest(HttpConnection conn) throws IOException { GSSManager gssManager = GSS_MANAGER_FACTORY.newInstance(conn .getURL()); String host = conn.getURL().getHost(); String peerName = "HTTP@" + host.toLowerCase(); try { GSSName gssName = gssManager.createName(peerName, GSSName.NT_HOSTBASED_SERVICE); GSSContext context = gssManager.createContext(gssName, OID, null, GSSContext.DEFAULT_LIFETIME); context.requestCredDeleg(true); byte[] token = context.initSecContext(prevToken, 0, prevToken.length); conn.setRequestProperty(HDR_AUTHORIZATION, getType().name() + " " + Base64.encodeBytes(token)); } catch (GSSException e) { IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } }

Target:
void configureRequest(HttpConnection conn) throws IOException { GSSManager gssManager = GSS_MANAGER_FACTORY.newInstance(conn .getURL()); String host = conn.getURL().getHost(); String peerName = "HTTP@" + host.toLowerCase(); try { GSSName gssName = gssManager.createName(peerName, GSSName.NT_HOSTBASED_SERVICE); GSSContext context = gssManager.createContext(gssName, OID, null, GSSContext.DEFAULT_LIFETIME); context.requestCredDeleg(true); byte[] token = context.initSecContext(prevToken, 0, prevToken.length); conn.setRequestProperty(HDR_AUTHORIZATION, getType().getName() + " " + Base64.encodeBytes(token)); } catch (GSSException e) { IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } }
Source:
public Response deleteBranchExchange(String path) { boolean modified = false; String exchangePath = asExchangeLocator(path); IResourceLocator locator = resourceManager.getResourceLocator(exchangePath); if (locator != null) { int deleteResult = resourceManager.delete(locator); switch (deleteResult) { case IResourceManager.OK: activityLog.createEntry(BRANCH_OPERATION_TYPEID, ActivityLog.INITIAL_STATUS, String.format("Branch Operation Delete Branch Exachange Resource {resource: %s, locator %s}", path, locator.getLocation())); modified = true; break; case IResourceManager.FAIL: throw new OseeWebApplicationException(Status.INTERNAL_SERVER_ERROR, "Error deleting exchange resource [%s] - locator [%s]", path, locator.getLocation()); case IResourceManager.RESOURCE_NOT_FOUND: default: break; } } return OrcsRestUtil.asResponse(modified); }

Target:
public Response deleteBranchExchange(String path) { boolean modified = false; String exchangePath = asExchangeLocator(path); IResourceLocator locator = resourceManager.getResourceLocator(exchangePath); if (locator != null) { int deleteResult = resourceManager.delete(locator); switch (deleteResult) { case IResourceManager.OK: try { activityLog.createEntry(BRANCH_OPERATION_TYPEID, ActivityLog.INITIAL_STATUS, String.format("Branch Operation Delete Branch Exachange Resource {resource: %s, locator %s}", path, locator.getLocation())); } catch (OseeCoreException ex) { OseeLog.log(ActivityLog.class, OseeLevel.SEVERE_POPUP, ex); } modified = true; break; case IResourceManager.FAIL: throw new OseeWebApplicationException(Status.INTERNAL_SERVER_ERROR, "Error deleting exchange resource [%s] - locator [%s]", path, locator.getLocation()); case IResourceManager.RESOURCE_NOT_FOUND: default: break; } } return OrcsRestUtil.asResponse(modified); }
Source:
private Undertow configureServer() { gracefulShutdown = new HermesShutdownHandler(deployAndStart(), hermesMetrics); Undertow.Builder builder = Undertow.builder() .addHttpListener(port, host) .setServerOption(REQUEST_PARSE_TIMEOUT, configFactory.getIntProperty(FRONTEND_REQUEST_PARSE_TIMEOUT)) .setServerOption(MAX_HEADERS, configFactory.getIntProperty(FRONTEND_MAX_HEADERS)) .setServerOption(MAX_PARAMETERS, configFactory.getIntProperty(FRONTEND_MAX_PARAMETERS)) .setServerOption(MAX_COOKIES, configFactory.getIntProperty(FRONTEND_MAX_COOKIES)) .setServerOption(ALWAYS_SET_KEEP_ALIVE, configFactory.getBooleanProperty(FRONTEND_SET_KEEP_ALIVE)) .setSocketOption(BACKLOG, configFactory.getIntProperty(FRONTEND_BACKLOG_SIZE)) .setSocketOption(READ_TIMEOUT, configFactory.getIntProperty(FRONTEND_READ_TIMEOUT)) .setIoThreads(configFactory.getIntProperty(FRONTEND_IO_THREADS_COUNT)) .setWorkerThreads(configFactory.getIntProperty(FRONTEND_WORKER_THREADS_COUNT)) .setBufferSize(configFactory.getIntProperty(FRONTEND_BUFFER_SIZE)) .setHandler(gracefulShutdown); if (configFactory.getBooleanProperty(FRONTEND_HTTP2_ENABLED)) { builder.setServerOption(ENABLE_HTTP2, true) .addHttpsListener(portSSL, host, new SSLContextSupplier(configFactory).get()); } this.undertow = builder.build(); return undertow; }

Target:
private Undertow configureServer() { gracefulShutdown = new HermesShutdownHandler(deployAndStart(), hermesMetrics); Undertow.Builder builder = Undertow.builder() .addHttpListener(port, host) .setServerOption(REQUEST_PARSE_TIMEOUT, configFactory.getIntProperty(FRONTEND_REQUEST_PARSE_TIMEOUT)) .setServerOption(MAX_HEADERS, configFactory.getIntProperty(FRONTEND_MAX_HEADERS)) .setServerOption(MAX_PARAMETERS, configFactory.getIntProperty(FRONTEND_MAX_PARAMETERS)) .setServerOption(MAX_COOKIES, configFactory.getIntProperty(FRONTEND_MAX_COOKIES)) .setServerOption(ALWAYS_SET_KEEP_ALIVE, configFactory.getBooleanProperty(FRONTEND_SET_KEEP_ALIVE)) .setSocketOption(BACKLOG, configFactory.getIntProperty(FRONTEND_BACKLOG_SIZE)) .setSocketOption(READ_TIMEOUT, configFactory.getIntProperty(FRONTEND_READ_TIMEOUT)) .setIoThreads(configFactory.getIntProperty(FRONTEND_IO_THREADS_COUNT)) .setWorkerThreads(configFactory.getIntProperty(FRONTEND_WORKER_THREADS_COUNT)) .setBufferSize(configFactory.getIntProperty(FRONTEND_BUFFER_SIZE)) .setHandler(gracefulShutdown); if (configFactory.getBooleanProperty(FRONTEND_HTTP2_ENABLED)) { builder.setServerOption(ENABLE_HTTP2, true) .addHttpsListener(sslPort, host, new SSLContextSupplier(configFactory).get()); } this.undertow = builder.build(); return undertow; }
Source:
private static void assemblerFromForm(HttpAction action, StreamRDF dest) { String dbType = action.getRequest().getParameter(paramDatasetType) ; String dbName = action.getRequest().getParameter(paramDatasetName) ; if ( StringUtils.isBlank(dbType) || StringUtils.isBlank(dbName) ) ServletOps.errorBadRequest("Required parameters: dbName and dbType"); Map<String, String> params = new HashMap<>() ; if ( dbName.startsWith("/") ) params.put(Template.NAME, dbName.substring(1)) ; else params.put(Template.NAME, dbName) ; FusekiSystem.addGlobals(params); String template = dbTypeToTemplate.get(dbType.toLowerCase(Locale.ROOT)); if ( template == null ) ServletOps.errorBadRequest(format("dbType can be only '%s' or '%s'", tDatabaseTDB, tDatabaseMem)) ; String syntax = TemplateFunctions.templateFile(template, params, Lang.TTL) ; RDFParser.create().source(new StringReader(syntax)).base("http://base/").lang(Lang.TTL).parse(dest); }

Target:
private static void assemblerFromForm(HttpAction action, StreamRDF dest) { String dbType = action.getRequest().getParameter(paramDatasetType) ; String dbName = action.getRequest().getParameter(paramDatasetName) ; if ( StringUtils.isBlank(dbType) || StringUtils.isBlank(dbName) ) ServletOps.errorBadRequest("Required parameters: dbName and dbType"); Map<String, String> params = new HashMap<>() ; if ( dbName.startsWith("/") ) params.put(Template.NAME, dbName.substring(1)) ; else params.put(Template.NAME, dbName) ; FusekiSystem.addGlobals(params); String template = dbTypeToTemplate.get(dbType.toLowerCase(Locale.ROOT)); if ( template == null ) ServletOps.errorBadRequest(format("dbType can be only '%s', '%s' or '%s'", tDatabaseTDB, tDatabaseTDB2, tDatabaseMem)) ; String syntax = TemplateFunctions.templateFile(template, params, Lang.TTL) ; RDFParser.create().source(new StringReader(syntax)).base("http://base/").lang(Lang.TTL).parse(dest); }
Source:
private void handleNotOperator(SubscriptionContext ctx, PyUnaryExpressionTree unary) { PyExpressionTree negatedExpr = unary.expression(); if (negatedExpr.is(Tree.Kind.PARENTHESIZED)) { negatedExpr = ((PyParenthesizedExpressionTree) negatedExpr).expression(); if (negatedExpr.is(Tree.Kind.COMPARISON) || !(negatedExpr instanceof PyBinaryExpressionTree)) { ctx.addIssue(negatedExpr, String.format(MESSAGE, "not")); } } }

Target:
private static void handleNotOperator(SubscriptionContext ctx, PyUnaryExpressionTree unary) { PyExpressionTree negatedExpr = unary.expression(); if (negatedExpr.is(Tree.Kind.PARENTHESIZED)) { negatedExpr = ((PyParenthesizedExpressionTree) negatedExpr).expression(); if (negatedExpr.is(Tree.Kind.COMPARISON) || !(negatedExpr instanceof PyBinaryExpressionTree)) { ctx.addIssue(negatedExpr, String.format(MESSAGE, "not")); } } }
Source:
public Response getPublicDatasets(@Context SecurityContext sc, @Context HttpServletRequest req) throws AppException { List<Dataset> clusterDatasets = delaDatasetCtrl.getLocalPublicDatasets(); DistributedFileSystemOps dfso = dfs.getDfsOps(); List<LocalDatasetDTO> localDS; try { localDS = LocalDatasetHelper.parse(datasetCtrl, dfso, clusterDatasets); } finally { dfso.close(); } GenericEntity<List<LocalDatasetDTO>> datasets = new GenericEntity<List<LocalDatasetDTO>>(localDS) {}; return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(datasets).build(); }

Target:
public Response getPublicDatasets(@Context SecurityContext sc, @Context HttpServletRequest req) throws AppException { List<Dataset> clusterDatasets = delaDatasetCtrl.getLocalPublicDatasets(); DistributedFileSystemOps dfso = dfs.getDfsOps(); List<LocalDatasetDTO> localDS; try { localDS = LocalDatasetHelper.parse(datasetCtrl, dfso, clusterDatasets); } finally { dfs.closeDfsClient(dfso); } GenericEntity<List<LocalDatasetDTO>> datasets = new GenericEntity<List<LocalDatasetDTO>>(localDS) {}; return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(datasets).build(); }
Source:
public FileActivity( User source, Type type, Purpose purpose, IFile newFile, IFile oldFile, byte[] content, String encoding) { super(source, newFile); if (type == null) throw new IllegalArgumentException("type must not be null"); if (purpose == null) throw new IllegalArgumentException("purpose must not be null"); if (newFile == null) throw new IllegalArgumentException("newPath must not be null"); switch (type) { case CREATED: if (content == null || oldFile != null) throw new IllegalArgumentException(); break; case REMOVED: if (content != null || oldFile != null) throw new IllegalArgumentException(); break; case MOVED: if (oldFile == null) throw new IllegalArgumentException(); break; } if (encoding == null && (type == Type.CREATED || (type == Type.MOVED && content != null))) { throw new IllegalArgumentException( "Encoding must be passed if type is created and/or binary content is passed"); } this.type = type; this.oldFile = oldFile != null ? new ResourceTransportWrapper<>(oldFile) : null; this.content = content; this.encoding = encoding; this.purpose = purpose; }

Target:
public FileActivity( User source, Type type, Purpose purpose, IFile newFile, IFile oldFile, byte[] content, String encoding) { super(source, newFile); if (type == null) throw new IllegalArgumentException("type must not be null"); if (purpose == null) throw new IllegalArgumentException("purpose must not be null"); if (newFile == null) throw new IllegalArgumentException("newPath must not be null"); switch (type) { case CREATED: if (content == null || oldFile != null) throw new IllegalArgumentException(); break; case REMOVED: if (content != null || oldFile != null) throw new IllegalArgumentException(); break; case MOVED: if (oldFile == null) throw new IllegalArgumentException(); break; } if (encoding == null && (type == Type.CREATED || (type == Type.MOVED && content != null))) { throw new IllegalArgumentException( "Encoding must be passed if type is created and/or binary content is passed"); } this.type = type; this.oldFileWrapper = oldFile != null ? new ResourceTransportWrapper<>(oldFile) : null; this.content = content; this.encoding = encoding; this.purpose = purpose; }
Source:
private void doSpell(final String cmd, final String id, final JSONArray paramArray) { final SpellChecker checker = new SpellChecker(dict); final Set<String> errors = new HashSet(); checker.addSpellCheckListener(new SpellCheckListener() { @Override public void spellingError(SpellCheckEvent event) { errors.add(event.getInvalidWord()); } }); JSONArray words = paramArray.optJSONArray(1); checker.checkSpelling(new StringWordTokenizer(words.toString())); respond(errors.iterator(), cmd, id); }

Target:
private void doSpell(final String cmd, final String id, final JSONArray paramArray) { final SpellChecker checker = new SpellChecker(dict); final Set<String> errors = new HashSet<>(); checker.addSpellCheckListener(new SpellCheckListener() { @Override public void spellingError(SpellCheckEvent event) { errors.add(event.getInvalidWord()); } }); JSONArray words = paramArray.optJSONArray(1); checker.checkSpelling(new StringWordTokenizer(words.toString())); respond(errors.iterator(), cmd, id); }