auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void setup() { nativeCacheManager = new CacheManager(new Configuration().name("EhCacheCacheManagerTests") .defaultCache(new CacheConfiguration("default", 100))); addNativeCache(CACHE_NAME); cacheManager = new EhCacheCacheManager(nativeCacheManager); cacheManager.afterPropertiesSet(); transactionalCacheManager = new EhCacheCacheManager(true, nativeCacheManager); transactionalCacheManager.afterPropertiesSet(); }

Target:
public void setup() { nativeCacheManager = new CacheManager(new Configuration().name("EhCacheCacheManagerTests") .defaultCache(new CacheConfiguration("default", 100))); addNativeCache(CACHE_NAME); cacheManager = new EhCacheCacheManager(nativeCacheManager); cacheManager.setTransactionAware(false); cacheManager.afterPropertiesSet(); transactionalCacheManager = new EhCacheCacheManager(nativeCacheManager); transactionalCacheManager.setTransactionAware(true); transactionalCacheManager.afterPropertiesSet(); }
Source:
public List<Account> getNewAccounts(long updatedSince) throws SQLException { long startTimeMs = System.currentTimeMillis(); Timestamp sinceTime = new Timestamp(updatedSince); try { PreparedStatement getSinceStatement = dataAccessor.getPreparedStatement(getAccountsSinceSql, false); getSinceStatement.setTimestamp(1, sinceTime); ResultSet rs = getSinceStatement.executeQuery(); List<Account> accounts = convertAccountsResultSet(rs); dataAccessor.onSuccess(Read, System.currentTimeMillis() - startTimeMs); return accounts; } catch (SQLException e) { dataAccessor.onException(e, Read); throw e; } }

Target:
public List<Account> getNewAccounts(long updatedSince) throws SQLException { long startTimeMs = System.currentTimeMillis(); Timestamp sinceTime = new Timestamp(updatedSince); ResultSet rs = null; try { PreparedStatement getSinceStatement = dataAccessor.getPreparedStatement(getAccountsSinceSql, false); getSinceStatement.setTimestamp(1, sinceTime); rs = getSinceStatement.executeQuery(); List<Account> accounts = convertAccountsResultSet(rs); dataAccessor.onSuccess(Read, System.currentTimeMillis() - startTimeMs); return accounts; } catch (SQLException e) { dataAccessor.onException(e, Read); throw e; } finally { closeQuietly(rs); } }
Source:
public List<Map<String, String>> linkify(HttpServletRequest req, String message) { String baseGerritUrl = urls.getBaseGerritUrl(req); CommentLinkInfo changeIds = new CommentLinkInfo("ChangeIdLinks", CHANGE_ID_PATTERN, baseGerritUrl + "#/q/$2,n,z", ""); List<CommentLinkInfo> operationalCommentLinks = new ArrayList<CommentLinkInfo>(commentLinks); operationalCommentLinks.add(changeIds); List<Map<String, String>> parsed = Lists.newArrayList(); parsed.add(ImmutableMap.of("text", message)); for (int index = 0; index < parsed.size(); index++) { Map<String, String> piece = parsed.get(index); if (piece.get("url") == null) { String text = piece.get("text"); Matcher m = allPattern.matcher(text); if (m.find()) { for (CommentLinkInfo clp : operationalCommentLinks) { List<Map<String, String>> resultingReplacement = clp.replace(piece.get("text")); if (resultingReplacement != null) { parsed.remove(index); for (Map<String, String> it : resultingReplacement) { parsed.add(index, it); index++; } } } } } } return parsed; }

Target:
public List<Map<String, String>> linkify(HttpServletRequest req, String message) { String baseGerritUrl = urls.getBaseGerritUrl(req); CommentLinkInfo changeIds = new CommentLinkInfo("ChangeIdLinks", CHANGE_ID_PATTERN, baseGerritUrl + "#/q/$2,n,z", ""); List<CommentLinkInfo> operationalCommentLinks = new ArrayList<>(commentLinks); operationalCommentLinks.add(changeIds); List<Map<String, String>> parsed = Lists.newArrayList(); parsed.add(ImmutableMap.of("text", message)); for (int index = 0; index < parsed.size(); index++) { Map<String, String> piece = parsed.get(index); if (piece.get("url") == null) { String text = piece.get("text"); Matcher m = allPattern.matcher(text); if (m.find()) { for (CommentLinkInfo cli : operationalCommentLinks) { List<Map<String, String>> resultingReplacement = cli.replace(piece.get("text")); if (resultingReplacement != null) { parsed.remove(index); for (Map<String, String> it : resultingReplacement) { parsed.add(index, it); index++; } } } } } } return parsed; }
Source:
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { final ServletContext forwardContext = getServletContext().getContext(targetContext); final RequestDispatcher dispatcher = forwardContext.getRequestDispatcher(pageNotFoundURI); dispatcher.forward(request, response); }

Target:
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { final ServletContext forwardContext = getServletContext().getContext(targetContext); if (forwardContext != null) { final RequestDispatcher dispatcher = forwardContext.getRequestDispatcher(pageNotFoundURI); if (dispatcher != null) { dispatcher.forward(request, response); } else { log.error("Unable to determine dispatcher"); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "unable to determine dispatcher"); } } else { log.error("Unable to determine forwarding context"); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "unable to determine forward context"); } }
Source:
public synchronized void get(App.Callback<BaseChangeEvent<T>> callback) throws IllegalStateException { Util.checkNull(callback, "callback"); if (thread != null) { throw new IllegalStateException("Resource already open"); } else { thread = new Thread(new Runnable() { @Override public void run() { try { eventStream = executor.run(); while (true) { BaseChangeEvent<T> nextEvent = eventStream.getNextEvent(); callback.onResult(App.Result.withResult(nextEvent)); } } catch (IOException exception) { callback.onResult(App.Result.withError(new AppException(ErrorCode.NETWORK_IO_EXCEPTION, exception))); } } }, String.format("RealmStreamTask|%s", name)); thread.start(); } }

Target:
public synchronized void get(App.Callback<BaseChangeEvent<T>> callback) throws IllegalStateException { Util.checkNull(callback, "callback"); if (thread != null) { throw new IllegalStateException("Resource already open"); } else { thread = new Thread(new Runnable() { @Override public void run() { try { eventStream = executor.run(); while (true) { BaseChangeEvent<T> nextEvent = eventStream.getNextEvent(); callback.onResult(App.Result.withResult(nextEvent)); } } catch (AppException exception) { callback.onResult(App.Result.withError(exception)); } catch (IOException exception) { AppException appException = new AppException(ErrorCode.NETWORK_IO_EXCEPTION, exception); callback.onResult(App.Result.withError(appException)); } } }, String.format("RealmStreamTask|%s", name)); thread.start(); } }
Source:
public static RefundResponse valueOf(RefundEntity refundEntity, UriInfo uriInfo) { Long accountId = refundEntity.getChargeEntity().getGatewayAccount().getId(); String externalChargeId = refundEntity.getChargeEntity().getExternalId(); String externalRefundId = refundEntity.getExternalId(); URI selfLink = uriInfo.getBaseUriBuilder() .path(REFUND_API_PATH) .build(accountId, externalChargeId, externalRefundId); URI paymentLink = uriInfo.getBaseUriBuilder() .path(CHARGE_API_PATH) .build(accountId, externalChargeId); return new RefundResponse(HalRepresentation.builder() .addProperty("refund_id", refundEntity.getExternalId()) .addProperty("amount", refundEntity.getAmount()) .addProperty("status", refundEntity.getStatus().toExternal().getStatus()) .addProperty("created_date", DateTimeUtils.toUTCDateTimeString(refundEntity.getCreatedDate())) .addProperty("refunded_by", refundEntity.getRefundedBy()) .addLink("self", selfLink) .addLink("payment", paymentLink), selfLink); }

Target:
public static RefundResponse valueOf(RefundEntity refundEntity, UriInfo uriInfo) { Long accountId = refundEntity.getChargeEntity().getGatewayAccount().getId(); String externalChargeId = refundEntity.getChargeEntity().getExternalId(); String externalRefundId = refundEntity.getExternalId(); URI selfLink = uriInfo.getBaseUriBuilder() .path(REFUND_API_PATH) .build(accountId, externalChargeId, externalRefundId); URI paymentLink = uriInfo.getBaseUriBuilder() .path(CHARGE_API_PATH) .build(accountId, externalChargeId); return new RefundResponse(HalRepresentation.builder() .addProperty("refund_id", refundEntity.getExternalId()) .addProperty("amount", refundEntity.getAmount()) .addProperty("status", refundEntity.getStatus().toExternal().getStatus()) .addProperty("created_date", DateTimeUtils.toUTCDateTimeString(refundEntity.getCreatedDate())) .addProperty("user_external_id", refundEntity.getUserExternalId()) .addLink("self", selfLink) .addLink("payment", paymentLink), selfLink); }
Source:
private Result updateImpl(final RevWalk walk, final Store store) throws IOException { RevObject newObj; RevObject oldObj; if (getRefDatabase().isNameConflicting(getName())) return Result.LOCK_FAILURE; try { if (!tryLock(true)) return Result.LOCK_FAILURE; boolean isTag = ref.getName().startsWith(Constants.R_TAGS); if (expValue != null && !isTag) { final ObjectId o; o = oldValue != null ? oldValue : ObjectId.zeroId(); if (!AnyObjectId.equals(expValue, o)) return Result.LOCK_FAILURE; } if (oldValue == null) return store.execute(Result.NEW); newObj = safeParse(walk, newValue); oldObj = safeParse(walk, oldValue); if (newObj == oldObj && !detachingSymbolicRef) return store.execute(Result.NO_CHANGE); if (newObj instanceof RevCommit && oldObj instanceof RevCommit) { if (walk.isMergedInto((RevCommit) oldObj, (RevCommit) newObj)) return store.execute(Result.FAST_FORWARD); } if (isForceUpdate() || isTag) return store.execute(Result.FORCED); return Result.REJECTED; } finally { unlock(); } }

Target:
private Result updateImpl(final RevWalk walk, final Store store) throws IOException { RevObject newObj; RevObject oldObj; if (getRefDatabase().isNameConflicting(getName())) return Result.LOCK_FAILURE; try { if (!tryLock(true)) return Result.LOCK_FAILURE; if (expValue != null) { final ObjectId o; o = oldValue != null ? oldValue : ObjectId.zeroId(); if (!AnyObjectId.equals(expValue, o)) return Result.LOCK_FAILURE; } if (oldValue == null) return store.execute(Result.NEW); newObj = safeParse(walk, newValue); oldObj = safeParse(walk, oldValue); if (newObj == oldObj && !detachingSymbolicRef) return store.execute(Result.NO_CHANGE); if (newObj instanceof RevCommit && oldObj instanceof RevCommit) { if (walk.isMergedInto((RevCommit) oldObj, (RevCommit) newObj)) return store.execute(Result.FAST_FORWARD); } if (isForceUpdate()) return store.execute(Result.FORCED); return Result.REJECTED; } finally { unlock(); } }
Source:
private List<String> getSyncthingPIDs() { List<String> mLibSyncthingPID = new ArrayList<String>(); Process ps = null; DataOutputStream psOut = null; BufferedReader br = null; mLibSyncthingPID.clear(); try { ps = Runtime.getRuntime().exec((mUseRoot) ? "su" : "sh"); psOut = new DataOutputStream(ps.getOutputStream()); psOut.writeBytes("ps\n"); psOut.writeBytes("exit\n"); psOut.flush(); ps.waitFor(); br = new BufferedReader(new InputStreamReader(ps.getInputStream(), "UTF-8")); String line; while ((line = br.readLine()) != null) { if (line.contains(Constants.FILENAME_SYNCTHING_BINARY)) { String syncthingPID = line.trim().split("\\s+")[1]; Log.v(TAG, "getSyncthingPIDs: Found process PID [" + syncthingPID + "]"); mLibSyncthingPID.add(syncthingPID); } } } catch (IOException | InterruptedException e) { Log.w(TAG_KILL, "Failed list Syncthing processes", e); } finally { try { if (br != null) { br.close(); } if (psOut != null) { psOut.close(); } } catch (IOException e) { Log.w(TAG_KILL, "Failed close the psOut stream", e); } if (ps != null) { ps.destroy(); } } return mLibSyncthingPID; }

Target:
private List<String> getSyncthingPIDs() { List<String> libSyncthingPID = new ArrayList<String>(); Process ps = null; DataOutputStream psOut = null; BufferedReader br = null; try { ps = Runtime.getRuntime().exec((mUseRoot) ? "su" : "sh"); psOut = new DataOutputStream(ps.getOutputStream()); psOut.writeBytes("ps\n"); psOut.writeBytes("exit\n"); psOut.flush(); ps.waitFor(); br = new BufferedReader(new InputStreamReader(ps.getInputStream(), "UTF-8")); String line; while ((line = br.readLine()) != null) { if (line.contains(Constants.FILENAME_SYNCTHING_BINARY)) { String syncthingPID = line.trim().split("\\s+")[1]; Log.v(TAG, "getSyncthingPIDs: Found process PID [" + syncthingPID + "]"); libSyncthingPID.add(syncthingPID); } } } catch (IOException | InterruptedException e) { Log.w(TAG_KILL, "Failed list Syncthing processes", e); } finally { try { if (br != null) { br.close(); } if (psOut != null) { psOut.close(); } } catch (IOException e) { Log.w(TAG_KILL, "Failed close the psOut stream", e); } if (ps != null) { ps.destroy(); } } return libSyncthingPID; }
Source:
public void runJob() { PID depositPID = getDepositPID(); Model model = getWritableModel(); Bag depositBag = model.createBag(depositPID.getURI().toString()); PID primaryPID = new PID("uuid:" + UUID.randomUUID()); Map<String, String> depositStatus = getDepositStatus(); String filename = depositStatus.get(DepositField.fileName.name()); String slug = depositStatus.get(DepositField.depositSlug.name()); String mimetype = depositStatus.get(DepositField.fileMimetype.name()); String contentModel = depositStatus.get(RDF.type.toString()); Resource primaryResource = model.createResource(primaryPID.getURI()); if (contentModel == null || Cdr.FileObject.equals(contentModel)) { populateSimple(model, primaryResource, slug, filename, mimetype); } else { populateContainer(model, primaryResource, primaryPID, slug, contentModel); } depositBag.add(primaryResource); if (!this.getDepositDirectory().exists()) { log.info("Creating deposit dir {}", this.getDepositDirectory().getAbsolutePath()); this.getDepositDirectory().mkdir(); } PremisLogger premisDepositLogger = getPremisLogger(depositPID); Resource premisDepositEvent = premisDepositLogger.buildEvent(Premis.Normalization) .addEventDetail("Normalized deposit package from {0} to {1}", PackagingType.SIMPLE_OBJECT.getUri(), PackagingType.BAG_WITH_N3.getUri()) .addSoftwareAgent(SoftwareAgent.depositService.getFullname()) .create(); premisDepositLogger.writeEvent(premisDepositEvent); }

Target:
public void runJob() { PID depositPID = getDepositPID(); Model model = getWritableModel(); Bag depositBag = model.createBag(depositPID.getURI().toString()); PID mainPID = repository.mintContentPid(); Map<String, String> depositStatus = getDepositStatus(); String filename = depositStatus.get(DepositField.fileName.name()); String slug = depositStatus.get(DepositField.depositSlug.name()); String mimetype = depositStatus.get(DepositField.fileMimetype.name()); Resource mainResource = model.createResource(mainPID.getURI()); populateFileObject(model, mainResource, slug, filename, mimetype); depositBag.add(mainResource); if (!this.getDepositDirectory().exists()) { log.info("Creating deposit dir {}", this.getDepositDirectory().getAbsolutePath()); this.getDepositDirectory().mkdir(); } PremisLogger premisDepositLogger = getPremisLogger(depositPID); Resource premisDepositEvent = premisDepositLogger.buildEvent(Premis.Normalization) .addEventDetail("Normalized deposit package from {0} to {1}", PackagingType.SIMPLE_OBJECT.getUri(), PackagingType.BAG_WITH_N3.getUri()) .addSoftwareAgent(SoftwareAgent.depositService.getFullname()) .create(); premisDepositLogger.writeEvent(premisDepositEvent); }
Source:
public MessageStream<M> merge(Collection<? extends MessageStream<? extends M>> otherStreams) { MessageStreamImpl<M> nextStream = new MessageStreamImpl<>(this.graph); List<MessageStream<M>> streamsToMerge = new ArrayList<>(); streamsToMerge.add(this); streamsToMerge.addAll((Collection<MessageStream<M>>) otherStreams); streamsToMerge.forEach(stream -> { OperatorSpec mergeOperatorSpec = OperatorSpecs.createMergeOperatorSpec(nextStream, this.graph.getNextOpId()); ((MessageStreamImpl<M>) stream).registeredOperatorSpecs.add(mergeOperatorSpec); }); return nextStream; }

Target:
public MessageStream<M> merge(Collection<? extends MessageStream<? extends M>> otherStreams) { MessageStreamImpl<M> nextStream = new MessageStreamImpl<>(this.graph); List<MessageStream<M>> streamsToMerge = new ArrayList<>((Collection<MessageStream<M>>) otherStreams); streamsToMerge.add(this); streamsToMerge.forEach(stream -> { OperatorSpec mergeOperatorSpec = OperatorSpecs.createMergeOperatorSpec(nextStream, this.graph.getNextOpId()); ((MessageStreamImpl<M>) stream).registeredOperatorSpecs.add(mergeOperatorSpec); }); return nextStream; }
Source:
public ITmfStateInterval doSingularQuery(long t, int attributeQuark) throws TimeRangeException, StateSystemDisposedException { ITmfStateInterval interval = null; try { interval = getRelevantInterval(t, attributeQuark); } catch (ClosedChannelException e) { e.printStackTrace(); } return interval; }

Target:
public ITmfStateInterval doSingularQuery(long t, int attributeQuark) throws TimeRangeException, StateSystemDisposedException { try { return getRelevantInterval(t, attributeQuark); } catch (ClosedChannelException e) { throw new StateSystemDisposedException(e); } }
Source:
protected void filter(GenericResourceMethod genericResourceMethod, Object[] arguments) throws ApiException { final String methodName = genericResourceMethod.getMethod().getName(); final Subject subject = EnvironmentContext.getCurrent().getSubject(); switch (methodName) { case "getCurrent": case "updatePassword": case "getById": case "find": case "test": case "getSettings": return; case "create": final String token = (String) arguments[1]; if (token != null) { if (!userSelfCreationAllowed && !subject.hasPermission(SystemDomain.DOMAIN_ID, null, MANAGE_USERS_ACTION)) { throw new ForbiddenException( "Currently only admins can create accounts. Please contact our Admin Team for further info."); } return; } subject.checkPermission(SystemDomain.DOMAIN_ID, null, MANAGE_USERS_ACTION); break; case "remove": final String userToRemove = (String) arguments[0]; if (subject.getUserId().equals(userToRemove)) { return; } subject.checkPermission(SystemDomain.DOMAIN_ID, null, MANAGE_USERS_ACTION); break; default: throw new ForbiddenException("User is not authorized to perform this operation"); } }

Target:
protected void filter(GenericResourceMethod genericResourceMethod, Object[] arguments) throws ApiException { final String methodName = genericResourceMethod.getMethod().getName(); final Subject subject = EnvironmentContext.getCurrent().getSubject(); switch (methodName) { case "getCurrent": case "updatePassword": case "getById": case "find": case "getSettings": return; case "create": final String token = (String) arguments[1]; if (token != null) { if (!userSelfCreationAllowed && !subject.hasPermission(SystemDomain.DOMAIN_ID, null, MANAGE_USERS_ACTION)) { throw new ForbiddenException( "Currently only admins can create accounts. Please contact our Admin Team for further info."); } return; } subject.checkPermission(SystemDomain.DOMAIN_ID, null, MANAGE_USERS_ACTION); break; case "remove": final String userToRemove = (String) arguments[0]; if (subject.getUserId().equals(userToRemove)) { return; } subject.checkPermission(SystemDomain.DOMAIN_ID, null, MANAGE_USERS_ACTION); break; default: throw new ForbiddenException("User is not authorized to perform this operation"); } }
Source:
private Pair<Long, Long> nibbleDeleteReplicated(ComparisonConstant op, int ts, long numberOfItems) throws NoConnectionsException, IOException { TimestampType value = new TimestampType(ts); VoltTable table = new VoltTable(new ColumnInfo[] { new ColumnInfo("col1", VoltType.typeFromObject(value)), }); table.addRow(value); long deleted = 0; long toBeDeleted = 0; long start = System.currentTimeMillis(); try { ClientResponse response = m_client.callProcedure("@NibbleDeleteMP", "rep", "ts", op.ordinal(), table, 500); VoltTable result = response.getResults()[0]; assertEquals(1, result.getRowCount()); result.advanceRow(); deleted = result.getLong("DELETED_ROWS"); long leftoverRows = result.getLong("LEFTOVER_ROWS"); toBeDeleted += leftoverRows; } catch (ProcCallException e) { fail("Fail to run NibbleDeleteSP: " + e.getMessage()); } System.out.println("Delete " + deleted + " rows on replicated table, " + toBeDeleted + " rows pending, cost " + (System.currentTimeMillis() - start) + " ms"); try { long rowCount = m_client.callProcedure("repcount").getResults()[0].asScalarLong(); assertEquals(numberOfItems - deleted, rowCount); } catch (ProcCallException e) { fail("Failed to get row count from Table part"); } return new Pair<>(deleted, toBeDeleted); }

Target:
private Pair<Long, Long> nibbleDeleteReplicated(ComparisonConstant op, int ts, long numberOfItems) throws NoConnectionsException, IOException { TimestampType value = new TimestampType(ts); VoltTable table = new VoltTable(new ColumnInfo[] { new ColumnInfo("col1", VoltType.typeFromObject(value)), }); table.addRow(value); long deleted = 0; long toBeDeleted = 0; long start = System.currentTimeMillis(); try { ClientResponse response = m_client.callProcedure("@NibbleDeleteMP", "rep", "ts", op.ordinal(), table, 500); VoltTable result = response.getResults()[0]; assertEquals(1, result.getRowCount()); result.advanceRow(); deleted = result.getLong("DELETED_ROWS"); long leftoverRows = result.getLong("LEFTOVER_ROWS"); toBeDeleted += leftoverRows; } catch (ProcCallException e) { fail("Fail to run NibbleDeleteMP: " + e.getMessage()); } System.out.println("Delete " + deleted + " rows on replicated table, " + toBeDeleted + " rows pending, cost " + (System.currentTimeMillis() - start) + " ms"); try { long rowCount = m_client.callProcedure("repcount").getResults()[0].asScalarLong(); assertEquals(numberOfItems - deleted, rowCount); } catch (ProcCallException e) { fail("Failed to get row count from Table part"); } return new Pair<>(deleted, toBeDeleted); }
Source:
public void changesTheDirectionFromNorthToEast() { GridPosition initialGridPosition = new GridPosition(0, 0); Robot robot = new Robot(initialGridPosition, Orientation.NORTH); robot.turnRight(); Orientation expectedOrientation = Orientation.EAST; assertEquals(robot.getGridPosition(), initialGridPosition); assertEquals(robot.getOrientation(), expectedOrientation); }

Target:
public void changesTheDirectionFromNorthToEast() { GridPosition initialGridPosition = new GridPosition(0, 0); Robot robot = new Robot(initialGridPosition, Orientation.NORTH); robot.turnRight(); Orientation expectedOrientation = Orientation.EAST; assertEquals(initialGridPosition, robot.getGridPosition()); assertEquals(expectedOrientation, robot.getOrientation()); }
Source:
public Optional<T> get(Random rand) { int target = rand.nextInt(this.totalWeight); int current = 0; for (T obj : this) { current += obj.getWeight(); if (current > target) { return Optional.of(obj); } } return Optional.empty(); }

Target:
public T get(Random rand) { int target = rand.nextInt(this.totalWeight); int current = 0; for (T obj : this) { current += obj.getWeight(); if (current > target) { return obj; } } return null; }
Source:
public RequestResponseHandlerController(int handlerCount, RestServerMetrics restServerMetrics) { if (handlerCount > 0) { this.restServerMetrics = restServerMetrics; createRequestHandlers(handlerCount); restServerMetrics.trackRequestHandlerHealth(requestResponseHandlers); } else { restServerMetrics.requestHandlerControllerInstantiationError.inc(); throw new IllegalArgumentException("Handlers to be created has to be > 0. Is " + handlerCount); } logger.trace("Instantiated RequestResponseHandlerController"); }

Target:
public RequestResponseHandlerController(int handlerCount, RestServerMetrics restServerMetrics) { if (handlerCount > 0) { this.restServerMetrics = restServerMetrics; createRequestResponseHandlers(handlerCount); restServerMetrics.trackRequestHandlerHealth(asyncRequestResponseHandlers); } else { restServerMetrics.requestHandlerControllerInstantiationError.inc(); throw new IllegalArgumentException("Handlers to be created has to be > 0. Is " + handlerCount); } logger.trace("Instantiated RequestResponseHandlerController"); }
Source:
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); xhtml.startDocument(); EmbeddedDocumentExtractor extractor = context.get( EmbeddedDocumentExtractor.class, new ParsingEmbeddedDocumentExtractor(context)); TemporaryResources tmp = new TemporaryResources(); Archive rar = null; try { TikaInputStream tis = TikaInputStream.get(stream, tmp); rar = new Archive(tis.getFile()); if (rar.isEncrypted()) { throw new EncryptedDocumentException(); } xhtml.element("div", " "); FileHeader header = rar.nextFileHeader(); while (header != null && !Thread.currentThread().isInterrupted()) { if (!header.isDirectory()) { InputStream subFile = null; try { subFile = rar.getInputStream(header); Metadata entrydata = PackageParser.handleEntryMetadata( header.getFileNameW().equals("")?header.getFileNameString():header.getFileNameW(), header.getCTime(), header.getMTime(), header.getFullUnpackSize(), xhtml ); if (extractor.shouldParseEmbedded(entrydata)) { extractor.parseEmbedded(subFile, handler, entrydata, true); } } finally { if (subFile != null) subFile.close(); } } header = rar.nextFileHeader(); } } catch (RarException e) { throw new TikaException("RarParser Exception", e); } finally { if (rar != null) rar.close(); tmp.close(); } xhtml.endDocument(); }

Target:
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); xhtml.startDocument(); EmbeddedDocumentExtractor extractor = context.get( EmbeddedDocumentExtractor.class, new ParsingEmbeddedDocumentExtractor(context)); TemporaryResources tmp = new TemporaryResources(); Archive rar = null; try { TikaInputStream tis = TikaInputStream.get(stream, tmp); rar = new Archive(tis.getFile()); if (rar.isEncrypted()) { throw new EncryptedDocumentException(); } xhtml.element("div", " "); FileHeader header = rar.nextFileHeader(); while (header != null && !Thread.currentThread().isInterrupted()) { if (!header.isDirectory()) { InputStream subFile = null; try { subFile = rar.getInputStream(header); Metadata entrydata = PackageParser.handleEntryMetadata( "".equals(header.getFileNameW())?header.getFileNameString():header.getFileNameW(), header.getCTime(), header.getMTime(), header.getFullUnpackSize(), xhtml ); if (extractor.shouldParseEmbedded(entrydata)) { extractor.parseEmbedded(subFile, handler, entrydata, true); } } finally { if (subFile != null) subFile.close(); } } header = rar.nextFileHeader(); } } catch (RarException e) { throw new TikaException("RarParser Exception", e); } finally { if (rar != null) rar.close(); tmp.close(); } xhtml.endDocument(); }
Source:
protected void onAttach() { super.onAttach(); register(EventController.get().addHandlerToSource(GetForumsEventHandler.TYPE, ForumController.get(), this)); register(EventController.get().addHandlerToSource(NavigationEventHandler.TYPE, NavigationController.get(), this)); topics.redraw(); }

Target:
protected void onAttach() { super.onAttach(); register(EventController.get().addHandlerToSource(GetForumsEventHandler.TYPE, ForumController.get(), this)); register(EventController.get().addHandlerToSource(NavigationEventHandler.TYPE, NavigationController.get(), this)); }
Source:
public List<DiagnosticsElement> getDiagnostics() { List<DiagnosticsElement> diagnosticsElements = new ArrayList<>(); Iterator<String> fieldNames = getJson().fieldNames(); boolean isHealthy = false; String message = null; while (fieldNames.hasNext()) { String fieldName = fieldNames.next(); JsonNode jsonNode = getJson().get(fieldName); if (jsonNode != null) { if (jsonNode.get(HEALTHY) != null) { isHealthy = jsonNode.get(HEALTHY).asBoolean(); } if (jsonNode.get(MESSAGE) != null) { message = jsonNode.get(MESSAGE).asText(); } diagnosticsElements.add(new DiagnosticsElement(fieldName, isHealthy, message)); } } return diagnosticsElements; }

Target:
public List<DiagnosticsElement> getDiagnostics() { List<DiagnosticsElement> diagnosticsElements = new ArrayList<>(); if (getJson() != null) { Iterator<String> fieldNames = getJson().fieldNames(); while (fieldNames.hasNext()) { boolean isHealthy = false; String message = null; String fieldName = fieldNames.next(); JsonNode jsonNode = getJson().get(fieldName); if (jsonNode != null) { if (jsonNode.get(HEALTHY) != null) { isHealthy = jsonNode.get(HEALTHY).asBoolean(); } if (jsonNode.get(MESSAGE) != null) { message = jsonNode.get(MESSAGE).asText(); } else { message = new String("Message Unavailable"); } diagnosticsElements.add(new DiagnosticsElement(fieldName, isHealthy, message)); } } } return diagnosticsElements; }
Source:
public void stop(StopContext context) { super.stop(context); System.clearProperty("wildfly.test.boot.disable.rollback"); }

Target:
public void stop(StopContext context) { super.stop(context); System.clearProperty("jboss.as.test.disable.runtime"); }
Source:
public void hideKeyboard(View view) { InputMethodManager inputManager = (InputMethodManager) this .getSystemService(Context.INPUT_METHOD_SERVICE); View focusedView = this.getCurrentFocus(); if (focusedView != null) { inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN); } }

Target:
public void hideKeyboard(View view) { InputMethodManager inputManager = (InputMethodManager) this .getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager .RESULT_UNCHANGED_SHOWN); }
Source:
public void fillMemory(IMemoryDMContext memoryDMC, IAddress address, long offset, int word_size, int count, byte[] pattern, RequestMonitor rm) { if (memoryDMC == null) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Unknown context type", null)); rm.done(); return; } if (word_size < 1) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, NOT_SUPPORTED, "Word size not supported (< 1)", null)); rm.done(); return; } if (count < 0) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, IDsfStatusConstants.INTERNAL_ERROR, "Invalid repeat count (< 0)", null)); rm.done(); return; } if (pattern.length < 1) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, IDsfStatusConstants.INTERNAL_ERROR, "Empty pattern", null)); rm.done(); return; } int length = pattern.length; byte[] buffer = new byte[count * length]; for (int i = 0; i < count; i++) { System.arraycopy(pattern, 0, buffer, i * length, length); } getMemoryCache(memoryDMC).setMemory(memoryDMC, address, offset, word_size, count * length, buffer, rm); }

Target:
public void fillMemory(IMemoryDMContext memoryDMC, IAddress address, long offset, int word_size, int count, byte[] pattern, RequestMonitor rm) { if (memoryDMC == null) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Unknown context type", null)); rm.done(); return; } if (word_size < 1) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, NOT_SUPPORTED, "Word size not supported (< 1)", null)); rm.done(); return; } if (count < 0) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, IDsfStatusConstants.INTERNAL_ERROR, "Invalid repeat count (< 0)", null)); rm.done(); return; } if (pattern.length < 1) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, IDsfStatusConstants.INTERNAL_ERROR, "Empty pattern", null)); rm.done(); return; } int length = pattern.length; byte[] buffer = new byte[count * length]; for (int i = 0; i < count; i++) { System.arraycopy(pattern, 0, buffer, i * length, length); } int word_count = buffer.length / word_size; if (buffer.length % word_size != 0) { word_count ++; } getMemoryCache(memoryDMC).setMemory(memoryDMC, address, offset, word_size, word_count, buffer, rm); }
Source:
public List<DataSegment> getUsedSegmentsForIntervals( final String dataSource, final List<Interval> intervals ) throws IOException { final StringBuilder sb = new StringBuilder(); sb.append("SELECT payload FROM %s WHERE used = true AND dataSource = :dataSource AND ("); for (int i = 0; i < intervals.size(); i++) { Interval interval = intervals.get(i); sb.append("(start <= '" + interval.getEnd().toString() + "' AND \"end\" >= '" + interval.getStart().toString() + "')"); if (i == intervals.size()-1) { sb.append(")"); } else { sb.append(" OR "); } } final VersionedIntervalTimeline<String, DataSegment> timeline = connector.getDBI().withHandle( new HandleCallback<VersionedIntervalTimeline<String, DataSegment>>() { @Override public VersionedIntervalTimeline<String, DataSegment> withHandle(Handle handle) throws IOException { final VersionedIntervalTimeline<String, DataSegment> timeline = new VersionedIntervalTimeline<String, DataSegment>( Ordering.natural() ); final ResultIterator<byte[]> dbSegments = handle.createQuery( String.format( sb.toString(), dbTables.getSegmentsTable() ) ) .bind("dataSource", dataSource) .map(ByteArrayMapper.FIRST) .iterator(); while (dbSegments.hasNext()) { final byte[] payload = dbSegments.next(); DataSegment segment = jsonMapper.readValue( payload, DataSegment.class ); timeline.add(segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk(segment)); } dbSegments.close(); return timeline; } } ); return Lists.newArrayList( Iterables.concat( Iterables.transform( Iterables.concat( Iterables.transform( intervals, new Function<Interval, Iterable<TimelineObjectHolder<String, DataSegment>>>() { @Override public Iterable<TimelineObjectHolder<String, DataSegment>> apply(Interval interval) { return timeline.lookup(interval); } } ) ), new Function<TimelineObjectHolder<String, DataSegment>, Iterable<DataSegment>>() { @Override public Iterable<DataSegment> apply(TimelineObjectHolder<String, DataSegment> input) { return input.getObject().payloads(); } } ) ) ); }

Target:
public List<DataSegment> getUsedSegmentsForIntervals( final String dataSource, final List<Interval> intervals ) throws IOException { return connector.retryWithHandle( new HandleCallback<List<DataSegment>>() { @Override public List<DataSegment> withHandle(Handle handle) throws Exception { final VersionedIntervalTimeline<String, DataSegment> timeline = getTimelineForIntervalsWithHandle( handle, dataSource, intervals ); Set<DataSegment> segments = Sets.newHashSet( Iterables.concat( Iterables.transform( Iterables.concat( Iterables.transform( intervals, new Function<Interval, Iterable<TimelineObjectHolder<String, DataSegment>>>() { @Override public Iterable<TimelineObjectHolder<String, DataSegment>> apply(Interval interval) { return timeline.lookup(interval); } } ) ), new Function<TimelineObjectHolder<String, DataSegment>, Iterable<DataSegment>>() { @Override public Iterable<DataSegment> apply(TimelineObjectHolder<String, DataSegment> input) { return input.getObject().payloads(); } } ) ) ); return new ArrayList<>(segments); } } ); }
Source:
public String docs() { return "void {[player], flight} Sets whether or not this player is flying. Requires player to have the ability to fly."; }

Target:
public String docs() { return "void {[player], flight} Sets whether or not this player is flying." + "Requires player to have the ability to fly, which is set with set_pflight()."; }
Source:
public void shouldReportXssInLocationHashAssign(String browser) throws NullPointerException, IOException { String test = "/shouldReportXssInLocationHashAssign/"; this.nano.addHandler( new NanoServerHandler(test) { @Override protected Response serve(IHTTPSession session) { String response = getHtml("LocationHashAssign.html"); return newFixedLengthResponse(response); } }); HttpMessage msg = this.getHttpMessage(test); this.rule.getConfig().setProperty("rules.domxss.browserid", browser); this.rule.init(msg, this.parent); this.rule.scan(); assertAlertsRaised(); }

Target:
public void shouldReportXssInLocationHashAssign(String browser) throws NullPointerException, IOException { String test = "/shouldReportXssInLocationHashAssign/"; this.nano.addHandler(new TestNanoServerHandler(test, "LocationHashAssign.html")); HttpMessage msg = this.getHttpMessage(test); this.rule.getConfig().setProperty("rules.domxss.browserid", browser); this.rule.init(msg, this.parent); this.rule.scan(); assertAlertsRaised(); }
Source:
public boolean acquireParts() { if (!customJob) { checkForArmorSupplies(); return kitFound && !partsInTransit() && (null == newArmorSupplies || (armorNeeded - newArmorSupplies.getAmount()) <= 0); } ArrayList<Part> newShoppingList = new ArrayList<>(); for (Part part : shoppingList) { if (part instanceof IAcquisitionWork) { Part replacement = part; if (part instanceof MissingPart) { replacement = ((MissingPart)part).findReplacement(true); } if (null != replacement) { if(replacement.getQuantity() > 1) { Part actualReplacement = replacement.clone(); actualReplacement.setRefitId(oldUnit.getId()); oldUnit.getCampaign().addPart(actualReplacement, 0); newUnitParts.add(actualReplacement.getId()); replacement.decrementQuantity(); } else { replacement.setRefitId(oldUnit.getId()); newUnitParts.add(replacement.getId()); } } else { newShoppingList.add(part); } } } boolean missingAmmo = false; for (int pid : newUnitParts) { Part part = getCampaign().getPart(pid); if (part instanceof AmmoBin) { AmmoBin bin = (AmmoBin) part; Part foundAmmo = getCampaign().findSparePart(campaignPart -> AmmoStorage.IsRightAmmo(campaignPart, (AmmoType) bin.getType())); if (foundAmmo == null || (((AmmoStorage) foundAmmo).getShots() < bin.getShotsNeeded())) { missingAmmo = true; break; } } } checkForArmorSupplies(); shoppingList = newShoppingList; if (partsInTransit()) { return false; } return shoppingList.size() == 0 && !missingAmmo && (null == newArmorSupplies || (armorNeeded - newArmorSupplies.getAmount()) <= 0); }

Target:
public boolean acquireParts() { if (!customJob) { checkForArmorSupplies(); return kitFound && !partsInTransit() && (null == newArmorSupplies || (armorNeeded - newArmorSupplies.getAmount()) <= 0); } ArrayList<Part> newShoppingList = new ArrayList<>(); for (Part part : shoppingList) { if (part instanceof IAcquisitionWork) { Part replacement = part; if (part instanceof MissingPart) { replacement = ((MissingPart)part).findReplacement(true); } if (null != replacement) { if(replacement.getQuantity() > 1) { Part actualReplacement = replacement.clone(); actualReplacement.setRefitId(oldUnit.getId()); oldUnit.getCampaign().addPart(actualReplacement, 0); newUnitParts.add(actualReplacement.getId()); replacement.decrementQuantity(); } else { replacement.setRefitId(oldUnit.getId()); newUnitParts.add(replacement.getId()); } } else { newShoppingList.add(part); } } } boolean missingAmmo = false; for (int pid : newUnitParts) { Part part = getCampaign().getPart(pid); if (part instanceof AmmoBin) { AmmoBin bin = (AmmoBin) part; Part foundAmmo = getCampaign().findSparePart(campaignPart -> AmmoStorage.IsRightAmmo(campaignPart, (AmmoType) bin.getType())); if ((foundAmmo == null) || (((AmmoStorage) foundAmmo).getShots() < bin.getShotsNeeded())) { missingAmmo = true; break; } } } checkForArmorSupplies(); shoppingList = newShoppingList; if (partsInTransit()) { return false; } return shoppingList.size() == 0 && !missingAmmo && (null == newArmorSupplies || (armorNeeded - newArmorSupplies.getAmount()) <= 0); }
Source:
protected List<SinkRecord> createStringRecords( int size, Set<TopicPartition> partitions ) { String key = "key"; List<SinkRecord> sinkRecords = new ArrayList<>(); for (long offset = 0, total = 0; total < size; ++offset) { for (TopicPartition tp : partitions) { String record = "Some random text..."; sinkRecords.add(new SinkRecord(TOPIC, tp.partition(), null, key, null, record, offset)); if (++total >= size) { break; } } } return sinkRecords; }

Target:
protected List<SinkRecord> createStringRecords( int size, Set<TopicPartition> partitions ) { String key = "key"; List<SinkRecord> sinkRecords = new ArrayList<>(); for (long offset = 0, total = 0; total < size; ++offset) { for (TopicPartition tp : partitions) { String record = "Some random text. Offset: " + offset; sinkRecords.add(new SinkRecord(TOPIC, tp.partition(), null, key, null, record, offset)); if (++total >= size) { break; } } } return sinkRecords; }
Source:
private int measureIfRoomItems(int widthUsed, int alwaysItemsWidth, int widthMeasureSpec, int heightMeasureSpec) { int width = 0; boolean widthUnspecified = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.UNSPECIFIED; int widthCapacity = (MeasureSpec.getSize(widthMeasureSpec) / 2) - alwaysItemsWidth; int allowedCount = ACTION_ITEM_COUNT_LIMIT - mAlwaysItemCount; for (InflatedMenuItem inflatedItem : mAllMenuItems) { if (allowedCount == 0 || (!widthUnspecified && widthCapacity <= mMinActionButtonWidth)) { break; } if (inflatedItem.mItem.getDisplayBehavior() == CarMenuItem.DisplayBehavior.IF_ROOM) { View action = inflatedItem.mView; measureChild(action, widthMeasureSpec, widthUsed + width, heightMeasureSpec, 0); int viewWidth = action.getMeasuredWidth() + getHorizontalMargins(action); if (widthUnspecified || widthCapacity - viewWidth > 0) { allowedCount--; widthCapacity -= viewWidth; width += viewWidth; inflatedItem.mIsDisplayedOnToolbar = true; addView(action); } } } return width; }

Target:
private int measureIfRoomItems(int widthUsed, int alwaysItemsWidth, int widthMeasureSpec, int heightMeasureSpec) { int width = 0; boolean isWidthUnspecified = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.UNSPECIFIED; int widthCapacity = (MeasureSpec.getSize(widthMeasureSpec) / 2) - alwaysItemsWidth; int allowedCount = ACTION_ITEM_COUNT_LIMIT - mAlwaysItemCount; for (InflatedMenuItem inflatedItem : mAllMenuItems) { if (allowedCount < 1 || (!isWidthUnspecified && widthCapacity <= mMinActionButtonWidth)) { break; } if (inflatedItem.mItem.getDisplayBehavior() == CarMenuItem.DisplayBehavior.IF_ROOM) { View action = inflatedItem.mView; measureChild(action, widthMeasureSpec, widthUsed + width, heightMeasureSpec, 0); int viewWidth = action.getMeasuredWidth() + getHorizontalMargins(action); if (isWidthUnspecified || widthCapacity - viewWidth > 0) { allowedCount--; widthCapacity -= viewWidth; width += viewWidth; inflatedItem.mIsDisplayedOnToolbar = true; addView(action); } } } return width; }
Source:
protected Set<InternalCacheEntry> loadAllLockSafe() throws CacheLoaderException { EntityManager em = emf.createEntityManager(); try { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(config.getEntityClass()); cq.select(cq.from(config.getEntityClass())); TypedQuery q = em.createQuery(cq); List list = q.getResultList(); if (list == null || list.isEmpty()) { return Collections.emptySet(); } PersistenceUnitUtil util = emf.getPersistenceUnitUtil(); Set<InternalCacheEntry> result = new HashSet<InternalCacheEntry>( list.size()); for (Object o : list) { Object key = util.getIdentifier(o); result.add(new ImmortalCacheEntry(key, o)); } return result; } finally { em.close(); } }

Target:
protected Set<InternalCacheEntry> loadAllLockSafe() throws CacheLoaderException { return loadLockSafe(-1); }
Source:
public Map<String, String> prepareImages(Map<String, DockerContainerConfig> containers) throws InterruptedException, InfrastructureException { if (executor.getActiveCount() + containers.size() > executor.getMaximumPoolSize()) { LOG.warn( String.format( "Maximum parallel images preparing threads reached. Some images will be queued.\n" + " Workspace machines count is %s. If problem persists, increase %s property value.", containers.size(), PARALLEL_PULL_PROPERTY_NAME)); } Map<String, String> imagesMap = new ConcurrentHashMap<>(containers.size()); CompletableFuture<Void> firstFailed = new CompletableFuture<>(); List<CompletableFuture<Void>> taskFutures = containers .entrySet() .stream() .map( e -> CompletableFuture.supplyAsync( (Supplier<Void>) () -> { try { imagesMap.put(e.getKey(), prepareImage(e.getKey(), e.getValue())); } catch (InternalInfrastructureException | SourceNotFoundException ex) { firstFailed.completeExceptionally(ex); } return null; }, executor)) .collect(toList()); CompletableFuture all = CompletableFuture.allOf(taskFutures.toArray(new CompletableFuture[taskFutures.size()])); try { CompletableFuture.anyOf(all, firstFailed).get(); } catch (ExecutionException e) { try { throw e.getCause(); } catch (InfrastructureException rethrow) { throw rethrow; } catch (Throwable thr) { throw new InternalInfrastructureException("Unable to build image", thr); } } return imagesMap; }

Target:
public Map<String, String> prepareImages(Map<String, DockerContainerConfig> containers) throws InterruptedException, InfrastructureException { if (executor.getActiveCount() + containers.size() > executor.getMaximumPoolSize()) { LOG.warn( String.format( "Maximum parallel images preparing threads reached. Some images will be queued.\n" + " Workspace machines count is %s. If problem persists, increase %s property value.", containers.size(), PARALLEL_PULL_PROPERTY_NAME)); } Map<String, String> machineToImageNames = new ConcurrentHashMap<>(containers.size()); CompletableFuture<Void> firstFailed = new CompletableFuture<>(); List<CompletableFuture<Void>> taskFutures = containers .entrySet() .stream() .map( e -> CompletableFuture.supplyAsync( (Supplier<Void>) () -> { try { machineToImageNames.put( e.getKey(), prepareImage(e.getKey(), e.getValue())); } catch (InternalInfrastructureException | SourceNotFoundException ex) { firstFailed.completeExceptionally(ex); } return null; }, executor)) .collect(toList()); CompletableFuture all = CompletableFuture.allOf(taskFutures.toArray(new CompletableFuture[taskFutures.size()])); try { CompletableFuture.anyOf(all, firstFailed).get(); } catch (ExecutionException e) { try { throw e.getCause(); } catch (InfrastructureException rethrow) { throw rethrow; } catch (Throwable thr) { throw new InternalInfrastructureException("Unable to build or pull image", thr); } } return machineToImageNames; }
Source:
public void authorizeStreamRead(final EventType eventType) throws AccessDeniedException { if (eventType.getAuthorization() == null) { return; } final Resource resource = new EventTypeResource(eventType.getName(), eventType.getAuthorization()); try { if (!authorizationService.isAuthorized(null, AuthorizationService.Operation.READ, resource)) { throw new AccessDeniedException(null, AuthorizationService.Operation.READ, resource); } } catch (final PluginException e) { throw new ServiceTemporarilyUnavailableException("Error calling authorization plugin", e); } }

Target:
public void authorizeStreamRead(final EventType eventType) throws AccessDeniedException { if (eventType.getAuthorization() == null) { return; } final Resource resource = new EventTypeResource(eventType.getName(), eventType.getAuthorization()); try { if (!authorizationService.isAuthorized(AuthorizationService.Operation.READ, resource)) { throw new AccessDeniedException(AuthorizationService.Operation.READ, resource); } } catch (final PluginException e) { throw new ServiceTemporarilyUnavailableException("Error calling authorization plugin", e); } }
Source:
private static boolean validEmail(String email) { return true; }

Target:
private static boolean validEmail(String email) { return Patterns.EMAIL_ADDRESS.matcher(email).matches(); }