auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private GitResourceVariantTreeProvider createTreeProviderWithAdditions() throws Exception { testRepo.createBranch(MASTER, BASE); testRepo.createAndCheckoutBranch(MASTER, BRANCH); file2 = testRepo.createFile(iProject, "file2"); testRepo.appendContentAndCommit(iProject, file2, INITIAL_CONTENT_2, "Creation of file2 in branch2."); testRepo.checkoutBranch(MASTER); file1 = testRepo.createFile(iProject, "file1"); testRepo.appendContentAndCommit(iProject, file1, INITIAL_CONTENT_1, "Creation of file1 in branch1."); iProject.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); try (RevWalk walk = new RevWalk(repo)) { RevTree baseTree = walk.parseTree(repo.resolve(BASE)); RevTree sourceTree = walk.parseTree(repo.resolve(MASTER)); RevTree remoteTree = walk.parseTree(repo.resolve(BRANCH)); TreeWalk tw = new NameConflictTreeWalk(repo); tw.addTree(baseTree); tw.addTree(sourceTree); tw.addTree(remoteTree); return new TreeWalkResourceVariantTreeProvider(repo, tw, 0, 1, 2); } }

Target:
private GitResourceVariantTreeProvider createTreeProviderWithAdditions() throws Exception { testRepo.createBranch(MASTER, BASE); testRepo.createAndCheckoutBranch(MASTER, BRANCH); file2 = testRepo.createFile(iProject, "file2"); testRepo.appendContentAndCommit(iProject, file2, INITIAL_CONTENT_2, "Creation of file2 in branch2."); testRepo.checkoutBranch(MASTER); file1 = testRepo.createFile(iProject, "file1"); testRepo.appendContentAndCommit(iProject, file1, INITIAL_CONTENT_1, "Creation of file1 in branch1."); iProject.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); try (RevWalk walk = new RevWalk(repo)) { RevTree baseTree = walk.parseTree(repo.resolve(BASE)); RevTree sourceTree = walk.parseTree(repo.resolve(MASTER)); RevTree remoteTree = walk.parseTree(repo.resolve(BRANCH)); TreeWalk tw = new TreeWalk(repo); tw.addTree(baseTree); tw.addTree(sourceTree); tw.addTree(remoteTree); return new TreeWalkResourceVariantTreeProvider(repo, tw, 0, 1, 2); } }
Source:
protected void updateContent(TargetBean data) { _pageContent.removeClassName("hide"); _targetNameBox.setValue(data.getName()); _descriptionBox.setValue(data.getDescription()); for (int i = 0; i < _targetType.getItemCount(); i++) { if (_targetType.getValue(i) != null && _targetType.getValue(i).equals(data.getType().getValue())) { _targetType.setSelectedIndex(i); break; } } _classifiersTable.setValue(data.getClassifiers()); refreshTargetForm(data); if (_uuid == null || _uuid.equals("")) { _resetButton.setVisible(false); } }

Target:
protected void updateContent(TargetBean data) { _pageContent.removeClassName("hide"); _targetNameBox.setValue(data.getName()); _descriptionBox.setValue(data.getDescription()); _targetType.setValue(data.getType().getValue()); _classifiersTable.setValue(data.getClassifiers()); refreshTargetForm(data); if (_uuid == null || _uuid.equals("")) { _resetButton.setVisible(false); } }
Source:
public Version getVersion(IProgressMonitor monitor) { Optional<Version> version = Optional.empty(); if (path != null) { try { ProcessBuilder builder = new ProcessBuilder(path, "version"); Process process = builder.start(); String line; try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { while (!monitor.isCanceled() && (!version.isPresent()) && ((line = reader.readLine()) != null)) { version = parseVersion(line); } } } catch (IOException e) { } } return version.orElse(Version.emptyVersion); }

Target:
public Version getVersion(IProgressMonitor monitor) { Optional<Version> version = Optional.empty(); if (path != null) { try { ProcessBuilder builder = new ProcessBuilder(path, "version"); Process process = builder.start(); String line; try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { while (!monitor.isCanceled() && (!version.isPresent()) && ((line = reader.readLine()) != null)) { version = parseVersion(line); } } } catch (IOException e) { OpenShiftCoreActivator.logError(e.getLocalizedMessage(), e); } } return version.orElse(Version.emptyVersion); }
Source:
public ImmutableSetMultimap<String, String> getValues(Collection<String> entityIds) { UpdateBuilder b = new UpdateBuilder(getValues); b.bindUris("entityList", entityIds); b.bind("uris.value", uris.value()); b.bind("uris.statement", uris.statement()); b.bindUri("prov:wasDerivedFrom", Provenance.WAS_DERIVED_FROM); return rdfClient.resultToMap(rdfClient.query(b.toString()), "entity", "s"); }

Target:
public ImmutableSetMultimap<String, String> getValues(Collection<String> entityIds) { UpdateBuilder b = new UpdateBuilder(getValues); b.bindUris("entityList", entityIds); b.bind("uris.value", uris.value()); b.bind("uris.statement", uris.statement()); b.bindUri("prov:wasDerivedFrom", Provenance.WAS_DERIVED_FROM); return rdfClient.selectToMap(b.toString(), "entity", "s"); }
Source:
public storage_pool getForVds(Guid vds, Guid userID, boolean isFiltered) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("vdsId", vds); ParameterizedRowMapper<storage_pool> mapper = new ParameterizedRowMapper<storage_pool>() { @Override public storage_pool mapRow(ResultSet rs, int rowNum) throws SQLException { storage_pool entity = new storage_pool(); entity.setdescription(rs.getString("description")); entity.setId(Guid.createGuidFromString(rs.getString("id"))); entity.setname(rs.getString("name")); entity.setstorage_pool_type(StorageType.forValue(rs .getInt("storage_pool_type"))); entity.setstatus(StoragePoolStatus.forValue(rs.getInt("status"))); entity.setmaster_domain_version(rs .getInt("master_domain_version")); entity.setspm_vds_id(NGuid.createGuidFromString(rs .getString("spm_vds_id"))); entity.setcompatibility_version(new Version(rs .getString("compatibility_version"))); entity.setQuotaEnforcementType(QuotaEnforcementTypeEnum.forValue(rs.getInt("quota_enforcement_type"))); entity.setStoragePoolFormatType(getStorageFormatTypeForPool(rs)); return entity; } }; return getCallsHandler().executeRead("Getstorage_poolsByVdsId", mapper, parameterSource); }

Target:
public storage_pool getForVds(Guid vds, Guid userID, boolean isFiltered) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("vdsId", vds).addValue("user_id", userID).addValue("is_filtered", isFiltered); ParameterizedRowMapper<storage_pool> mapper = new ParameterizedRowMapper<storage_pool>() { @Override public storage_pool mapRow(ResultSet rs, int rowNum) throws SQLException { storage_pool entity = new storage_pool(); entity.setdescription(rs.getString("description")); entity.setId(Guid.createGuidFromString(rs.getString("id"))); entity.setname(rs.getString("name")); entity.setstorage_pool_type(StorageType.forValue(rs .getInt("storage_pool_type"))); entity.setstatus(StoragePoolStatus.forValue(rs.getInt("status"))); entity.setmaster_domain_version(rs .getInt("master_domain_version")); entity.setspm_vds_id(NGuid.createGuidFromString(rs .getString("spm_vds_id"))); entity.setcompatibility_version(new Version(rs .getString("compatibility_version"))); entity.setQuotaEnforcementType(QuotaEnforcementTypeEnum.forValue(rs.getInt("quota_enforcement_type"))); entity.setStoragePoolFormatType(getStorageFormatTypeForPool(rs)); return entity; } }; return getCallsHandler().executeRead("Getstorage_poolsByVdsId", mapper, parameterSource); }
Source:
private void applyRename(List<RenameProject> projects) { List<Either<TextDocumentEdit, ResourceOperation>> edits = new ArrayList<>(); for (RenameProject project : projects) { project.getTextDocumentEdits().forEach(edit -> edits.add(Either.forLeft(edit))); ; } workspaceEditAction.applyWorkspaceEdit(new WorkspaceEdit(edits)); }

Target:
private void applyRename(List<RenameProject> projects) { List<Either<TextDocumentEdit, ResourceOperation>> edits = new ArrayList<>(); for (RenameProject project : projects) { project.getTextDocumentEdits().forEach(edit -> edits.add(Either.forLeft(edit))); } workspaceEditAction.applyWorkspaceEdit(new WorkspaceEdit(edits)); }
Source:
void handleBookieFailure(final Map<Integer, BookieSocketAddress> failedBookies) { if (clientCtx.getConf().disableEnsembleChangeFeature.isAvailable()) { if (LOG.isDebugEnabled()) { LOG.debug("Ensemble change is disabled. Retry sending to failed bookies for ledger {}.", failedBookies, ledgerId); } unsetSuccessAndSendWriteRequest(getCurrentEnsemble(), failedBookies.keySet()); return; } if (writeFlags.contains(WriteFlag.DEFERRED_SYNC)) { if (LOG.isDebugEnabled()) { LOG.debug("Cannot perform ensemble change with write flags {}. " + "Failed bookies for ledger {}.", writeFlags, failedBookies, ledgerId); } handleUnrecoverableErrorDuringAdd(WriteException); return; } synchronized (metadataLock) { if (changingEnsemble) { delayedWriteFailedBookies.putAll(failedBookies); } else { changingEnsemble = true; Map<Integer, BookieSocketAddress> toReplace = new HashMap<>(delayedWriteFailedBookies); delayedWriteFailedBookies.clear(); toReplace.putAll(failedBookies); List<BookieSocketAddress> origEnsemble = getCurrentEnsemble(); ensembleChangeLoop(origEnsemble, toReplace); } } }

Target:
void handleBookieFailure(final Map<Integer, BookieSocketAddress> failedBookies) { if (clientCtx.getConf().disableEnsembleChangeFeature.isAvailable()) { if (LOG.isDebugEnabled()) { LOG.debug("Ensemble change is disabled. Retry sending to failed bookies for ledger {}.", failedBookies, ledgerId); } unsetSuccessAndSendWriteRequest(getCurrentEnsemble(), failedBookies.keySet()); return; } if (writeFlags.contains(WriteFlag.DEFERRED_SYNC)) { if (LOG.isDebugEnabled()) { LOG.debug("Cannot perform ensemble change with write flags {}. " + "Failed bookies for ledger {}.", writeFlags, failedBookies, ledgerId); } handleUnrecoverableErrorDuringAdd(WriteException); return; } boolean triggerLoop = false; Map<Integer, BookieSocketAddress> toReplace = null; List<BookieSocketAddress> origEnsemble = null; synchronized (metadataLock) { if (changingEnsemble) { delayedWriteFailedBookies.putAll(failedBookies); } else { changingEnsemble = true; triggerLoop = true; toReplace = new HashMap<>(delayedWriteFailedBookies); delayedWriteFailedBookies.clear(); toReplace.putAll(failedBookies); origEnsemble = getCurrentEnsemble(); } } if (triggerLoop) { ensembleChangeLoop(origEnsemble, toReplace); } }
Source:
private synchronized void tickClock(final String workerId) { assert (workerClockMap.containsKey(workerId)); int workerClock = workerClockMap.get(workerId).intValue(); workerClock++; workerClockMap.put(workerId, workerClock); if (minimumClockWorkers.contains(workerId)) { minimumClockWorkers.remove(workerId); if (minimumClockWorkers.size() == 0) { globalMinimumClock++; broadcastGlobalMinimumClock(); } } else if (workerClock == globalMinimumClock) { minimumClockWorkers.add(workerId); } }

Target:
private synchronized void tickClock(final String workerId) { Integer workerClock = workerClockMap.get(workerId); if (workerClock == null) { throw new RuntimeException(String.format("Uninitialized worker %s sent tick message", workerId)); } workerClock++; workerClockMap.put(workerId, workerClock); if (minimumClockWorkers.remove(workerId)) { if (minimumClockWorkers.size() == 0) { globalMinimumClock++; broadcastGlobalMinimumClock(); } } }
Source:
public VariableBatchStrategy(Ordering<T> ordering, List<Integer> maxActiveGroups, boolean rollingForward) { this.ordering = Objects.requireNonNull(ordering); this.rollingForward = rollingForward; maxActiveGroups.forEach(x -> Preconditions.checkArgument(x > 0)); this.maxActiveGroups = ImmutableList.copyOf(maxActiveGroups); this.totalModInstanceCount = Optional.empty(); }

Target:
public VariableBatchStrategy( Ordering<T> ordering, List<Integer> maxActiveGroups, boolean rollingForward) { this.ordering = Objects.requireNonNull(ordering); this.rollingForward = rollingForward; maxActiveGroups.forEach(x -> Preconditions.checkArgument(x > 0)); this.groupSizes = ImmutableList.copyOf(maxActiveGroups); this.totalModInstanceCount = Optional.empty(); }
Source:
private static void sendWithRest(MessageChannel channel) { IntStream.range(1, 10).forEach(i -> { channel.send(MessageBuilder.withPayload(createEvent()).build()); }); }

Target:
private static void sendWithRest(MessageChannel channel) { for (int i = 0; i < 10; i++) { channel.send(MessageBuilder.withPayload(createEvent()).build()); } }
Source:
public String getTag() { if (tags == null || tags.isEmpty()) { return null; } return tags.iterator().next(); }

Target:
public String getTag() { return tag; }
Source:
void streamingPut(ByteArray key, Versioned<byte[]> value) { if(overwrite == false) { dstStreamingClient.streamingPut(key, value); } else { VectorClock denseClock = VectorClockUtils.makeClockWithCurrentTime(dstServerIds); Versioned<byte[]> updatedValue = new Versioned<byte[]>(value.getValue(), denseClock); dstStreamingClient.streamingPut(key, updatedValue); } entriesForkLifted++; if(entriesForkLifted % progressOps == 0) { logger.info(workName + " fork lifted " + entriesForkLifted + " entries successfully"); } }

Target:
void streamingPut(ByteArray key, Versioned<byte[]> value) { if(overwrite) { VectorClock denseClock = VectorClockUtils.makeClockWithCurrentTime(dstServerIds); Versioned<byte[]> updatedValue = new Versioned<byte[]>(value.getValue(), denseClock); dstStreamingClient.streamingPut(key, updatedValue); } else { dstStreamingClient.streamingPut(key, value); } entriesForkLifted++; if(entriesForkLifted % progressOps == 0) { logger.info(workName + " fork lifted " + entriesForkLifted + " entries successfully"); } }
Source:
private void onSerialOwnershipRequested(Object data) { try { throw new Exception(); } catch (Exception e) { StackTraceElement[] elems = e.getStackTrace(); String requester = elems[elems.length - 4].getClassName(); synchronized (this) { this.notify(); } close(); String myPackage = this.getClass().getPackage().getName(); if (requester.startsWith(myPackage)) requester = "another AT connection"; logger.debug("Connection for port canceled due to ownership request from {}.", port, requester); } }

Target:
private void onSerialOwnershipRequested(Object data) { try { throw new Exception(); } catch (Exception e) { StackTraceElement[] elems = e.getStackTrace(); String requester = elems[elems.length - 4].getClassName(); synchronized (this) { this.notify(); } close(); String myPackage = this.getClass().getPackage().getName(); if (requester.startsWith(myPackage)) requester = "another AT connection"; logger.warn("Connection for port canceled due to ownership request from {}.", port, requester); } }
Source:
private ChannelHandlerContext findCtx() throws ClosedChannelException { ChannelHandlerContext ctx = this.multiplexCtx; if (ctx != null && !ctx.isRemoved()) { return ctx; } ctx = channel.pipeline().context(Http2MultiplexCodec.class); if (ctx == null) { ctx = channel.pipeline().context(Http2MultiplexHandler.class); } if (ctx == null) { if (channel.isActive()) { throw new IllegalStateException(StringUtil.simpleClassName(Http2MultiplexCodec.class) + " must be in the ChannelPipeline of Channel " + channel); } else { throw new ClosedChannelException(); } } this.multiplexCtx = ctx; return ctx; }

Target:
private ChannelHandlerContext findCtx() throws ClosedChannelException { ChannelHandlerContext ctx = this.multiplexCtx; if (ctx != null && !ctx.isRemoved()) { return ctx; } ChannelPipeline pipeline = channel.pipeline(); ctx = pipeline.context(Http2MultiplexCodec.class); if (ctx == null) { ctx = pipeline.context(Http2MultiplexHandler.class); } if (ctx == null) { if (channel.isActive()) { throw new IllegalStateException(StringUtil.simpleClassName(Http2MultiplexCodec.class) + " or " + StringUtil.simpleClassName(Http2MultiplexHandler.class) + " must be in the ChannelPipeline of Channel " + channel); } else { throw new ClosedChannelException(); } } this.multiplexCtx = ctx; return ctx; }
Source:
private static byte[] serializeContent(Content content) throws CacheDatabaseException { try { String type = content.getType(); switch (type) { case "text": return serializeTextContent((TextContent) content); case "image": return serializeImageContent((ImageContent) content); default: throw new ContentException("No such content exists !"); } } catch (CacheDatabaseException exception) { Log.d(TAG, "Could not serialize content !", exception); throw new CacheDatabaseException("Could not serialize Content !"); } }

Target:
private static byte[] serializeContent(Content content) throws CacheDatabaseException { Objects.requireNonNull(content); try { String type = content.getType(); switch (type) { case "text": return serializeTextContent((TextContent) content); case "image": return serializeImageContent((ImageContent) content); default: throw new ContentException("No such content exists !"); } } catch (CacheDatabaseException exception) { Log.d(TAG, "Could not serialize content !", exception); throw exception; } }
Source:
public boolean isHygrometerNotifying() { TiSensorTagGattResources resource = this.gattResources.get(HUMIDITY); if (resource != null) { return resource.getGattValueCharacteristic().isNotifying(); } else { return false; } }

Target:
public boolean isHygrometerNotifying() { return isNotifying(HUMIDITY); }
Source:
public void onMetadataChanged(@NonNull MediaItem item) { final MediaSessionImplBase session = getSession(); if (session == null) { return; } SessionPlayer player = session.getPlayer(); if (player.getCurrentMediaItem() == item) { if (!updateCurrentMediaItemMetadataWithDuration(player)) { notifyCurrentMediaItemChanged(item); } } }

Target:
public void onMetadataChanged(@NonNull MediaItem item) { final MediaSessionImplBase session = getSession(); if (session == null) { return; } SessionPlayer player = session.getPlayer(); if (player.getCurrentMediaItem() == item) { boolean notified = updateCurrentMediaItemMetadataWithDuration(player); if (!notified) { notifyCurrentMediaItemChanged(item); } } }
Source:
public int visit(IASTExpression expr) { if (!shouldReportInMacro() && enclosedInMacroExpansion(expr)) return PROCESS_SKIP; if (expr instanceof IASTFunctionCallExpression) { IASTFunctionCallExpression func = (IASTFunctionCallExpression) expr; IASTExpression functionNameExpression = func.getFunctionNameExpression(); IASTNode parent = func.getParent(); if (!(func.getParent() instanceof IASTExpressionStatement) && func.getPropertyInParent() != IASTExpressionList.NESTED_EXPRESSION) { while (parent instanceof IASTUnaryExpression) { int operator = ((IASTUnaryExpression) parent).getOperator(); if (operator != IASTUnaryExpression.op_bracketedPrimary) { return PROCESS_CONTINUE; } parent = parent.getParent(); } if (!(parent instanceof IASTExpressionStatement)) { return PROCESS_CONTINUE; } } IASTName name; if (functionNameExpression instanceof IASTIdExpression) { name = ((IASTIdExpression) functionNameExpression).getName(); } else if (functionNameExpression instanceof IASTFieldReference) { name = ((IASTFieldReference) functionNameExpression).getFieldName(); } else { return PROCESS_CONTINUE; } IBinding binding = name.resolveBinding(); if (checkNestedRightSide(func, binding, name)) { return PROCESS_CONTINUE; } if (binding instanceof IFunction && ((IFunction) binding).isNoDiscard()) { reportProblem(ER_ID, expr, name); } else if (binding instanceof ICPPClassType && expr instanceof ICPPASTExpression && checkEvaluation((ICPPASTExpression) expr)) { reportProblem(ER_ID, expr, name); } return PROCESS_CONTINUE; } else if (expr instanceof ICPPASTCastExpression) { ICPPASTCastExpression cast = (ICPPASTCastExpression) expr; if (cast.getOperator() != ICPPASTCastExpression.op_static_cast) { return PROCESS_CONTINUE; } if (checkEvaluation(cast)) { reportProblem(ER_ID, expr, cast.getTypeId()); } } return PROCESS_CONTINUE; }

Target:
public int visit(IASTExpression expr) { if (!shouldReportInMacro() && enclosedInMacroExpansion(expr)) return PROCESS_SKIP; if (isDiscardedValueExpression(expr) && isCallToNodiscardFunction(expr, res)) { reportProblem(ER_ID, expr, res[0]); res[0] = null; } return PROCESS_CONTINUE; }
Source:
private ScheduledQueryMaintenanceRequestType translateAstType(int type) throws SemanticException { switch (type) { case HiveParser.TOK_CREATE_SCHEDULED_QUERY: return ScheduledQueryMaintenanceRequestType.INSERT; case HiveParser.TOK_ALTER_SCHEDULED_QUERY: return ScheduledQueryMaintenanceRequestType.UPDATE; case HiveParser.TOK_DROP_SCHEDULED_QUERY: return ScheduledQueryMaintenanceRequestType.DELETE; default: throw new SemanticException("Can't handle: " + type); } }

Target:
private ScheduledQueryMaintenanceRequestType translateAstType(int type) throws SemanticException { switch (type) { case HiveParser.TOK_CREATE_SCHEDULED_QUERY: return ScheduledQueryMaintenanceRequestType.CREATE; case HiveParser.TOK_ALTER_SCHEDULED_QUERY: return ScheduledQueryMaintenanceRequestType.ALTER; case HiveParser.TOK_DROP_SCHEDULED_QUERY: return ScheduledQueryMaintenanceRequestType.DROP; default: throw new SemanticException("Can't handle: " + type); } }
Source:
public void execute(JobExecutionContext context) throws JobExecutionException { String methodName = null; try { JobDataMap data = context.getJobDetail().getJobDataMap(); Map paramsMap = data.getWrappedMap(); methodName = (String) paramsMap.get(SchedulerUtilBaseImpl.RUN_METHOD_NAME); final Object instance = getInstanceToRun(paramsMap); final Object[] methodParams = (Object[]) paramsMap.get(SchedulerUtilBaseImpl.RUN_METHOD_PARAM); String methodKey = getMethodKey(instance.getClass().getName(), methodName); final Method methodToRun; if (!cachedMethods.containsKey(methodKey)) { synchronized (JobWrapper.class) { if (cachedMethods.containsKey(methodKey)) { methodToRun = cachedMethods.get(methodKey); } else { methodToRun = getMethodToRun(instance, methodName); if (methodToRun == null) { log.error("could not find the required method '{}' on instance of {}", methodName, instance.getClass().getSimpleName()); return; } cachedMethods.put(methodKey, methodToRun); } } } else { methodToRun = cachedMethods.get(methodKey); } OnTimerMethodAnnotation annotation = methodToRun.getAnnotation(OnTimerMethodAnnotation.class); if (annotation.transactional()) { Exception e = TransactionSupport.executeInNewTransaction(new TransactionMethod<Exception>() { @Override public Exception runInTransaction() { try { methodToRun.invoke(instance, methodParams); } catch (Exception e) { return e; } return null; } }); if (e != null) { throw e; } } else { methodToRun.invoke(instance, methodParams); } } catch (Exception e) { log.error("Failed to invoke scheduled method {}: {}", methodName, e.getMessage()); log.debug("Exception", e); JobExecutionException jee = new JobExecutionException("failed to execute job"); jee.setStackTrace(e.getStackTrace()); throw jee; } }

Target:
public void execute(JobExecutionContext context) throws JobExecutionException { String methodName = null; try { JobDataMap data = context.getJobDetail().getJobDataMap(); Map paramsMap = data.getWrappedMap(); methodName = (String) paramsMap.get(SchedulerUtilBaseImpl.RUN_METHOD_NAME); final Object instance = getInstanceToRun(paramsMap); final Object[] methodParams = (Object[]) paramsMap.get(SchedulerUtilBaseImpl.RUN_METHOD_PARAM); String methodKey = getMethodKey(instance.getClass().getName(), methodName); final Method methodToRun; if (!cachedMethods.containsKey(methodKey)) { cachedMethods.putIfAbsent(methodKey, getMethodToRun(instance, methodName)); } methodToRun = cachedMethods.get(methodKey); invokeMethod(instance, methodToRun, methodParams); } catch (Exception e) { log.error("Failed to invoke scheduled method {}: {}", methodName, e.getMessage()); log.debug("Exception", e); JobExecutionException jee = new JobExecutionException("failed to execute job"); jee.setStackTrace(e.getStackTrace()); throw jee; } }
Source:
public void process(JSONRequestContext requestContext) { StudentGroupContactLogEntryCommentDAO entryCommentDAO = DAOFactory.getInstance().getStudentGroupContactLogEntryCommentDAO(); Long commentId = requestContext.getLong("commentId"); StudentGroupContactLogEntryComment comment = entryCommentDAO.findById(commentId); entryCommentDAO.archive(comment); }

Target:
public void process(JSONRequestContext requestContext) { StudentGroupContactLogEntryCommentDAO entryCommentDAO = DAOFactory.getInstance().getStudentGroupContactLogEntryCommentDAO(); Long commentId = requestContext.getLong("commentId"); if (commentId == null) throw new SmvcRuntimeException(StatusCode.UNDEFINED, "CommentId was not defined."); StudentGroupContactLogEntryComment comment = entryCommentDAO.findById(commentId); entryCommentDAO.archive(comment); }
Source:
public DataSet<ExecRow> write() throws StandardException{ long start = System.currentTimeMillis(); CountFunction countFunction = new CountFunction<>(); KafkaStreamer kafkaStreamer = new KafkaStreamer(rdd.getNumPartitions(), topicName, schema); JavaRDD streamed = rdd.map(countFunction).mapPartitionsWithIndex(kafkaStreamer, true); streamed.collect(); Long count = countFunction.getCount().value(); if(count == 0) { try { kafkaStreamer.noData(); } catch(Exception e) { throw StandardException.newException("", e); } } long end = System.currentTimeMillis(); ValueRow valueRow=new ValueRow(2); valueRow.setColumn(1,new SQLLongint(count)); valueRow.setColumn(2,new SQLLongint(end-start)); return new SparkDataSet<>(SpliceSpark.getContext().parallelize(Collections.singletonList(valueRow), 1)); }

Target:
public DataSet<ExecRow> write() throws StandardException{ long start = System.currentTimeMillis(); CountFunction countFunction = new CountFunction<>(); KafkaStreamer kafkaStreamer = new KafkaStreamer(rdd.getNumPartitions(), topicName); JavaRDD streamed = rdd.map(countFunction).mapPartitionsWithIndex(kafkaStreamer, true); streamed.collect(); Long count = countFunction.getCount().value(); if(count == 0) { try { kafkaStreamer.noData(); } catch(Exception e) { throw StandardException.newException("", e); } } long end = System.currentTimeMillis(); ValueRow valueRow=new ValueRow(2); valueRow.setColumn(1,new SQLLongint(count)); valueRow.setColumn(2,new SQLLongint(end-start)); return new SparkDataSet<>(SpliceSpark.getContext().parallelize(Collections.singletonList(valueRow), 1)); }
Source:
public LightblueBulkDataResponse getBulkResponse() { return bulkResponse; }

Target:
public LightblueBulkDataErrorResponse getBulkResponse() { return bulkResponse; }
Source:
private LongSupplier committingIdSupplier() throws IOException { if ( transactionIdStore != null ) { return () -> transactionIdStore.committingTransactionId(); } if ( fileBasedOperationsOnly ) { return () -> { throw new UnsupportedOperationException( "Current version of log files can't perform any " + "operation that require availability of transaction id store. Please build full version of log files " + "to be able to use them." ); }; } if ( readOnly ) { requireNonNull( pageCache, "Read only log files require page cache to be able to read commited " + "transaction info from store store." ); requireNonNull( storeDirectory, "Store directory is required." ); ReadOnlyTransactionIdStore transactionIdStore = new ReadOnlyTransactionIdStore( pageCache, storeDirectory ); return transactionIdStore::committingTransactionId; } else { requireNonNull( dependencies, TransactionIdStore.class.getSimpleName() + " is required. " + "Please provide an instance or a dependencies where it can be found." ); return () -> resolveDependency( TransactionIdStore.class ).committingTransactionId(); } }

Target:
private LongSupplier committingIdSupplier() throws IOException { if ( transactionIdStore != null ) { return transactionIdStore::committingTransactionId; } if ( fileBasedOperationsOnly ) { return () -> { throw new UnsupportedOperationException( "Current version of log files can't perform any " + "operation that require availability of transaction id store. Please build full version of log files " + "to be able to use them." ); }; } if ( readOnly ) { requireNonNull( pageCache, "Read only log files require page cache to be able to read commited " + "transaction info from store store." ); requireNonNull( storeDirectory, "Store directory is required." ); ReadOnlyTransactionIdStore transactionIdStore = new ReadOnlyTransactionIdStore( pageCache, storeDirectory ); return transactionIdStore::committingTransactionId; } else { requireNonNull( dependencies, TransactionIdStore.class.getSimpleName() + " is required. " + "Please provide an instance or a dependencies where it can be found." ); return () -> resolveDependency( TransactionIdStore.class ).committingTransactionId(); } }
Source:
public void visit(NodeTraversal t, Node n, Node parent) { switch (n.getToken()) { case FUNCTION: JSDocInfo bestJSDocInfo = NodeUtil.getBestJSDocInfo(n); if (bestJSDocInfo != null && (bestJSDocInfo.isConstructor() || bestJSDocInfo.isInterface())) { convertConstructorToClass(n, bestJSDocInfo); } break; case CALL: if ("goog.defineClass".equals(n.getFirstChild().getQualifiedName())) { convertDefineClassToClass(n); } break; case GETPROP: case NAME: case VAR: case LET: case CONST: boolean needToExport = false; JSDocInfo jsdoc = NodeUtil.getBestJSDocInfo(n); if (jsdoc != null && jsdoc.hasTypedefType()) { String name; if (n.getToken() == Token.NAME) { name = n.getString(); } else if (n.getToken() == Token.GETPROP) { needToExport = true; name = n.getSecondChild().getString(); } else { name = n.getFirstChild().getString(); } Node typeDef = Node.newString(Token.TYPE_ALIAS, name); types.put(name, typeDef); typeDef.setJSDocInfo(jsdoc); if (needToExport) { typesToRename.put( n.getFirstChild().getString() + "." + n.getSecondChild().getString(), name); typeDef = new Node(Token.EXPORT, typeDef); } if (parent.getToken() == Token.EXPR_RESULT) { parent.getParent().replaceChild(parent, typeDef); } else if (parent.getToken() == Token.ASSIGN) { parent.getGrandparent().replaceChild(parent.getParent(), typeDef); } else { parent.replaceChild(n, typeDef); } } break; default: break; } }

Target:
public void visit(NodeTraversal t, Node n, Node parent) { JSDocInfo bestJSDocInfo = null; switch (n.getToken()) { case FUNCTION: bestJSDocInfo = NodeUtil.getBestJSDocInfo(n); if (bestJSDocInfo != null && (bestJSDocInfo.isConstructor() || bestJSDocInfo.isInterface())) { convertConstructorToClass(n, bestJSDocInfo); } break; case CALL: if ("goog.defineClass".equals(n.getFirstChild().getQualifiedName())) { convertDefineClassToClass(n); } break; case GETPROP: bestJSDocInfo = NodeUtil.getBestJSDocInfo(n); if (bestJSDocInfo != null && bestJSDocInfo.hasTypedefType()) { String interfaceName = n.getSecondChild().getString(); Node interfaceMember = Node.newString(Token.INTERFACE_MEMBERS, interfaceName); typesToRename.put(n.getQualifiedName(), interfaceName); types.put(interfaceName, interfaceMember); interfaceMember.setJSDocInfo(bestJSDocInfo); Node interfaceNode = new Node(Token.INTERFACE, IR.empty(), IR.empty(), interfaceMember); Node nameNode = Node.newString(Token.NAME, interfaceName); nameNode.addChildToBack(interfaceNode); Node exportNode = new Node(Token.EXPORT, new Node(Token.CONST, nameNode)); replaceExpressionOrAssignment(n, parent, exportNode); } break; case NAME: case VAR: case LET: case CONST: bestJSDocInfo = NodeUtil.getBestJSDocInfo(n); if (bestJSDocInfo != null && bestJSDocInfo.hasTypedefType()) { String name; if (n.getToken() == Token.NAME) { name = n.getString(); } else { name = n.getFirstChild().getString(); } Node typeDef = Node.newString(Token.TYPE_ALIAS, name); types.put(name, typeDef); typeDef.setJSDocInfo(bestJSDocInfo); replaceExpressionOrAssignment(n, parent, typeDef); } break; default: break; } }
Source:
private void markAllBelowAsRead() { if (listView.getSelectedIndex() >= 0) { for (int i = listView.getSelectedIndex(); i < listView.getItems().size(); i++) { TurboIssue issue = listView.getItems().get(i).getIssue(); issue.markAsRead(UI.prefs); } parentPanelControl.refresh(); } }

Target:
private void markAllBelowAsRead() { Optional<GuiElement> item = listView.getSelectedItem(); if (item.isPresent()) { for(int i = listView.getSelectedIndex(); i < listView.getItems().size(); i++){ TurboIssue issue = listView.getItems().get(i).getIssue(); issue.markAsRead(UI.prefs); } parentPanelControl.refresh(); } }
Source:
private static void parse( String filename, InputStream inputStream, AnnotatedTypeFactory atypeFactory, ProcessingEnvironment processingEnv, StubAnnotations stubAnnos, boolean isJdkAsStub) { AnnotationFileParser sp = new AnnotationFileParser(filename, atypeFactory, processingEnv, isJdkAsStub); try { sp.parseStubUnit(inputStream); sp.process(stubAnnos); } catch (ParseProblemException e) { StringJoiner message = new StringJoiner(LINE_SEPARATOR); message.add( e.getProblems().size() + " problems while parsing stub file " + filename + ":"); for (Problem p : e.getProblems()) { message.add(p.getVerboseMessage()); } sp.warn(message.toString()); } }

Target:
private static void parse( String filename, InputStream inputStream, AnnotatedTypeFactory atypeFactory, ProcessingEnvironment processingEnv, StubAnnotations stubAnnos, boolean isJdkAsStub) { AnnotationFileParser afp = new AnnotationFileParser(filename, atypeFactory, processingEnv, isJdkAsStub); try { afp.parseStubUnit(inputStream); afp.process(stubAnnos); } catch (ParseProblemException e) { StringJoiner message = new StringJoiner(LINE_SEPARATOR); message.add( e.getProblems().size() + " problems while parsing stub file " + filename + ":"); for (Problem p : e.getProblems()) { message.add(p.getVerboseMessage()); } afp.warn(message.toString()); } }
Source:
public static String getUniqueHostName(VDS host) { return host.getHostName() + "-" + new String(DigestUtils.md5Hex(host.getId().toByteArray())).substring(0, 6); }

Target:
public static String getUniqueHostName(VDS host) { return host.getHostName() + "-" + DigestUtils.md5Hex(host.getId().toByteArray()).substring(0, 6); }
Source:
private void checkRange(CubeMap cubeMap, int lowerBound, int upperBound) { Set<Cube> range = new HashSet<>(); cubeMap.cubes(lowerBound, upperBound).forEach(cube -> { assertFalse(range.contains(cube)); range.add(cube); }); cubeMap.all().forEach(cube -> { if (cube.getY() >= lowerBound && cube.getY() <= upperBound) { assertTrue(range.contains(cube)); } else { assertFalse(range.contains(cube)); } }); int alwaysLower = Integer.MIN_VALUE; for(Cube cube : cubeMap.cubes(lowerBound, upperBound)) { assertThat(cube.getY(), is(greaterThan(alwaysLower))); alwaysLower = cube.getY(); } }

Target:
private void checkRange(CubeMap cubeMap, int lowerBound, int upperBound) { Iterable<Cube> range = cubeMap.cubes(lowerBound, upperBound); Set<Cube> rangeSet = new HashSet<>(); range.forEach(cube -> { rangeSet.add(cube); }); assertThat(range, hasDistinctElements()); cubeMap.all().forEach(cube -> { if (cube.getY() >= lowerBound && cube.getY() <= upperBound) { assertThat(rangeSet, hasItem(cube)); } else { assertThat(rangeSet, not(hasItem(cube))); } }); int alwaysLower = Integer.MIN_VALUE; for(Cube cube : range) { assertThat(cube.getY(), is(greaterThan(alwaysLower))); alwaysLower = cube.getY(); } }
Source:
public int readdirCallback(String path, long bufaddr, FuseFillDir filter, long offset, ByteBuffer fi) { try { return readdir(path, bufaddr, filter, offset, new FuseFileInfo(fi)); } catch (Exception e) { e.printStackTrace(); return -ErrorCodes.EIO(); } }

Target:
public int readdirCallback(String path, long bufaddr, FuseFillDir filter, long offset, ByteBuffer fi) { try { return readdir(path, bufaddr, filter, offset, new FuseFileInfo(fi)); } catch (Exception e) { LOG.error("Failed to readdir {}, offset {}: ", path, offset, e); return -ErrorCodes.EIO(); } }
Source:
public void moveDown(){ setY(getY() + 2.2); setX(getX() - 0.7); }

Target:
public void moveDown(){ setY(getY() + downspeed); setX(getX() - 0.7); }
Source:
public void shouldCreateAPaymentRequest() throws Exception { GatewayAccountEntity gatewayAccount = new GatewayAccountEntity( defaultTestAccount.getPaymentProvider(), new HashMap<>(), TEST); gatewayAccount.setId(defaultTestAccount.getAccountId()); PaymentRequestEntity paymentRequestEntity = aValidPaymentRequestEntity() .withId(null) .withGatewayAccountEntity(gatewayAccount) .build(); assertThat(paymentRequestEntity.getId(), is(nullValue())); paymentRequestDao.persist(paymentRequestEntity); assertThat(paymentRequestEntity.getId(), is(notNullValue())); assertThat(paymentRequestEntity.getCreatedDate().getNano() % 1000000, is(0)); }

Target:
public void shouldCreateAPaymentRequest() throws Exception { GatewayAccountEntity gatewayAccount = new GatewayAccountEntity( defaultTestAccount.getPaymentProvider(), new HashMap<>(), TEST); gatewayAccount.setId(defaultTestAccount.getAccountId()); PaymentRequestEntity paymentRequestEntity = aValidPaymentRequestEntity() .withGatewayAccountEntity(gatewayAccount) .build(); paymentRequestDao.persist(paymentRequestEntity); assertThat(paymentRequestEntity.getId(), is(notNullValue())); assertThat(paymentRequestEntity.getCreatedDate().getNano() % 1000000, is(0)); }
Source:
private void initButtonsPart() { yesNoButtons = new HLayout(); yesNoButtons.setMargin(10); yesNoButtons.setMembersMargin(5); yesNoButtons.setHeight(30); yesNoButtons.setWidth100(); yesNoButtons.setAlign(Alignment.RIGHT); yesButton = new IButton("Yes"); yesButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { String url = "/automation-dashboard/#/portal/job-planner-calendar-def-workflows"; com.google.gwt.user.client.Window.open(url, url, ""); PlanWindow.this.window.hide(); PlanWindow.this.destroy(); } }); noButton = new IButton("No"); noButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { PlanWindow.this.window.hide(); PlanWindow.this.destroy(); } }); yesNoButtons.setMembers(yesButton, noButton); rootPage.addMember(yesNoButtons); }

Target:
private void initButtonsPart() { yesNoButtons = new HLayout(); yesNoButtons.setMargin(10); yesNoButtons.setMembersMargin(5); yesNoButtons.setHeight(30); yesNoButtons.setWidth100(); yesNoButtons.setAlign(Alignment.RIGHT); yesButton = new IButton("Yes"); yesButton.addClickHandler(clickEvent -> { com.google.gwt.user.client.Window.open(JPP_URL, JPP_URL, ""); PlanWindow.this.window.hide(); PlanWindow.this.destroy(); }); noButton = new IButton("No"); noButton.addClickHandler(clickEvent -> { PlanWindow.this.window.hide(); PlanWindow.this.destroy(); }); yesNoButtons.setMembers(yesButton, noButton); rootPage.addMember(yesNoButtons); }
Source:
public CommonProtos.Priority serialize(Priority source) { CommonProtos.Priority.Builder builder = CommonProtos.Priority.newBuilder(); if(source.getReasons() != null) { if (source.getReasons().getPositive() != null) { for (String reason : source.getReasons().getPositive()) { builder.addPositiveReasons(reason); } } if (source.getReasons().getNegative() != null) { for (String reason : source.getReasons().getNegative()) { builder.addNegativeReasons(reason); } } } if(source.getPriority() != null) { builder.setPriority(source.getPriority()); } return builder.build(); }

Target:
public CommonProtos.Priority serialize(Priority source) { CommonProtos.Priority.Builder builder = CommonProtos.Priority.newBuilder(); PriorityScoreReasons scoreReasons = source.getReasons(); if(scoreReasons != null) { if (scoreReasons.getPositive() != null) { for (String reason : scoreReasons.getPositive()) { builder.addPositiveReasons(reason); } } if (scoreReasons.getNegative() != null) { for (String reason : scoreReasons.getNegative()) { builder.addNegativeReasons(reason); } } } if(source.getPriority() != null) { builder.setPriority(source.getPriority()); } return builder.build(); }
Source:
static void addToWarsByContext(Entity entity, String url, String targetName) { targetName = filenameToWebContextMapper.convertDeploymentTargetNameToContext(targetName); synchronized (entity) { Map<String,String> newWarsMap = MutableMap.copyOf(entity.getConfig(WARS_BY_CONTEXT)); newWarsMap.put(targetName, url); ((EntityInternal)entity).setConfig(WARS_BY_CONTEXT, newWarsMap); } }

Target:
static void addToWarsByContext(Entity entity, String url, String targetName) { targetName = FILENAME_TO_WEB_CONTEXT_MAPPER.convertDeploymentTargetNameToContext(targetName); synchronized (entity) { Map<String,String> newWarsMap = MutableMap.copyOf(entity.getConfig(WARS_BY_CONTEXT)); newWarsMap.put(targetName, url); ((EntityInternal)entity).setConfig(WARS_BY_CONTEXT, newWarsMap); } }
Source:
public void addHead(final MessageReference ref, boolean scheduling) { enterCritical(CRITICAL_PATH_ADD_HEAD); synchronized (this) { try { enforceRing(ref, scheduling); if (!ref.isAlreadyAcked()) { if (!scheduling && scheduledDeliveryHandler.checkAndSchedule(ref, false)) { return; } internalAddHead(ref); directDeliver = false; } } finally { leaveCritical(CRITICAL_PATH_ADD_HEAD); } } }

Target:
public void addHead(final MessageReference ref, boolean scheduling) { enterCritical(CRITICAL_PATH_ADD_HEAD); synchronized (this) { try { if (ringSize != -1) { enforceRing(ref, scheduling); } if (!ref.isAlreadyAcked()) { if (!scheduling && scheduledDeliveryHandler.checkAndSchedule(ref, false)) { return; } internalAddHead(ref); directDeliver = false; } } finally { leaveCritical(CRITICAL_PATH_ADD_HEAD); } } }
Source:
protected void doStart() { Assert.state(this.outputChannel != null || StringUtils.hasText(this.outputChannelName), "'outputChannel' or 'outputChannelName' is required"); if (this.outputChannelName != null) { synchronized (this) { if (this.outputChannelName != null) { this.outputChannel = getChannelResolver().resolveDestination(this.outputChannelName); this.outputChannelName = null; } } } }

Target:
protected void doStart() { Assert.state(this.outputChannel != null || StringUtils.hasText(this.outputChannelName), "'outputChannel' or 'outputChannelName' is required"); if (this.outputChannelName != null) { this.outputChannel = getChannelResolver().resolveDestination(this.outputChannelName); } }
Source:
public boolean tryLock(String... names) throws InterruptedException { return tryLock(jgroupsLockingService.getLockTimeoutMillis(), TimeUnit.MILLISECONDS, names); }

Target:
public boolean tryLock(String... names) throws InterruptedException { return tryLock(lockTimeoutMillis, TimeUnit.MILLISECONDS, names); }
Source:
public ChannelOutput receive() throws IOException { ByteBuf responseByteBuf; try { responseByteBuf = responsePromise.get(http2ClientConfig.http2BlockingChannelReceiveTimeoutMs, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new IOException("Failed to receive response from " + getRemoteHost() + ":" + getRemotePort(), e); } DataInputStream dataInputStream = new NettyByteBufDataInputStream(responseByteBuf); return new ChannelOutput(dataInputStream, dataInputStream.readLong() - 8); }

Target:
public ChannelOutput receive() throws IOException { logger.error("Http2 doesn't support send() receive(). Please use sendAndReceive()"); throw new UnsupportedOperationException(); }
Source:
private void markAsDeleted(StoreKey id, FileSpan fileSpan, MessageInfo info) throws StoreException { validateFileSpan(fileSpan, true); IndexValue value = findKey(id); if (value == null && info == null) { throw new StoreException("Id " + id + " not present in index " + dataDir, StoreErrorCodes.ID_Not_Found); } else if (value != null && value.isFlagSet(IndexValue.Flags.Delete_Index)) { throw new StoreException("Id " + id + " already deleted in index " + dataDir, StoreErrorCodes.ID_Deleted); } long size = fileSpan.getEndOffset().getOffset() - fileSpan.getStartOffset().getOffset(); IndexValue newValue; if (value == null) { newValue = new IndexValue(size, fileSpan.getStartOffset(), info.getExpirationTimeInMs(), Utils.Infinite_Time, IndexValue.SERVICE_CONTAINER_ID_DEFAULT_VALUE, IndexValue.SERVICE_CONTAINER_ID_DEFAULT_VALUE); newValue.clearOriginalMessageOffset(); } else { newValue = new IndexValue(value.getSize(), value.getOffset(), value.getExpiresAtMs(), Utils.Infinite_Time, value.getServiceId(), value.getContainerId()); newValue.setNewOffset(fileSpan.getStartOffset()); newValue.setNewSize(size); } newValue.setFlag(IndexValue.Flags.Delete_Index); addToIndex(new IndexEntry(id, newValue, null), fileSpan); }

Target:
private void markAsDeleted(StoreKey id, FileSpan fileSpan, MessageInfo info) throws StoreException { validateFileSpan(fileSpan, true); IndexValue value = findKey(id); if (value == null && info == null) { throw new StoreException("Id " + id + " not present in index " + dataDir, StoreErrorCodes.ID_Not_Found); } else if (value != null && value.isFlagSet(IndexValue.Flags.Delete_Index)) { throw new StoreException("Id " + id + " already deleted in index " + dataDir, StoreErrorCodes.ID_Deleted); } long size = fileSpan.getEndOffset().getOffset() - fileSpan.getStartOffset().getOffset(); IndexValue newValue; if (value == null) { newValue = new IndexValue(size, fileSpan.getStartOffset(), info.getExpirationTimeInMs()); newValue.clearOriginalMessageOffset(); } else { newValue = new IndexValue(value.getSize(), value.getOffset(), value.getExpiresAtMs(), Utils.Infinite_Time, value.getServiceId(), value.getContainerId()); newValue.setNewOffset(fileSpan.getStartOffset()); newValue.setNewSize(size); } newValue.setFlag(IndexValue.Flags.Delete_Index); addToIndex(new IndexEntry(id, newValue, null), fileSpan); }
Source:
protected void runQuery(String key, QueryResultCallback callback) throws DashboardDataException { if (!sqlQueries.containsKey(key)) { throw new DashboardDataException("SQL query not found: " + key); } try (Connection con = dataSource.getConnection(); PreparedStatement ps = con.prepareStatement(sqlQueries.getProperty(key)); ResultSet rs = ps.executeQuery()) { callback.onResult(rs); } catch (SQLException e) { throw new DashboardDataException("Error while running SQL query", e); } }

Target:
protected void runQuery(String key, QueryResultCallback callback) throws DashboardDataException { if (!sqlQueries.containsKey(key)) { throw new DashboardDataException("SQL query not found: " + key); } try (Connection con = dataSource.getConnection(); PreparedStatement ps = con.prepareStatement(sqlQueries.getProperty(key)); ResultSet rs = ps.executeQuery()) { while (rs.next()) { callback.onResult(rs); } } catch (SQLException e) { throw new DashboardDataException("Error while running SQL query", e); } }
Source:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String contentType = request.getParameter("contenttype"); String fileName = request.getParameter("filename"); Boolean cache = Boolean.parseBoolean(request.getParameter("cache")); String encodingType = request.getParameter("encodingtype"); String content = request.getParameter("content"); if (contentType != null) { response.setContentType(contentType); } if (fileName == null) { fileName = "attachment"; } response.setHeader("Content-Disposition", "attachment; filename*='UTF-8'" + URLEncoder.encode(StringEscapeUtils.unescapeHtml(fileName), "UTF-8")); if (!cache) { response.setHeader("Cache-Control", "max-age=0, must-revalidate"); response.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); } if (content == null) { return; } if ("binary".equals(encodingType)) { response.getOutputStream().write(Base64.decodeBase64(content)); } else if ("plain".equals(encodingType)) { content = StringEscapeUtils.unescapeHtml(content); response.getWriter().write(content); if (response.getWriter().checkError()) { throw new IOException("Error when writing to response stream"); } } else { throw new ServletException(String.format("Unsupported encoding type %s", encodingType)); } }

Target:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String contentType = request.getParameter("contenttype"); Boolean cache = Boolean.parseBoolean(request.getParameter("cache")); String encodingType = request.getParameter("encodingtype"); String content = request.getParameter("content"); if (StringUtils.isNotBlank(contentType)) { response.setContentType(contentType); } if (!cache) { response.setHeader("Cache-Control", "max-age=0, must-revalidate"); response.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); } if (content == null) { return; } if (ENCODINGTYPE_BINARY.equals(encodingType)) { response.getOutputStream().write(Base64.decodeBase64(content)); } else if (ENCODINGTYPE_PLAIN.equals(encodingType)) { content = StringEscapeUtils.unescapeHtml(content); response.getWriter().write(content); if (response.getWriter().checkError()) { throw new IOException("Error when writing to response stream"); } } else { throw new ServletException(String.format("Unsupported encoding type %s", encodingType)); } }