auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public GroupResource parse(TopLevelResource parent, IdString id) throws AuthException, ResourceNotFoundException { final CurrentUser user = self.get(); if (user instanceof AnonymousUser) { throw new AuthException("Authentication required"); } else if(!(user.isIdentifiedUser())) { throw new ResourceNotFoundException(id); } GroupDescription.Basic group = parseId(id.get()); if (group == null) { throw new ResourceNotFoundException(id.get()); } GroupControl ctl = groupControlFactory.controlFor(group); if (group.getClass().getEnclosingClass().equals(LdapGroupBackend.class)) { if (!ctl.isVisible(groupBackend)) { throw new ResourceNotFoundException(id); } } else { if (!ctl.isVisible()) { throw new ResourceNotFoundException(id); } } return new GroupResource(ctl); }

Target:
public GroupResource parse(TopLevelResource parent, IdString id) throws AuthException, ResourceNotFoundException { final CurrentUser user = self.get(); if (user instanceof AnonymousUser) { throw new AuthException("Authentication required"); } else if(!(user.isIdentifiedUser())) { throw new ResourceNotFoundException(id); } GroupDescription.Basic group = parseId(id.get()); if (group == null) { throw new ResourceNotFoundException(id.get()); } GroupControl ctl = groupControlFactory.controlFor(group); if (!ctl.isVisible()) { throw new ResourceNotFoundException(id); } return new GroupResource(ctl); }
Source:
private static void validateDescriptionSection(String fileName, String sectionName, Node subSection) { if ("config_filters.xml".equals(fileName) && "SuppressionXpathFilter".equals(sectionName)) { validateSuppressionXpathFilterIncompatibleChecksList(subSection); } }

Target:
private static void validateDescriptionSection(String fileName, String sectionName, Node subSection) { if ("config_filters.xml".equals(fileName) && "SuppressionXpathFilter".equals(sectionName)) { validateListOfSuppressionXpathFilterIncompatibleChecks(subSection); } }
Source:
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException { boolean tableOptPassed = cl.hasOption(OptUtil.tableOpt().getOpt()); final String tableName; if (tableOptPassed) { tableName = OptUtil.getTableOpt(cl, shellState); } else { tableName = shellState.getTableName(); shellState.checkTableState(); } String dir = cl.getArgs()[0]; String failureDir = cl.getArgs()[1]; final boolean setTime = Boolean.parseBoolean(cl.getArgs()[2]); shellState.getConnector().tableOperations().importDirectory(tableName, dir, failureDir, setTime); return 0; }

Target:
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException { final String tableName = OptUtil.getTableOpt(cl, shellState); String dir = cl.getArgs()[0]; String failureDir = cl.getArgs()[1]; final boolean setTime = Boolean.parseBoolean(cl.getArgs()[2]); shellState.getConnector().tableOperations().importDirectory(tableName, dir, failureDir, setTime); return 0; }
Source:
public void testStreamWithoutTotalReads() throws IOException, NoSuchFieldException, IllegalAccessException { final String tmpDir = IOUtil.getDefaultTmpDir().getAbsolutePath(); final String[] args = new String[]{ "INPUT=/dev/stdin", "SPLIT_TO_N_READS=5", "OUTPUT=" + tmpDir }; final int rc = runPicardCommandLine(args); Assert.assertEquals(rc, 1); }

Target:
public void testStreamWithoutTotalReads() throws IOException { final String tmpDir = IOUtil.getDefaultTmpDir().getAbsolutePath(); final String[] args = new String[]{ "INPUT=/dev/stdin", "SPLIT_TO_N_READS=5", "OUTPUT=" + tmpDir }; final int rc = runPicardCommandLine(args); Assert.assertEquals(rc, 1); }
Source:
protected static <SelfT extends AbstractCommitSessionValve<?>> void commitSession( final Request request) { final Context context = request.getContext(); final Manager manager = context.getManager(); if (manager instanceof DeltaSessionManager) { final DeltaSessionFacade session = (DeltaSessionFacade) request.getSession(false); if (session != null) { final DeltaSessionManager<SelfT> deltaSessionManager = uncheckedCast(manager); final Log contextLogger = context.getLogger(); if (session.isValid()) { deltaSessionManager.removeTouchedSession(session.getId()); session.commit(); if (contextLogger.isDebugEnabled()) { contextLogger.debug(session + ": Committed."); } } else { if (contextLogger.isDebugEnabled()) { contextLogger.debug(session + ": Not valid so not committing."); } } } } }

Target:
protected static <SelfT extends AbstractCommitSessionValve<?>> void commitSession( final Request request) { final Context context = request.getContext(); final Manager manager = context.getManager(); if (manager instanceof DeltaSessionManager) { final DeltaSessionFacade session = (DeltaSessionFacade) request.getSession(false); if (session != null) { final DeltaSessionManager<SelfT> deltaSessionManager = uncheckedCast(manager); if (session.isValid()) { deltaSessionManager.removeTouchedSession(session.getId()); session.commit(); if (log.isDebugEnabled()) { log.debug(session + ": Committed."); } } else { if (log.isDebugEnabled()) { log.debug(session + ": Not valid so not committing."); } } } } }
Source:
public TmfStateValue getValue() { return fValue; }

Target:
public @NonNull TmfStateValue getValue() { return fValue; }
Source:
public static BigDoorsDoorTag valueOf(String string, TagContext context) { if (string == null || string.length() == 0) { return null; } string = string.replace("bigdoor@", ""); try { long id = Long.parseLong(string); return new BigDoorsDoorTag(commander.getDoor(null, id)); } catch (NumberFormatException e) { Debug.echoError("Invalid door id specified."); } return null; }

Target:
public static BigDoorsDoorTag valueOf(String string, TagContext context) { if (string == null || string.length() == 0) { return null; } if (string.startsWith("bigdoors@")) { string = string.substring("bigdoor@".length()); } if (!ArgumentHelper.matchesInteger(string)) { return null; } return new BigDoorsDoorTag(BigDoorsBridge.commander.getDoor(null, Integer.parseInt(string))); }
Source:
private WebDriverWrapper getWebDriver() { WebDriverWrapper fxDriver; try { fxDriver = freeDrivers.pop(); } catch (Exception e) { fxDriver = new WebDriverWrapper(createWebDriver()); } synchronized (takenDrivers) { takenDrivers.add(fxDriver); } if (reaperThread == null) { synchronized (reaperThreadSync) { if (reaperThread == null) { reaperThread = new Thread( new Runnable() { @Override public void run() { log.info("Reaper thread starting"); reaperThread.setName("ZAP-DomXssReaper"); do { try { Thread.sleep(5000); } catch (InterruptedException e) { } Date now = new Date(); synchronized (takenDrivers) { Iterator<WebDriverWrapper> iter = takenDrivers.iterator(); while (iter.hasNext()) { WebDriverWrapper wrapper = iter.next(); if ((now.getTime() - wrapper.getLastAccessed() .getTime()) / 1000 > 10) { log.debug( "Driver hung " + wrapper.getDriver() .hashCode()); wrapper.getDriver().quit(); wrapper.setDriver(createWebDriver()); log.debug( "New driver " + wrapper.getDriver() .hashCode()); } } } } while (takenDrivers.size() > 0); log.info( "Reaper thread exiting " + takenDrivers.size()); reaperThread = null; } }); reaperThread.start(); } } } return fxDriver; }

Target:
private WebDriverWrapper getWebDriver() { WebDriverWrapper driver = null; try { driver = freeDrivers.get(browser).pop(); if (!driver.getBrowser().equals(browser)) { driver.getDriver().quit(); driver = null; } } catch (Exception e) { } if (driver == null) { driver = new WebDriverWrapper(createWebDriver(), browser); } synchronized (takenDrivers) { takenDrivers.add(driver); } if (reaperThread == null) { synchronized (reaperThreadSync) { if (reaperThread == null) { reaperThread = new Thread( new Runnable() { @Override public void run() { log.info("Reaper thread starting"); reaperThread.setName("ZAP-DomXssReaper"); do { try { Thread.sleep(5000); } catch (InterruptedException e) { } Date now = new Date(); synchronized (takenDrivers) { Iterator<WebDriverWrapper> iter = takenDrivers.iterator(); while (iter.hasNext()) { WebDriverWrapper wrapper = iter.next(); if ((now.getTime() - wrapper.getLastAccessed() .getTime()) / 1000 > 10) { log.debug( "Driver hung " + wrapper.getDriver() .hashCode()); wrapper.getDriver().quit(); wrapper.setDriver(createWebDriver()); log.debug( "New driver " + wrapper.getDriver() .hashCode()); } } } } while (takenDrivers.size() > 0); log.info( "Reaper thread exiting " + takenDrivers.size()); reaperThread = null; } }); reaperThread.start(); } } } return driver; }
Source:
public boolean targets(TechSet technologies) { return technologies.includes(Tech.Db); }

Target:
public boolean targets(TechSet technologies) { return technologies.includes(Tech.MongoDB); }
Source:
private Map<Cell, Value> extractResults( DbReadTable table, ClosableIterator<AgnosticLightResultRow> rows) { Map<Cell, Value> results = Maps.newHashMap(); Map<Cell, OverflowValue> overflowResults = Maps.newHashMap(); try (ClosableIterator<AgnosticLightResultRow> iter = rows) { boolean hasOverflow = table.hasOverflowValues(); while (iter.hasNext()) { AgnosticLightResultRow row = iter.next(); Cell cell = Cell.create(row.getBytes(ROW), row.getBytes(COL)); Long overflowId = hasOverflow ? row.getLongObject("overflow") : null; if (overflowId == null) { Value value = Value.create(row.getBytes("val"), row.getLong(TIMESTAMP)); Value oldValue = results.put(cell, value); if (oldValue != null && oldValue.getTimestamp() > value.getTimestamp()) { results.put(cell, oldValue); } } else { OverflowValue ov = ImmutableOverflowValue.of(row.getLong(TIMESTAMP), overflowId); OverflowValue oldOv = overflowResults.put(cell, ov); if (oldOv != null && oldOv.ts() > ov.ts()) { overflowResults.put(cell, oldOv); } } } } fillOverflowValues(table, overflowResults, results); return results; }

Target:
private Map<Cell, Value> extractResults( DbReadTable table, ClosableIterator<AgnosticLightResultRow> rows) { Map<Cell, Value> results = Maps.newHashMap(); Map<Cell, OverflowValue> overflowResults = Maps.newHashMap(); try (ClosableIterator<AgnosticLightResultRow> iter = rows) { boolean hasOverflow = table.hasOverflowValues(); while (iter.hasNext()) { AgnosticLightResultRow row = iter.next(); Cell cell = Cell.create(row.getBytes(ROW), row.getBytes(COL)); Long overflowId = hasOverflow ? row.getLongObject("overflow") : null; if (overflowId == null) { Value value = Value.create(row.getBytes(VAL), row.getLong(TIMESTAMP)); Value oldValue = results.put(cell, value); if (oldValue != null && oldValue.getTimestamp() > value.getTimestamp()) { results.put(cell, oldValue); } } else { OverflowValue ov = ImmutableOverflowValue.of(row.getLong(TIMESTAMP), overflowId); OverflowValue oldOv = overflowResults.put(cell, ov); if (oldOv != null && oldOv.ts() > ov.ts()) { overflowResults.put(cell, oldOv); } } } } fillOverflowValues(table, overflowResults, results); return results; }
Source:
public void setId(String id) throws FormatException, IOException { LOGGER.debug("{} initializing {}", this.getClass().getSimpleName(), id); if (currentId == null || !new Location(id).getAbsolutePath().equals( new Location(currentId).getAbsolutePath())) { initFile(id); MetadataStore store = getMetadataStore(); if (saveOriginalMetadata) { if (store instanceof OMEXMLMetadata) { setupService(); Hashtable<String, Object> allMetadata = new Hashtable<String, Object>(); allMetadata.putAll(metadata); for (int s=0; s < getSeriesCount(); s++) { String name = "Series " + s; try { String realName = ((IMetadata) store).getImageName(s); if (realName != null && realName.trim().length() != 0) { name = realName; } } catch (Exception e) { } setSeries(s); MetadataTools.merge(getSeriesMetadata(), allMetadata, name + " "); } setSeries(0); service.populateOriginalMetadata((OMEXMLMetadata) store, allMetadata); } } if (store instanceof OMEXMLMetadata) { ((OMEXMLMetadata) store).resolveReferences(); setupService(); if (getMetadataOptions().isValidate()) { try { String omexml = service.getOMEXML((MetadataRetrieve)store); service.validateOMEXML(omexml); } catch (ServiceException | NullPointerException e) { LOGGER.warn("OMEXMLService unable to create OME-XML metadata object.", e); } } for (int s=0; s < getSeriesCount(); s++) { setSeries(s); if (getModuloZ().length() > 1 || getModuloC().length() > 1 || getModuloT().length() > 1) { service.addModuloAlong( (OMEXMLMetadata) store, core.get(series, resolution), s); } } setSeries(0); } } }

Target:
public void setId(String id) throws FormatException, IOException { LOGGER.debug("{} initializing {}", this.getClass().getSimpleName(), id); if (currentId == null || !new Location(id).getAbsolutePath().equals( new Location(currentId).getAbsolutePath())) { initFile(id); MetadataStore store = getMetadataStore(); if (saveOriginalMetadata) { if (store instanceof OMEXMLMetadata) { setupService(); Hashtable<String, Object> allMetadata = new Hashtable<>(metadata); for (int s=0; s < getSeriesCount(); s++) { String name = "Series " + s; try { String realName = ((IMetadata) store).getImageName(s); if (realName != null && realName.trim().length() != 0) { name = realName; } } catch (Exception e) { } setSeries(s); MetadataTools.merge(getSeriesMetadata(), allMetadata, name + " "); } setSeries(0); service.populateOriginalMetadata((OMEXMLMetadata) store, allMetadata); } } if (store instanceof OMEXMLMetadata) { ((OMEXMLMetadata) store).resolveReferences(); setupService(); if (getMetadataOptions().isValidate()) { try { String omexml = service.getOMEXML((MetadataRetrieve)store); service.validateOMEXML(omexml); } catch (ServiceException | NullPointerException e) { LOGGER.warn("OMEXMLService unable to create OME-XML metadata object.", e); } } for (int s=0; s < getSeriesCount(); s++) { setSeries(s); if (getModuloZ().length() > 1 || getModuloC().length() > 1 || getModuloT().length() > 1) { service.addModuloAlong( (OMEXMLMetadata) store, core.get(series, resolution), s); } } setSeries(0); } } }
Source:
public ActionResult execute() { String searchKey = getNonNullRequestParamValue(Const.ParamsNames.ADMIN_SEARCH_KEY); List<InstructorAttributes> instructors = logic.searchInstructorsInWholeSystem(searchKey).instructorList; List<InstructorData> instructorDataList = new ArrayList<>(); for (InstructorAttributes instructor : instructors) { InstructorData instructorData = new InstructorData(instructor); instructorData.addAdditionalInformationForAdminSearch( StringHelper.encrypt(instructor.getKey()), getInstituteFromGoogleId(instructor.getGoogleId()), instructor.getGoogleId()); instructorData.hideInformationForSearch(); instructorDataList.add(instructorData); } InstructorsData instructorsData = new InstructorsData(); instructorsData.setInstructors(instructorDataList); return new JsonResult(instructorsData); }

Target:
public ActionResult execute() { String searchKey = getNonNullRequestParamValue(Const.ParamsNames.ADMIN_SEARCH_KEY); List<InstructorAttributes> instructors = logic.searchInstructorsInWholeSystem(searchKey).instructorList; List<InstructorData> instructorDataList = new ArrayList<>(); for (InstructorAttributes instructor : instructors) { InstructorData instructorData = new InstructorData(instructor); instructorData.addAdditionalInformationForAdminSearch( StringHelper.encrypt(instructor.getKey()), getInstituteFromGoogleId(instructor.getGoogleId()), instructor.getGoogleId()); instructorDataList.add(instructorData); } InstructorsData instructorsData = new InstructorsData(); instructorsData.setInstructors(instructorDataList); return new JsonResult(instructorsData); }
Source:
public <N extends Node> ParseResult<N> parse(ParseStart<N> start, Provider provider) { assertNotNull(start); assertNotNull(provider); String x = providerToString(provider); try { provider.close(); } catch (IOException e) { e.printStackTrace(); } provider = new StringProvider(x); LineEnding detectedLineEnding = LineEnding.detect(x); for (PreProcessor preProcessor : configuration.getPreProcessors()) { provider = preProcessor.process(provider); } final GeneratedJavaParser parser = getParserForProvider(provider); try { N resultNode = start.parse(parser); ParseResult<N> result = new ParseResult<>(resultNode, parser.problems, parser.getCommentsCollection()); resultNode.setData(Node.LINE_ENDING_KEY, detectedLineEnding); resultNode.findAll(Node.class) .forEach(node -> node.setData(Node.LINE_ENDING_KEY, detectedLineEnding)); configuration.getPostProcessors() .forEach(postProcessor -> postProcessor.process(result, configuration)); result.getProblems() .sort(PROBLEM_BY_BEGIN_POSITION); return result; } catch (Exception e) { final String message = e.getMessage() == null ? "Unknown error" : e.getMessage(); parser.problems.add(new Problem(message, null, e)); return new ParseResult<>(null, parser.problems, parser.getCommentsCollection()); } finally { try { provider.close(); } catch (IOException e) { } } }

Target:
public <N extends Node> ParseResult<N> parse(ParseStart<N> start, Provider provider) { assertNotNull(start); assertNotNull(provider); for (PreProcessor preProcessor : configuration.getPreProcessors()) { provider = preProcessor.process(provider); } final GeneratedJavaParser parser = getParserForProvider(provider); try { N resultNode = start.parse(parser); ParseResult<N> result = new ParseResult<>(resultNode, parser.problems, parser.getCommentsCollection()); configuration.getPostProcessors() .forEach(postProcessor -> postProcessor.process(result, configuration)); result.getProblems() .sort(PROBLEM_BY_BEGIN_POSITION); return result; } catch (Exception e) { final String message = e.getMessage() == null ? "Unknown error" : e.getMessage(); parser.problems.add(new Problem(message, null, e)); return new ParseResult<>(null, parser.problems, parser.getCommentsCollection()); } finally { try { provider.close(); } catch (IOException e) { } } }
Source:
public void bindTag(ServiceReference metacardTypeRef) { if (metacardTypeRef == null) { LOGGER.trace("New reference to metacard type was null"); return; } Object tag = metacardTypeRef.getProperty(ACCESS_CONTROLLED_TAG); if (tag == null) { if (LOGGER.isTraceEnabled()) { LOGGER.trace( "Registered metacard type is not access-controlled", typeName(metacardTypeRef)); } return; } if (!(tag instanceof String)) { LOGGER.warn( "The service property 'access-controlled-tag' is not valid, verify blueprint is correct"); return; } if (LOGGER.isTraceEnabled()) { LOGGER.trace( "Found access-controlled metacard type '{}', caching tag '{}'", typeName(metacardTypeRef), tag); } accessControlledTags.add((String) tag); }

Target:
public void bindTag(ServiceReference metacardTypeRef) { if (metacardTypeRef == null) { LOGGER.trace("New reference to metacard type was null"); return; } Object tag = metacardTypeRef.getProperty(ACCESS_CONTROLLED_TAG); if (tag == null) { if (LOGGER.isTraceEnabled()) { LOGGER.trace( "Registered metacard type is not access-controlled", typeName(metacardTypeRef)); } return; } if (!(tag instanceof String)) { if (LOGGER.isWarnEnabled()) { LOGGER.warn( "The service property 'access-controlled-tag' is not valid for metacard type {}, " + "verify the blueprint XML document is correct", typeName(metacardTypeRef)); } return; } if (LOGGER.isTraceEnabled()) { LOGGER.trace( "Found access-controlled metacard type '{}', caching tag '{}'", typeName(metacardTypeRef), tag); } accessControlledTags.add((String) tag); }
Source:
public void start() { Path location = PersistenceUtil.getQualifiedLocation(ctx.getGlobalConfiguration(), configuration.location(), ctx.getCache().getName() + ".dat"); try { file = location.toFile(); if (!file.exists()) { File dir = file.getParentFile(); if (!dir.mkdirs() && !dir.exists()) { throw PERSISTENCE.directoryCannotBeCreated(dir.getAbsolutePath()); } } channel = new RandomAccessFile(file, "rw").getChannel(); Map<K, FileEntry> entryMap = configuration.maxEntries() > 0 ? new LinkedHashMap<>(16, 0.75f, true) : new HashMap<>(); entries = Collections.synchronizedMap(entryMap); freeList = Collections.synchronizedSortedSet(new TreeSet<>()); byte[] header = new byte[MAGIC.length]; if (!configuration.purgeOnStartup() && channel.read(ByteBuffer.wrap(header), 0) == MAGIC.length && Arrays.equals(MAGIC, header)) { rebuildIndex(); processFreeEntries(); } else clear(); fragmentationFactor = configuration.fragmentationFactor(); } catch (Exception e) { throw new PersistenceException(e); } }

Target:
public void start() { Path location = PersistenceUtil.getQualifiedLocation(ctx.getGlobalConfiguration(), configuration.location(), ctx.getCache().getName(), "data"); try { file = new File(location.toFile(), ctx.getCache().getName() + ".dat"); if (!file.exists()) { File dir = file.getParentFile(); if (!dir.mkdirs() && !dir.exists()) { throw PERSISTENCE.directoryCannotBeCreated(dir.getAbsolutePath()); } } channel = new RandomAccessFile(file, "rw").getChannel(); Map<K, FileEntry> entryMap = configuration.maxEntries() > 0 ? new LinkedHashMap<>(16, 0.75f, true) : new HashMap<>(); entries = Collections.synchronizedMap(entryMap); freeList = Collections.synchronizedSortedSet(new TreeSet<>()); byte[] header = new byte[MAGIC.length]; if (!configuration.purgeOnStartup() && channel.read(ByteBuffer.wrap(header), 0) == MAGIC.length && Arrays.equals(MAGIC, header)) { rebuildIndex(); processFreeEntries(); } else clear(); fragmentationFactor = configuration.fragmentationFactor(); } catch (Exception e) { throw new PersistenceException(e); } }
Source:
public Operation exec(Prolog engine) throws PrologException { engine.setB0(); PatchSetInfo psInfo = StoredValues.PATCH_SET_INFO.get(engine); UserIdentity committer = psInfo.getCommitter(); return exec(engine, committer); }

Target:
public Operation exec(Prolog engine) throws PrologException { PatchSetInfo psInfo; try { psInfo = getPatchSetInfo(engine); } catch (PatchSetInfoNotAvailableException err) { throw new JavaException(this, 1, err); } UserIdentity committer = psInfo.getCommitter(); return exec(engine, committer); }
Source:
List<ChunkInfo> getChunksToStitch(BlobProperties stitchedBlobProperties, JSONObject stitchRequestJson) throws RestServiceException { List<String> signedChunkIds = StitchRequestSerDe.fromJson(stitchRequestJson); if (signedChunkIds.isEmpty()) { throw new RestServiceException("Must provide at least one ID in stitch request", RestServiceErrorCode.MissingArgs); } List<ChunkInfo> chunksToStitch = new ArrayList<>(signedChunkIds.size()); String expectedSession = null; long totalStitchedBlobSize = 0; for (String signedChunkId : signedChunkIds) { if (!idSigningService.isIdSigned(signedChunkId)) { throw new RestServiceException("All chunks IDs must be signed: " + signedChunkId, RestServiceErrorCode.BadRequest); } Pair<String, Map<String, String>> idAndMetadata = idSigningService.parseSignedId(signedChunkId); String blobId = idAndMetadata.getFirst(); Map<String, String> metadata = idAndMetadata.getSecond(); expectedSession = verifyChunkUploadSession(metadata, expectedSession); @SuppressWarnings("ConstantConditions") long chunkSizeBytes = RestUtils.getLongHeader(metadata, RestUtils.Headers.BLOB_SIZE, true); totalStitchedBlobSize = totalStitchedBlobSize + chunkSizeBytes; @SuppressWarnings("ConstantConditions") long expirationTimeMs = RestUtils.getLongHeader(metadata, EXPIRATION_TIME_MS_KEY, true); verifyChunkAccountAndContainer(blobId, stitchedBlobProperties); chunksToStitch.add(new ChunkInfo(blobId, chunkSizeBytes, expirationTimeMs)); } restResponseChannel.setHeader(RestUtils.Headers.BLOB_SIZE, totalStitchedBlobSize); return chunksToStitch; }

Target:
List<ChunkInfo> getChunksToStitch(BlobProperties stitchedBlobProperties, JSONObject stitchRequestJson) throws RestServiceException { List<String> signedChunkIds = StitchRequestSerDe.fromJson(stitchRequestJson); if (signedChunkIds.isEmpty()) { throw new RestServiceException("Must provide at least one ID in stitch request", RestServiceErrorCode.MissingArgs); } List<ChunkInfo> chunksToStitch = new ArrayList<>(signedChunkIds.size()); String expectedSession = null; long totalStitchedBlobSize = 0; for (String signedChunkId : signedChunkIds) { if (!idSigningService.isIdSigned(signedChunkId)) { throw new RestServiceException("All chunks IDs must be signed: " + signedChunkId, RestServiceErrorCode.BadRequest); } Pair<String, Map<String, String>> idAndMetadata = idSigningService.parseSignedId(signedChunkId); String blobId = idAndMetadata.getFirst(); Map<String, String> metadata = idAndMetadata.getSecond(); expectedSession = verifyChunkUploadSession(metadata, expectedSession); @SuppressWarnings("ConstantConditions") long chunkSizeBytes = RestUtils.getLongHeader(metadata, RestUtils.Headers.BLOB_SIZE, true); totalStitchedBlobSize += chunkSizeBytes; @SuppressWarnings("ConstantConditions") long expirationTimeMs = RestUtils.getLongHeader(metadata, EXPIRATION_TIME_MS_KEY, true); verifyChunkAccountAndContainer(blobId, stitchedBlobProperties); chunksToStitch.add(new ChunkInfo(blobId, chunkSizeBytes, expirationTimeMs)); } restResponseChannel.setHeader(RestUtils.Headers.BLOB_SIZE, totalStitchedBlobSize); return chunksToStitch; }
Source:
public synchronized void reset() throws IOException { if (mark >= 0 && position < markLimit) { this.position = mark; this.iterator = concat(markBuffers.iterator(), iterator); discardMark(); nextBuffer(); } else { throw new IOException("No mark defined"); } }

Target:
public void reset() throws IOException { if (mark >= 0 && position < markLimit) { this.position = mark; this.iterator = concat(markBuffers.iterator(), iterator); discardMark(); nextBuffer(); } else { throw new IOException("No mark defined or has read past the previous mark limit"); } }
Source:
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { super.decode(ctx, in, out); if(isHandShaked()) { logger.debug("Handshaked with hostname " + hostname()); Optional<Route<SniRouteSource, NettyHandlerRouteDestination>> route = routingTable.streamRoutes(SniRouteSource.class, NettyHandlerRouteDestination.class) .filter(r -> r.getRouteSource().getSniHostName().equals(this.hostname())) .findAny(); NettyHandlerRouteDestination routeDestination = route.orElseThrow(() -> logger.noRouteFound()).getRouteDesitnation(); ChannelInitializer<Channel> channelInitializer = routeDestination.getChannelInitializer(); ctx.pipeline().addLast(channelInitializer); channelInitializer.channelRegistered(ctx); logger.debug("Replaced with route destination's handlers"); } }

Target:
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { super.decode(ctx, in, out); if (isHandShaked()) { logger.debugf("Handshaked with hostname %s", hostname()); Optional<Route<SniRouteSource, NettyHandlerRouteDestination>> route = routingTable.streamRoutes(SniRouteSource.class, NettyHandlerRouteDestination.class) .filter(r -> r.getRouteSource().getSniHostName().equals(this.hostname())) .findAny(); NettyHandlerRouteDestination routeDestination = route.orElseThrow(() -> logger.noRouteFound()).getRouteDesitnation(); ChannelInitializer<Channel> channelInitializer = routeDestination.getChannelInitializer(); ctx.pipeline().addLast(channelInitializer); logger.debug("Replaced with route destination's handlers"); } }
Source:
public Response start(Action action) { RunVmParams params; VdcActionType actionType; if (action.isSetVm()) { VM vm = action.getVm(); validateEnums(VM.class, vm); actionType = VdcActionType.RunVmOnce; params = createRunVmOnceParams(vm); } else { actionType = VdcActionType.RunVm; params = new RunVmParams(guid); } if (action.isSetPause() && action.isPause()) { params.setRunAndPause(true); } boolean useSysprep = action.isSetUseSysprep() && action.isUseSysprep(); boolean useCloudInit = action.isSetUseCloudInit() && action.isUseCloudInit(); if (useSysprep && useCloudInit) { Fault fault = new Fault(); fault.setReason( localize( Messages.CANT_USE_SYSPREP_AND_CLUD_INIT_SIMULTANEOUSLY ) ); return Response.status(Response.Status.CONFLICT) .entity(fault) .build(); } if (useSysprep) { params.setInitializationType(InitializationType.Sysprep); } else if (useCloudInit) { params.setInitializationType(InitializationType.CloudInit); } else { params.setInitializationType(InitializationType.None); } return doAction(actionType, params, action); }

Target:
public Response start(Action action) { RunVmParams params; VdcActionType actionType; if (action.isSetVm()) { VM vm = action.getVm(); validateEnums(VM.class, vm); actionType = VdcActionType.RunVmOnce; params = createRunVmOnceParams(vm); } else { actionType = VdcActionType.RunVm; params = new RunVmParams(guid); } if (action.isSetPause() && action.isPause()) { params.setRunAndPause(true); } boolean useSysprep = action.isSetUseSysprep() && action.isUseSysprep(); boolean useCloudInit = action.isSetUseCloudInit() && action.isUseCloudInit(); if (useSysprep && useCloudInit) { Fault fault = new Fault(); fault.setReason( localize( Messages.CANT_USE_SYSPREP_AND_CLOUD_INIT_SIMULTANEOUSLY ) ); return Response.status(Response.Status.CONFLICT) .entity(fault) .build(); } if (useSysprep) { params.setInitializationType(InitializationType.Sysprep); } else if (useCloudInit) { params.setInitializationType(InitializationType.CloudInit); } else { params.setInitializationType(InitializationType.None); } return doAction(actionType, params, action); }
Source:
public static void clearSnapshot(String snapshotName, String keyspace) { RateLimiter snapshotRateLimiter = RateLimiter.create(DatabaseDescriptor.getSnapshotLinksPerSecond() == 0 ? Double.MAX_VALUE : DatabaseDescriptor.getSnapshotLinksPerSecond()); List<File> snapshotDirs = Directories.getKSChildDirectories(keyspace); Directories.clearSnapshot(snapshotName, snapshotDirs, snapshotRateLimiter); }

Target:
public static void clearSnapshot(String snapshotName, String keyspace) { RateLimiter clearSnapshotRateLimiter = DatabaseDescriptor.getSnapshotRateLimiter(); List<File> snapshotDirs = Directories.getKSChildDirectories(keyspace); Directories.clearSnapshot(snapshotName, snapshotDirs, clearSnapshotRateLimiter); }
Source:
public static void insertBenchmarkQuery(Handle handle, String querySet, String name, String query) { handle.execute( "INSERT INTO benchmark_queries(\n" + " query_set, name, catalog, benchmark_schema, query, create_time, update_time)\n" + "SELECT\n" + " ?,\n" + " ?,\n" + " 'benchmark',\n" + " 'default',\n" + " ?,\n" + " CURRENT_TIMESTAMP,\n" + " CURRENT_TIMESTAMP\n", querySet, name, query); }

Target:
public static void insertBenchmarkQuery(Handle handle, String querySet, String name, String query) { handle.execute( "INSERT INTO benchmark_queries(\n" + " `query_set`, `name`, `catalog`, `schema`, `query`)\n" + "SELECT\n" + " ?,\n" + " ?,\n" + " 'benchmark',\n" + " 'default',\n" + " ?\n", querySet, name, query); }
Source:
public void generateJavaDocForSharedPref() throws IOException { CompileResult result = compileFiles(SharedPrefWithJavaDoc.class); File generatedFile = toGeneratedFile(SharedPrefWithJavaDoc.class); assertCompilationSuccessful(result); String[] fieldDoc = { " * <p><b>Defaults to</b>: 42</p>", " * The Age!", " * @return the age as int", " * @deprecated use {@link #ageLong()}", }; String[] editorDoc = { " * The Age!", " * @return the age as int", " * @deprecated use {@link #ageLong()}", }; assertGeneratedClassContains(generatedFile, fieldDoc); assertGeneratedClassContains(generatedFile, editorDoc); }

Target:
public void generateJavaDocForSharedPref() throws IOException { CompileResult result = compileFiles(SharedPrefWithJavaDoc.class); File generatedFile = toGeneratedFile(SharedPrefWithJavaDoc.class); assertCompilationSuccessful(result); String[] fieldDoc = { " * <p><b>Defaults to</b>: 42</p>", " * The Age!", " * @return the age as int", " * @deprecated use {@link #ageLong()}", " * ", " */", " public IntPrefField age() {", }; String[] editorDoc = { " * The Age!", " * @return the age as int", " * @deprecated use {@link #ageLong()}", " * ", " */", " public IntPrefEditorField<SharedPrefWithJavaDoc_.SharedPrefWithJavaDocEditor_> age() {", }; assertGeneratedClassContains(generatedFile, fieldDoc); assertGeneratedClassContains(generatedFile, editorDoc); }
Source:
protected <I, R> Flowable<R> exactlyOnceParallel(CacheSet<I> set, Set<K> keysToExclude, Function<I, K> toKeyFunction, IntSet segments, Function<? super Publisher<I>, ? extends CompletionStage<R>> transformer, SegmentListener listener, IntSet concurrentSegments) { Flowable<I> flowable = Flowable.fromPublisher(set.localPublisher(segments)); if (keysToExclude != null) { flowable = flowable.filter(i -> !keysToExclude.contains(toKeyFunction.apply(i))); } return combineStages(flowable.buffer(512) .parallel() .runOn(asyncScheduler) .map(buffer -> transformer.apply(Flowable.fromIterable(buffer))) .sequential()); }

Target:
protected <I, R> Flowable<R> exactlyOnceParallel(CacheSet<I> set, Set<K> keysToExclude, Function<I, K> toKeyFunction, IntSet segments, Function<? super Publisher<I>, ? extends CompletionStage<R>> transformer, SegmentListener listener, IntSet concurrentSegments) { Flowable<I> flowable = Flowable.fromPublisher(set.localPublisher(segments)); if (keysToExclude != null) { flowable = flowable.filter(i -> !keysToExclude.contains(toKeyFunction.apply(i))); } return combineStages(flowable.buffer(PARALLEL_BATCH_SIZE) .parallel() .runOn(asyncScheduler) .map(buffer -> transformer.apply(Flowable.fromIterable(buffer))) .sequential()); }
Source:
private void discoverHostName_SelectedItemChanged() { if (Boolean.TRUE.equals(getIsDiscoveredHosts().getEntity())) { ExternalDiscoveredHost dhost = (ExternalDiscoveredHost) getExternalDiscoveredHosts().getSelectedItem(); ExternalHostGroup dhg = (ExternalHostGroup) getExternalHostGroups().getSelectedItem(); if (dhost != null && dhg != null) { setOriginalName(dhost.getName()); getName().setEntity(dhost.getName()); getHost().setEntity(dhost.getName() + "." + dhg.getDomainName()); } } }

Target:
private void discoverHostName_SelectedItemChanged() { if (Boolean.TRUE.equals(getIsDiscoveredHosts().getEntity())) { ExternalDiscoveredHost dhost = (ExternalDiscoveredHost) getExternalDiscoveredHosts().getSelectedItem(); ExternalHostGroup dhg = (ExternalHostGroup) getExternalHostGroups().getSelectedItem(); if (dhost != null && dhg != null) { setOriginalName(dhost.getName()); getName().setEntity(dhost.getName()); getHost().setEntity(dhost.getName() + "." + (dhg.getDomainName() != null ? dhg.getDomainName() : "")); } } }
Source:
public static boolean isSane(String path) { final int length = path.length(); if (length > PATH_MAX) { log.error("The path is characters long, which is longer than the maximum allowed {}.", length, PATH_MAX); return false; } if (path.contains("..") || path.contains(" log.error("The path contains potentially dangerous directory navigation sequences."); return false; } return true; }

Target:
public static boolean isSane(String path) { final int length = path.length(); if (length > PATH_MAX) { log.error("The path '{}' is characters long, which is longer than the maximum allowed {}.", path, length, PATH_MAX); return false; } if (path.contains("..") || path.contains(" log.error("The path contains potentially dangerous directory navigation sequences."); return false; } return true; }
Source:
AmbiguateProperties( AbstractCompiler compiler, char[] reservedFirstCharacters, char[] reservedNonFirstCharacters) { checkState(compiler.getLifeCycleStage().isNormalized()); this.compiler = compiler; this.reservedFirstCharacters = reservedFirstCharacters; this.reservedNonFirstCharacters = reservedNonFirstCharacters; this.invalidatingTypes = new InvalidatingTypes.Builder(compiler.getTypeIRegistry()) .addTypesInvalidForPropertyRenaming() .addAllTypeMismatches(compiler.getTypeMismatches()) .addAllTypeMismatches(compiler.getImplicitInterfaceUses()) .build(); this.externedNames.addAll(compiler.getExternProperties()); }

Target:
AmbiguateProperties( AbstractCompiler compiler, char[] reservedFirstCharacters, char[] reservedNonFirstCharacters) { checkState(compiler.getLifeCycleStage().isNormalized()); this.compiler = compiler; this.reservedFirstCharacters = reservedFirstCharacters; this.reservedNonFirstCharacters = reservedNonFirstCharacters; this.invalidatingTypes = new InvalidatingTypes.Builder(compiler.getTypeIRegistry()) .addTypesInvalidForPropertyRenaming() .addAllTypeMismatches(compiler.getTypeMismatches()) .addAllTypeMismatches(compiler.getImplicitInterfaceUses()) .build(); this.externedNames = ImmutableSet.<String>builder() .add("prototype") .addAll(compiler.getExternProperties()) .build(); }
Source:
public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String etag = getRelease(); String zipEtag = etag + "-gzip"; HttpServletResponse inner = (HttpServletResponse) response; HttpServletRequest req = ((HttpServletRequest) request); String ifNoneMatch = req.getHeader("If-None-Match"); long ifModSince = req.getDateHeader("If-Modified-Since"); LOG.info("etag = " + etag + ", START_UP = " + START_UP + " , ifNoneMatch = " + ifNoneMatch + ", ifModSince = " + ifModSince); if (etag.equals(ifNoneMatch) || zipEtag.equals(ifNoneMatch) || (ifModSince == START_UP)) { inner.setStatus(304); } else { inner.setHeader("ETag", etag); inner.setHeader("Cache-Control", "public,max-age=600"); inner.setDateHeader("Last-Modified", START_UP); chain.doFilter(request, new EtagIgnorer(inner)); } }

Target:
public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String etag = getRelease(); String zipEtag = etag + "-gzip"; HttpServletResponse inner = (HttpServletResponse) response; HttpServletRequest req = ((HttpServletRequest) request); String ifNoneMatch = req.getHeader("If-None-Match"); long ifModSince = req.getDateHeader("If-Modified-Since"); LOG.debug("etag = " + etag + ", START_UP = " + START_UP + ", ifNoneMatch = " + ifNoneMatch + ", ifModSince = " + ifModSince); if (etag.equals(ifNoneMatch) || zipEtag.equals(ifNoneMatch) || (ifModSince == START_UP.getTime())) { inner.setStatus(304); } else { inner.setHeader("ETag", etag); inner.setHeader("Cache-Control", "public,max-age=600"); inner.setDateHeader("Last-Modified", START_UP.getTime()); chain.doFilter(request, new EtagIgnorer(inner)); } }
Source:
public BackendInitialBuildState<?> getBackend(String backendName) { if ( StringHelper.isEmpty( backendName ) ) { backendName = getDefaultBackendName(); } return backendBuildStateByName.computeIfAbsent( backendName, this::createBackend ); }

Target:
BackendInitialBuildState<?> getBackend(String backendName) { if ( StringHelper.isEmpty( backendName ) ) { backendName = getDefaultBackendName(); } return backendBuildStateByName.computeIfAbsent( backendName, this::createBackend ); }
Source:
public void test() throws InterruptedException { try { SignUtil.signIn(driver, baseURL, uid, pwd); this.importMappingServiceTestData(); this.testTagWizard(); this.testAddOneProject(); this.testAddLifeLinesSourceToMappingProject(); this.testBasicFunctionalitiesInAttributeMappingScreen(); this.testIntegrateDataForLifeLines(); SignUtil.signOut(driver); this.deleteAllTestDataSetsFromTheApp(); } catch (Exception e) { LOG.error("The MappingServiceApp Selenium test failed: " + e.getMessage()); } finally { } }

Target:
public void test() throws InterruptedException { SignUtil.signIn(driver, baseURL, uid, pwd); this.importMappingServiceTestData(); this.testTagWizard(); this.testAddOneProject(); this.testAddLifeLinesSourceToMappingProject(); this.testBasicFunctionalitiesInAttributeMappingScreen(); this.testIntegrateDataForLifeLines(); SignUtil.signOut(driver); this.deleteAllTestDataSetsFromTheApp(); }
Source:
public Response shutdown(Action action) { org.ovirt.engine.core.common.businessentities.VM vm = getEntity(entityType, VdcQueryType.GetVmByVmId, new IdQueryParameters(guid), "VM"); Integer timeout = action.isSetGracefulTimeout() ? action.getGracefulTimeout() : vm.getGracefulTimeout(); return doAction(VdcActionType.ShutdownVm, new PowerDownVmParameters(guid, timeout, vm.isPowerdownForced()), action); }

Target:
public Response shutdown(Action action) { org.ovirt.engine.core.common.businessentities.VM vm = getEntity(entityType, VdcQueryType.GetVmByVmId, new IdQueryParameters(guid), "VM"); return doAction(VdcActionType.ShutdownVm, new PowerDownVmParameters(guid, getVmPowerDownTimeout(action, vm), vm.isPowerdownForced()), action); }
Source:
public List<ArtifactEntry> findByCoordinates(Map<String, String> coordinates) { if (coordinates == null || coordinates.keySet() .isEmpty()) { return findAll().orElse(Collections.EMPTY_LIST); } String nativeQuery = buildQuery(coordinates); OSQLSynchQuery<ArtifactEntry> query = new OSQLSynchQuery<>(nativeQuery); logger.info("[findByCoordinates] SQL -> \n\t" + nativeQuery); List<ArtifactEntry> resultList = getDelegate().query(query); return resultList; }

Target:
public List<ArtifactEntry> findByCoordinates(Map<String, String> coordinates) { if (coordinates == null || coordinates.keySet() .isEmpty()) { return findAll().orElse(Collections.EMPTY_LIST); } String nativeQuery = buildQuery(coordinates); OSQLSynchQuery<ArtifactEntry> query = new OSQLSynchQuery<>(nativeQuery); logger.info("[findByCoordinates] SQL -> \n\t" + nativeQuery); return getDelegate().query(query); }
Source:
public boolean validate(Process process) { PrefsInterface prefs = serviceManager.getRulesetService().getPreferences(process.getRuleset()); FileformatInterface gdzfile; try { gdzfile = serviceManager.getProcessService().readMetadataFile(process); } catch (Exception e) { logger.error(e.getMessage(), e); Helper.setFehlerMeldung(Helper.getTranslation("MetadataReadError") + process.getTitle(), e.getMessage()); return false; } return validate(gdzfile, prefs, process); }

Target:
public boolean validate(Process process) { PrefsInterface prefs = serviceManager.getRulesetService().getPreferences(process.getRuleset()); FileformatInterface gdzfile; try { gdzfile = serviceManager.getProcessService().readMetadataFile(process); } catch (PreferencesException | IOException | ReadException | RuntimeException e) { Helper.setErrorMessage(Helper.getTranslation("MetadataReadError") + process.getTitle(), logger, e); return false; } return validate(gdzfile, prefs, process); }
Source:
public void reportError(Throwable e) { Sentry.capture(e); LoggerFactory.getLogger((MethodHandles.lookup().lookupClass())).warn("Logging error to sentry: {}", e.toString()); }

Target:
public void reportError(Throwable e) { log.warn("Logging error to sentry: {}", e); Sentry.capture(e); }
Source:
@Override public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { if (attribute.equals("MBeanInfo")) return getMBeanInfo(); Metric metric = mset.get(attribute); if (metric == null) return null; if (metric instanceof BooleanMetric) return ((BooleanMetric)metric).value(); else if (metric instanceof DoubleMetric) return ((DoubleMetric)metric).value(); else if (metric instanceof IntMetric) return ((IntMetric)metric).value(); else if (metric instanceof LongMetric) return ((LongMetric)metric).value(); else if (metric instanceof ObjectMetric) return ((ObjectMetric)metric).value(); throw new IllegalArgumentException("Unknown metric class. " + metric.getClass()); }

Target:
@Override public Object getAttribute(String attribute) { if (attribute.equals("MBeanInfo")) return getMBeanInfo(); Metric metric = mset.get(attribute); if (metric == null) return null; if (metric instanceof BooleanMetric) return ((BooleanMetric)metric).value(); else if (metric instanceof DoubleMetric) return ((DoubleMetric)metric).value(); else if (metric instanceof IntMetric) return ((IntMetric)metric).value(); else if (metric instanceof LongMetric) return ((LongMetric)metric).value(); else if (metric instanceof ObjectMetric) return ((ObjectMetric)metric).value(); throw new IllegalArgumentException("Unknown metric class. " + metric.getClass()); }
Source:
SolrClient createSolrHttpClient(String coreName) throws IOException, SolrServerException { final HttpClientBuilder httpClientBuilder = createHttpBuilder(); final HttpSolrClient.Builder solrClientBuilder = new HttpSolrClient.Builder(getCoreUrl(coreName)); try (final Closer closer = new Closer()) { createSolrCore(coreName, null, httpClientBuilder.build()); CloseableHttpClient noRetryHttpClient = httpClientBuilder.build(); final HttpSolrClient noRetrySolrClient = closer.with(solrClientBuilder.withHttpClient(noRetryHttpClient).build()); CloseableHttpClient yesRetryHttpClient = httpClientBuilder.setRetryHandler(new SolrHttpRequestRetryHandler(coreName)).build(); final HttpSolrClient retrySolrClient = closer.with(solrClientBuilder.withHttpClient(yesRetryHttpClient).build()); return closer.returning(new PingAwareSolrClientProxy(retrySolrClient, noRetrySolrClient)); } }

Target:
SolrClient createSolrHttpClient(String coreName) throws IOException, SolrServerException { final HttpClientBuilder httpClientBuilder = createHttpBuilder(); final HttpSolrClient.Builder solrClientBuilder = new HttpSolrClient.Builder(getCoreUrl(coreName)); try (final Closer closer = new Closer()) { createSolrCore(coreName, httpClientBuilder.build()); CloseableHttpClient noRetryHttpClient = httpClientBuilder.build(); final HttpSolrClient noRetrySolrClient = closer.with(solrClientBuilder.withHttpClient(noRetryHttpClient).build()); CloseableHttpClient yesRetryHttpClient = httpClientBuilder.setRetryHandler(new SolrHttpRequestRetryHandler(coreName)).build(); final HttpSolrClient retrySolrClient = closer.with(solrClientBuilder.withHttpClient(yesRetryHttpClient).build()); return closer.returning(new PingAwareSolrClientProxy(retrySolrClient, noRetrySolrClient)); } }
Source:
private boolean parseChaserConfig(String configString) { values.clear(); String strippedConfig = configString.replaceAll("(\\s)+", ""); for (String singleStepString : strippedConfig.split("\\|")) { ValueSet value = ValueSet.fromString(singleStepString); if (value != null) { values.add(value); logger.trace("added step value to thing {}", value, this.thing.getUID()); } else { logger.warn("could not add step value to thing {}, malformed", singleStepString, this.thing.getUID()); } } return (values.size() > 0); }

Target:
private boolean parseChaserConfig(String configString) { values.clear(); String strippedConfig = configString.replaceAll("(\\s)+", ""); for (String singleStepString : strippedConfig.split("\\|")) { ValueSet value = ValueSet.fromString(singleStepString); if (value != null) { values.add(value); logger.trace("added step value to thing {}", value, this.thing.getUID()); } else { logger.debug("could not add step value to thing {}, malformed", singleStepString, this.thing.getUID()); } } return (values.size() > 0); }
Source:
public void verifyTemplateID(String templateID ,ArrayList<ErrorObj> errorObjects) { Map<String, Object> data = new HashMap<String, Object>(); data.put("siteId", "HELLO THERE"); data.put("siteParticipantCount", 25); StringWriter wtr = new StringWriter(); Template template = null; try { template = new Template("template name", new StringReader(templateID), new Configuration()); template.process(data, wtr); logger.info("Template ID Sample :"+ wtr.toString()); } catch (TemplateException te) { te.printStackTrace(); ErrorObj errorObject = createErrorObject("Study Object", "Template ID is not Valid" , "templateID"); errorObjects.add(errorObject); } catch (IOException ioe) { ioe.printStackTrace(); ErrorObj errorObject = createErrorObject("Study Object", "Template ID is not Valid", "templateID"); errorObjects.add(errorObject); } }

Target:
public void verifyTemplateID(String templateID ,ArrayList<ErrorObj> errorObjects) { Map<String, Object> data =ParticipantIdModel.getData(); StringWriter wtr = new StringWriter(); Template template = null; try { template = new Template("template name", new StringReader(templateID), new Configuration()); template.process(data, wtr); logger.info("Template ID Sample :"+ wtr.toString()); } catch (TemplateException te) { te.printStackTrace(); ErrorObj errorObject = createErrorObject("Study Object", "Template ID is not Valid" , "templateID"); errorObjects.add(errorObject); } catch (IOException ioe) { ioe.printStackTrace(); ErrorObj errorObject = createErrorObject("Study Object", "Template ID is not Valid", "templateID"); errorObjects.add(errorObject); } }