auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void whenPromptHasAnswer_answerTextViewShowsCorrectDate() { FormEntryPrompt prompt = promptWithQuestionDefAndAnswer(questionDef, new DateData(dateAnswer.toDate())); DatePickerDetails datePickerDetails = DateTimeWidgetUtils.getDatePickerDetails(prompt.getQuestion().getAppearanceAttr()); DateWidget widget = createWidget(prompt); assertEquals(widget.binding.widgetAnswerText.getText(), DateTimeWidgetUtils.getDateTimeLabel(dateAnswer.toDate(), datePickerDetails, false, widget.getContext())); }

Target:
public void whenPromptHasAnswer_answerTextViewShowsCorrectDate() { FormEntryPrompt prompt = promptWithQuestionDefAndAnswer(questionDef, new DateData(dateAnswer.toDate())); DatePickerDetails datePickerDetails = DateTimeWidgetUtils.getDatePickerDetails(prompt.getQuestion().getAppearanceAttr()); DateWidget widget = createWidget(prompt); assertEquals(widget.binding.dateAnswerText.getText(), DateTimeWidgetUtils.getDateTimeLabel(dateAnswer.toDate(), datePickerDetails, false, widget.getContext())); }
Source:
public File getStudioClasspathLocation() { return new File(OServer.class.getProtectionDomain() .getCodeSource() .getLocation() .getPath()).toPath().resolveSibling("orientdb-studio-2.2.0.jar").toFile(); }

Target:
public File getStudioClasspathLocation() { return new File(OServer.class.getProtectionDomain() .getCodeSource() .getLocation() .getPath()).toPath() .resolveSibling(String.format("orientdb-studio-%s.jar", ORIENTDB_STUDO_VERSION)) .toFile(); }
Source:
private HashSet<ASTMethodCallExpression> getPreviousMethodCalls(final AbstractApexNode<?> self) { final HashSet<ASTMethodCallExpression> innerMethodCalls = new HashSet<>(); final ASTBlockStatement blockStatement = self.getFirstParentOfType(ASTBlockStatement.class); if (blockStatement != null) { List<ASTMethodCallExpression> nodes = blockStatement.findDescendantsOfType(ASTMethodCallExpression.class); mapCallToMethodDecl(self, innerMethodCalls, nodes); } final List<ASTMethod> specialMethods = findSpecialMethods(self); for (ASTMethod method : specialMethods) { innerMethodCalls.addAll(method.findDescendantsOfType(ASTMethodCallExpression.class)); } mapCallToMethodDecl(self, innerMethodCalls, new ArrayList<ASTMethodCallExpression>(innerMethodCalls)); return innerMethodCalls; }

Target:
private HashSet<ASTMethodCallExpression> getPreviousMethodCalls(final AbstractApexNode<?> self) { final HashSet<ASTMethodCallExpression> innerMethodCalls = new HashSet<>(); final ASTMethod outerMethod = self.getFirstParentOfType(ASTMethod.class); if (outerMethod != null) { final ASTBlockStatement blockStatement = outerMethod.getFirstChildOfType(ASTBlockStatement.class); recursivelyEvaluateCRUDMethodCalls(self, innerMethodCalls, blockStatement); final List<ASTMethod> constructorMethods = findConstructorlMethods(self); for (ASTMethod method : constructorMethods) { innerMethodCalls.addAll(method.findDescendantsOfType(ASTMethodCallExpression.class)); } mapCallToMethodDecl(self, innerMethodCalls, new ArrayList<ASTMethodCallExpression>(innerMethodCalls)); } return innerMethodCalls; }
Source:
private File createFile(String string) throws IOException { File f = File.createTempFile(string, "tdat"); files.add(f); return f; }

Target:
private File createFile(String string) throws IOException { trash.mkdirs(); File f = File.createTempFile(string, "tdat", trash); files.add(f); return f; }
Source:
public void passthroughProfileDoesNotContainFilterIdButDefaultWillBeUsed() { passthroughProfileContainsSupportedPropertiesTest(true, false, DEFAULT_GUID, INVALID_NETWORK_FILTER_ID); assertThat(validator.passthroughProfileContainsSupportedProperties(true), failsWith(EngineMessage.ACTION_TYPE_FAILED_PASSTHROUGH_PROFILE_CONTAINS_NOT_SUPPORTED_PROPERTIES)); }

Target:
public void passthroughProfileDoesNotContainFilterIdButDefaultWillBeUsed() { passthroughProfileContainsSupportedPropertiesTest(true, false, DEFAULT_GUID, null); assertThat(validator.passthroughProfileContainsSupportedProperties(true), failsWith(EngineMessage.ACTION_TYPE_FAILED_PASSTHROUGH_PROFILE_CONTAINS_NOT_SUPPORTED_PROPERTIES)); }
Source:
public String toString() { StringBuilder sb = new StringBuilder(1024); sb.append("<pool>"); if (minPoolSize != null) { sb.append("<").append(Pool.Tag.MIN_POOL_SIZE).append(">"); sb.append(minPoolSize); sb.append("</").append(Pool.Tag.MIN_POOL_SIZE).append(">"); } if (initialPoolSize != null) { sb.append("<").append(Pool.Tag.INITIAL_POOL_SIZE).append(">"); sb.append(initialPoolSize); sb.append("</").append(Pool.Tag.INITIAL_POOL_SIZE).append(">"); } if (maxPoolSize != null) { sb.append("<").append(Pool.Tag.MAX_POOL_SIZE).append(">"); sb.append(maxPoolSize); sb.append("</").append(Pool.Tag.MAX_POOL_SIZE).append(">"); } if (prefill != null) { sb.append("<").append(Pool.Tag.PREFILL).append(">"); sb.append(prefill); sb.append("</").append(Pool.Tag.PREFILL).append(">"); } if (fair != null) { sb.append("<").append(Pool.Tag.FAIR).append(">"); sb.append(fair); sb.append("</").append(Pool.Tag.CAPACITY).append(">"); } if (useStrictMin != null) { sb.append("<").append(Pool.Tag.USE_STRICT_MIN).append(">"); sb.append(useStrictMin); sb.append("</").append(Pool.Tag.USE_STRICT_MIN).append(">"); } if (flushStrategy != null) { sb.append("<").append(Pool.Tag.FLUSH_STRATEGY).append(">"); sb.append(flushStrategy); sb.append("</").append(Pool.Tag.FLUSH_STRATEGY).append(">"); } if (capacity != null) { sb.append("<").append(Pool.Tag.CAPACITY).append(">"); sb.append(capacity); sb.append("</").append(Pool.Tag.CAPACITY).append(">"); } sb.append("</pool>"); return sb.toString(); }

Target:
public String toString() { StringBuilder sb = new StringBuilder(1024); sb.append("<pool>"); if (minPoolSize != null) { sb.append("<").append(Pool.Tag.MIN_POOL_SIZE).append(">"); sb.append(minPoolSize); sb.append("</").append(Pool.Tag.MIN_POOL_SIZE).append(">"); } if (initialPoolSize != null) { sb.append("<").append(Pool.Tag.INITIAL_POOL_SIZE).append(">"); sb.append(initialPoolSize); sb.append("</").append(Pool.Tag.INITIAL_POOL_SIZE).append(">"); } if (maxPoolSize != null) { sb.append("<").append(Pool.Tag.MAX_POOL_SIZE).append(">"); sb.append(maxPoolSize); sb.append("</").append(Pool.Tag.MAX_POOL_SIZE).append(">"); } if (prefill != null) { sb.append("<").append(Pool.Tag.PREFILL).append(">"); sb.append(prefill); sb.append("</").append(Pool.Tag.PREFILL).append(">"); } if (useStrictMin != null) { sb.append("<").append(Pool.Tag.USE_STRICT_MIN).append(">"); sb.append(useStrictMin); sb.append("</").append(Pool.Tag.USE_STRICT_MIN).append(">"); } if (fair != null && !fair.equals(Defaults.FAIR)) { sb.append("<").append(Pool.Tag.FAIR).append(">"); sb.append(fair); sb.append("</").append(Pool.Tag.FAIR).append(">"); } if (flushStrategy != null) { sb.append("<").append(Pool.Tag.FLUSH_STRATEGY).append(">"); sb.append(flushStrategy); sb.append("</").append(Pool.Tag.FLUSH_STRATEGY).append(">"); } if (capacity != null) { sb.append("<").append(Pool.Tag.CAPACITY).append(">"); sb.append(capacity); sb.append("</").append(Pool.Tag.CAPACITY).append(">"); } sb.append("</pool>"); return sb.toString(); }
Source:
public void addResults(QueryStatusInfo statusInfo, QueryData data) { if (types.get() == null && statusInfo.getColumns() != null) { types.set(getTypes(statusInfo.getColumns())); } if (data.getData() != null) { checkState(types.get() != null, "Type information is missing"); List<Column> columns = statusInfo.getColumns(); for (List<Object> fields : data.getData()) { try { XContentBuilder dataBuilder = jsonBuilder().startObject(); for (int i = 0; i < fields.size(); i++) { Type type = types.get().get(i); Object value = convertValue(fields.get(i), type); dataBuilder.field(columns.get(i).getName(), value); } dataBuilder.endObject(); client.prepareIndex(tableName, "doc").setSource(dataBuilder.string(), JSON).get(); } catch (IOException e) { throw new UncheckedIOException("Failure loading data into Elasticsearch index: " + tableName, e); } } } }

Target:
public void addResults(QueryStatusInfo statusInfo, QueryData data) { if (types.get() == null && statusInfo.getColumns() != null) { types.set(getTypes(statusInfo.getColumns())); } if (data.getData() == null) { return; } checkState(types.get() != null, "Type information is missing"); List<Column> columns = statusInfo.getColumns(); for (List<Object> fields : data.getData()) { try { XContentBuilder dataBuilder = jsonBuilder().startObject(); for (int i = 0; i < fields.size(); i++) { Type type = types.get().get(i); Object value = convertValue(fields.get(i), type); dataBuilder.field(columns.get(i).getName(), value); } dataBuilder.endObject(); client.prepareIndex(tableName, "doc") .setSource(dataBuilder.string(), JSON) .get(); } catch (IOException e) { throw new UncheckedIOException("Error loading data into Elasticsearch index: " + tableName, e); } } }
Source:
public MutableFudgeMsg buildMessage(final FudgeSerializer serializer, final Trade trade) { if (trade instanceof TradeWrapper) { TradeWrapper tradeWrapper = (TradeWrapper) trade; DirectBeanFudgeBuilder<TradeWrapper> builder = new DirectBeanFudgeBuilder<>(JodaBeanUtils.metaBean(trade.getClass())); MutableFudgeMsg wrapperMsg = builder.buildMessage(serializer, tradeWrapper); FudgeSerializer.addClassHeader(wrapperMsg, trade.getClass()); return wrapperMsg; } else { final MutableFudgeMsg tradeMsg = buildMessageImpl(serializer, trade); tradeMsg.add(null, FudgeSerializer.TYPES_HEADER_ORDINAL, FudgeWireType.STRING, Trade.class.getName()); return tradeMsg; } }

Target:
public MutableFudgeMsg buildMessage(final FudgeSerializer serializer, final Trade trade) { final MutableFudgeMsg tradeMsg = buildMessageImpl(serializer, trade); tradeMsg.add(null, FudgeSerializer.TYPES_HEADER_ORDINAL, FudgeWireType.STRING, Trade.class.getName()); return tradeMsg; }
Source:
public void addKerberosAuthentication(UserEntity userEntity, String principalName, boolean persist) throws AmbariException { addAuthentication(userEntity, UserAuthenticationType.KERBEROS, principalName, new Validator() { @Override public void validate(UserEntity userEntity, String key) throws AmbariException { if (!CollectionUtils.isEmpty(userAuthenticationDAO.findByTypeAndKey(UserAuthenticationType.KERBEROS, key))) { throw new AmbariException("The authentication type already exists for this principal"); } } }, persist); }

Target:
public void addKerberosAuthentication(UserEntity userEntity, String principalName, boolean persist) throws AmbariException { addAuthentication(userEntity, UserAuthenticationType.KERBEROS, principalName, (user, key) -> { if (!CollectionUtils.isEmpty(userAuthenticationDAO.findByTypeAndKey(UserAuthenticationType.KERBEROS, key))) { throw new AmbariException("The authentication type already exists for this principal"); } }, persist); }
Source:
public InterpreterResult interpret(String st, InterpreterContext context) throws InterpreterException { assertVersion(); z.setInterpreterContext(context); z.setGui(context.getGui()); z.setNoteGui(context.getNoteGui()); InterpreterContext.set(context); jsc.setJobGroup(buildJobGroupId(context), buildJobDesc(context), false); jsc.setLocalProperty("spark.scheduler.pool", context.getLocalProperties().get("pool")); InterpreterOutput out = context.out; PrintStream scalaOut = Console.out(); PrintStream newOut = (out != null) ? new PrintStream(out) : null; Console.setOut(newOut); InterpreterResult result = interpreter.interpret(st, context); Console.setOut(scalaOut); return result; }

Target:
public InterpreterResult interpret(String st, InterpreterContext context) throws InterpreterException { if (isSparkVersionUnsupported()) { return unsupportedMessage; } z.setInterpreterContext(context); z.setGui(context.getGui()); z.setNoteGui(context.getNoteGui()); InterpreterContext.set(context); jsc.setJobGroup(buildJobGroupId(context), buildJobDesc(context), false); jsc.setLocalProperty("spark.scheduler.pool", context.getLocalProperties().get("pool")); InterpreterOutput out = context.out; PrintStream scalaOut = Console.out(); PrintStream newOut = (out != null) ? new PrintStream(out) : null; Console.setOut(newOut); InterpreterResult result = interpreter.interpret(st, context); Console.setOut(scalaOut); return result; }
Source:
protected void activate(Map<String, Object> parameters) { minThreads = (Integer) parameters.get(CONFIG_MIN_THREADS); maxThreads = (Integer) parameters.get(CONFIG_MAX_THREADS); keepAliveTimeout = (Integer) parameters.get(CONFIG_KEEP_ALIVE); queueSize = (Integer) parameters.get(CONFIG_QUEUE_SIZE); threadPool = new ThreadPoolExecutor(minThreads, maxThreads, keepAliveTimeout, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueSize), new NamedThreadFactory("jetty")); logger.info("jetty thread pool started with min threads {}, max threads {}", minThreads, maxThreads); }

Target:
protected void activate(Map<String, Object> parameters) { getConfigParameters(parameters); }
Source:
public void loadValues(IProject project) { Preferences prefs = DocCommentOwnerManager.getInstance().getPreferences(project); newLineAfterBrief.setSelection(prefs.getBoolean(DocCommentOwnerManager.DOXYGEN_NEW_LINE_AFTER_BRIEF, DocCommentOwnerManager.DEF_DOXYGEN_NEW_LINE_AFTER_BRIEF)); useBriefTag.setSelection(prefs.getBoolean(DocCommentOwnerManager.DOXYGEN_USE_BRIEF_TAG, DocCommentOwnerManager.DEF_DOXYGEN_USE_BRIEF_TAG)); useJavadocStyle.setSelection(prefs.getBoolean(DocCommentOwnerManager.DOXYGEN_USE_JAVADOC_TAGS, DocCommentOwnerManager.DEF_DOXYGEN_USE_JAVADOC_TAGS)); usePrePostTag.setSelection(prefs.getBoolean(DocCommentOwnerManager.DOXYGEN_USE_PRE_POST_TAGS, DocCommentOwnerManager.DEF_DOXYGEN_USE_PRE_POST_TAGS)); useStructuredCommands.setSelection(prefs.getBoolean(DocCommentOwnerManager.DOXYGEN_USE_STRUCTURED_COMMANDS, DocCommentOwnerManager.DEF_DOXYGEN_USE_STRUCTURED_COMMANDS)); }

Target:
public void loadValues(IProject project) { initialize(newLineAfterBrief, DocCommentOwnerManager.DOXYGEN_NEW_LINE_AFTER_BRIEF, project, DocCommentOwnerManager.DEF_DOXYGEN_NEW_LINE_AFTER_BRIEF); initialize(useBriefTag, DocCommentOwnerManager.DOXYGEN_USE_BRIEF_TAG, project, DocCommentOwnerManager.DEF_DOXYGEN_USE_BRIEF_TAG); initialize(useJavadocStyle, DocCommentOwnerManager.DOXYGEN_USE_JAVADOC_TAGS, project, DocCommentOwnerManager.DEF_DOXYGEN_USE_JAVADOC_TAGS); initialize(usePrePostTag, DocCommentOwnerManager.DOXYGEN_USE_PRE_POST_TAGS, project, DocCommentOwnerManager.DEF_DOXYGEN_USE_PRE_POST_TAGS); initialize(useStructuralCommands, DocCommentOwnerManager.DOXYGEN_USE_STRUCTURAL_COMMANDS, project, DocCommentOwnerManager.DEF_DOXYGEN_USE_STRUCTURED_COMMANDS); }
Source:
public Aggregator factorize(ColumnSelectorFactory metricFactory) { ValueType valueType = metricFactory.columnType(fieldName); if (valueType == null) { return Aggregators.noopAggregator(); } if (valueType == ValueType.FLOAT) { return new VarianceAggregator.FloatVarianceAggregator( name, metricFactory.makeFloatColumnSelector(fieldName) ); } if (valueType == ValueType.LONG) { return new VarianceAggregator.LongVarianceAggregator( name, metricFactory.makeLongColumnSelector(fieldName) ); } return new VarianceAggregator.ObjectVarianceAggregator( name, metricFactory.makeObjectColumnSelector(fieldName) ); }

Target:
public Aggregator factorize(ColumnSelectorFactory metricFactory) { ObjectColumnSelector selector = metricFactory.makeObjectColumnSelector(fieldName); if (selector == null) { return Aggregators.noopAggregator(); } if ("float".equalsIgnoreCase(inputType)) { return new VarianceAggregator.FloatVarianceAggregator( name, metricFactory.makeFloatColumnSelector(fieldName) ); } else if ("long".equalsIgnoreCase(inputType)) { return new VarianceAggregator.LongVarianceAggregator( name, metricFactory.makeLongColumnSelector(fieldName) ); } else if ("variance".equalsIgnoreCase(inputType)) { return new VarianceAggregator.ObjectVarianceAggregator(name, selector); } throw new IAE( "Incompatible type for metric[%s], expected a float, long or variance, got a %s", fieldName, inputType ); }
Source:
Point2D swtToPlot(int x, int y) { Rectangle sdArea = PlotFrame.this.getScreenDataArea(); final ValueAxis domainAxis = getChart().getXYPlot().getDomainAxis(); final ValueAxis rangeAxis = getChart().getXYPlot().getRangeAxis(); double xSize = domainAxis.getUpperBound() - domainAxis.getLowerBound(); double ySize = rangeAxis.getUpperBound() - rangeAxis.getLowerBound(); double relativeX = ((double) x - sdArea.x) / (sdArea.width); double relativeY = ((double) y - sdArea.y) / (sdArea.height); double realX = domainAxis.getLowerBound() + relativeX * xSize; double realY = rangeAxis.getUpperBound() - relativeY * ySize; return new Point2D.Double(realX, realY); }

Target:
private final Point2D swtToPlot(int x, int y) { Rectangle rectangle = PlotFrame.this.getScreenDataArea(); final ValueAxis domainAxis = getChart().getXYPlot().getDomainAxis(); final ValueAxis rangeAxis = getChart().getXYPlot().getRangeAxis(); final double widthInAxisUnits = domainAxis.getUpperBound() - domainAxis.getLowerBound(); final double heightInAxisUnits = rangeAxis.getUpperBound() - rangeAxis.getLowerBound(); double relativeX = ((double) x - rectangle.x) / (rectangle.width); double relativeY = ((double) y - rectangle.y) / (rectangle.height); double xPlot = domainAxis.getLowerBound() + relativeX * widthInAxisUnits; double yPlot = rangeAxis.getUpperBound() - relativeY * heightInAxisUnits; return new Point2D.Double(xPlot, yPlot); }
Source:
public static String extractDirNameFromAbsolutePath(String path) { if (path.endsWith("/") || path.endsWith(File.separator)) { path = path.substring(0, path.length() - 1); } int startIndex = path.lastIndexOf(File.separator); if (startIndex == -1) { startIndex = path.lastIndexOf("/"); } return path.substring(startIndex + 1, path.length()); }

Target:
public static String extractDirNameFromAbsolutePath(String path) { if (path.endsWith("/") || path.endsWith(File.separator)) { path = path.substring(0, path.length() - 1); } return FileUtil.stripPath(path); }
Source:
private void testResponseRate() { feedbackEditPage.clickNewQuestionButton(); feedbackEditPage.fillQuestionBox("new question"); feedbackEditPage.clickAddQuestionButton(); FeedbackResponseAttributes feedbackResponse = new FeedbackResponseAttributes( feedbackSessionName, courseId, "1", FeedbackQuestionType.TEXT, "tmms.test@gmail.tmt", Const.DEFAULT_SECTION, "alice.b.tmms@gmail.tmt", Const.DEFAULT_SECTION, new Text("Response from instructor to Alice")); BackDoor.createFeedbackResponse(feedbackResponse); ______TS("check response rate before editing question"); AppUrl feedbacksPageUrl = createUrl(Const.ActionURIs.INSTRUCTOR_FEEDBACKS_PAGE).withInstructorId(instructorId); InstructorFeedbacksPage feedbacksPage = AppPage.getNewPageInstance(browser, feedbacksPageUrl, InstructorFeedbacksPage.class); feedbacksPage.waitForPageToLoad(); assertEquals("1 / 1", feedbacksPage.getResponseValue(courseId, feedbackSessionName)); feedbackEditPage = getFeedbackEditPage(); feedbackEditPage.clickEditQuestionButton(1); feedbackEditPage.selectRecipientTypeForQuestion1("Other teams in the course"); feedbackEditPage.clickAndConfirmSaveForQuestion1(); ______TS("check response rate after editing question"); feedbacksPage = AppPage.getNewPageInstance(browser, feedbacksPageUrl, InstructorFeedbacksPage.class); feedbacksPage.waitForPageToLoad(); assertEquals("0 / 1", feedbacksPage.getResponseValue(courseId, feedbackSessionName)); feedbackEditPage = getFeedbackEditPage(); feedbackEditPage.clickAndConfirm(feedbackEditPage.getDeleteQuestionLink(1)); }

Target:
private void testResponseRate() { feedbackEditPage.clickNewQuestionButton(); feedbackEditPage.fillQuestionBox("new question"); feedbackEditPage.clickAddQuestionButton(); FeedbackResponseAttributes feedbackResponse = new FeedbackResponseAttributes( feedbackSessionName, courseId, "1", FeedbackQuestionType.TEXT, "tmms.test@gmail.tmt", Const.DEFAULT_SECTION, "alice.b.tmms@gmail.tmt", Const.DEFAULT_SECTION, new Text("Response from instructor to Alice")); BackDoor.createFeedbackResponse(feedbackResponse); ______TS("check response rate before editing question"); InstructorFeedbacksPage feedbacksPage = navigateToInstructorFeedbacksPage(); assertEquals("1 / 1", feedbacksPage.getResponseValue(courseId, feedbackSessionName)); feedbackEditPage = getFeedbackEditPage(); feedbackEditPage.clickEditQuestionButton(1); feedbackEditPage.selectRecipientTypeForQuestion1("Other teams in the course"); feedbackEditPage.clickAndConfirmSaveForQuestion1(); ______TS("check response rate after editing question"); feedbacksPage = navigateToInstructorFeedbacksPage(); assertEquals("0 / 1", feedbacksPage.getResponseValue(courseId, feedbackSessionName)); feedbackEditPage = getFeedbackEditPage(); feedbackEditPage.clickAndConfirm(feedbackEditPage.getDeleteQuestionLink(1)); }
Source:
public static boolean publishHTMLPage(IHTMLPage htmlPage, List relatedNotPublished, User user, boolean respectFrontendRoles ) throws WebAssetException, DotSecurityException, DotDataException { Logger.debug(PublishFactory.class, "*****I'm an HTML Page -- Publishing"); ContentletAPI contentletAPI = APILocator.getContentletAPI(); for ( Object asset : relatedNotPublished ) { if ( asset instanceof Contentlet ) { Logger.debug( PublishFactory.class, "*****I'm an HTML Page -- Publishing my Contentlet Child=" + ((Contentlet) asset).getInode() ); try { Contentlet c = (Contentlet) asset; if ( !APILocator.getWorkflowAPI().findSchemeForStruct( c.getStructure() ).isMandatory() ) { contentletAPI.publish( (Contentlet) asset, user, false ); ContentletServices.invalidateLive(c); } } catch ( DotSecurityException e ) { Logger.debug( PublishFactory.class, "publish html page: User has no permission to publish the content inode = " + ((Contentlet) asset).getInode() + " in the page, skipping it." ); } } else if ( asset instanceof Template ) { Logger.debug( PublishFactory.class, "*****I'm an HTML Page -- Publishing Template =" + ((Template) asset).getInode() ); publishAsset( (Template) asset, user, respectFrontendRoles, false ); } } PageServices.invalidateAll(htmlPage); if ( htmlPage instanceof HTMLPageAsset ) { APILocator.getContentletAPI().publish( (HTMLPageAsset) htmlPage, user, false ); } return true; }

Target:
public static boolean publishHTMLPage(IHTMLPage htmlPage, List relatedNotPublished, User user, boolean respectFrontendRoles ) throws WebAssetException, DotSecurityException, DotDataException { Logger.debug(PublishFactory.class, "*****I'm an HTML Page -- Publishing"); ContentletAPI contentletAPI = APILocator.getContentletAPI(); for ( Object asset : relatedNotPublished ) { if ( asset instanceof Contentlet ) { Logger.debug( PublishFactory.class, "*****I'm an HTML Page -- Publishing my Contentlet Child=" + ((Contentlet) asset).getInode() ); try { Contentlet contentlet = (Contentlet) asset; if ( !APILocator.getWorkflowAPI().findSchemeForStruct( contentlet.getStructure() ).isMandatory() ) { contentletAPI.publish( (Contentlet) asset, user, false ); ContentletServices.invalidateLive(contentlet); } } catch ( DotSecurityException e ) { Logger.debug( PublishFactory.class, "publish html page: User has no permission to publish the content inode = " + ((Contentlet) asset).getInode() + " in the page, skipping it." ); } } else if ( asset instanceof Template ) { Logger.debug( PublishFactory.class, "*****I'm an HTML Page -- Publishing Template =" + ((Template) asset).getInode() ); publishAsset( (Template) asset, user, respectFrontendRoles, false ); } } PageServices.invalidateAll(htmlPage); if ( htmlPage instanceof HTMLPageAsset ) { APILocator.getContentletAPI().publish( (HTMLPageAsset) htmlPage, user, false ); } return true; }
Source:
public EncounterTransaction save(EncounterTransaction encounterTransaction) { EncounterTransaction updatedEncounterTransaction = null; DbSession session = sessionFactory.getCurrentSession(); FlushMode flushMode = session.getFlushMode(); session.setFlushMode(FlushMode.MANUAL); try { updatedEncounterTransaction = saveInternal(encounterTransaction); } finally { session.setFlushMode(flushMode); } return updatedEncounterTransaction; }

Target:
public EncounterTransaction save(EncounterTransaction encounterTransaction) { EncounterTransaction updatedEncounterTransaction = null; FlushMode flushMode = DbSessionUtil.getCurrentFlushMode(); DbSessionUtil.setManualFlushMode(); try { updatedEncounterTransaction = saveInternal(encounterTransaction); } finally { DbSessionUtil.setFlushMode(flushMode); } return updatedEncounterTransaction; }
Source:
public void initParam(Object obj) { OptionsParam options = (OptionsParam) obj; OptionsParamCertificate certParam = options.getCertificateParam(); if(overrideEnableClientCertificate) { certParam.setEnableCertificate(true); useClientCertificateCheckBox.setSelected(certParam.isUseClientCert()); useClientCertificateCheckBoxActionPerformed(null); overrideEnableClientCertificate = false; } else { useClientCertificateCheckBox.setSelected(certParam.isUseClientCert()); } enableUnsafeSSLRenegotiationCheckBox.setSelected(certParam.isAllowUnsafeSslRenegotiation()); }

Target:
public void initParam(Object obj) { OptionsParam options = (OptionsParam) obj; OptionsParamCertificate certParam = options.getCertificateParam(); if(overrideEnableClientCertificate) { certParam.setEnableCertificate(true); overrideEnableClientCertificate = false; } useClientCertificateCheckBox.setSelected(certParam.isUseClientCert()); useClientCertificateCheckBoxActionPerformed(null); enableUnsafeSSLRenegotiationCheckBox.setSelected(certParam.isAllowUnsafeSslRenegotiation()); }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (backupService == null) { SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); } String url = ((HttpServletRequest) request).getRequestURI(); if (isFilesAPI(url)) { chain.doFilter(request, response); return; } if (isBackupFinishJsonUrl(url)) { ((HttpServletResponse) response).setHeader("Cache-Control", "private, max-age=0, no-cache"); ((HttpServletResponse) response).setDateHeader("Expires", 0); generateResponseForIsBackupFinishedAPI(response); return; } if (backupService.isBackingUp()) { ((HttpServletResponse) response).setHeader("Cache-Control", "private, max-age=0, no-cache"); ((HttpServletResponse) response).setDateHeader("Expires", 0); if (isAPIUrl(url) && !isMessagesJson(url)) { generateAPIResponse(request, response); } else { generateHTMLResponse(response); } ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { chain.doFilter(request, response); } }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (backupService == null) { SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); } String url = ((HttpServletRequest) request).getRequestURI(); if (isBackupFinishJsonUrl(url)) { ((HttpServletResponse) response).setHeader("Cache-Control", "private, max-age=0, no-cache"); ((HttpServletResponse) response).setDateHeader("Expires", 0); generateResponseForIsBackupFinishedAPI(response); return; } if (backupService.isBackingUp()) { ((HttpServletResponse) response).setHeader("Cache-Control", "private, max-age=0, no-cache"); ((HttpServletResponse) response).setDateHeader("Expires", 0); if (isAPIUrl(url) && !isMessagesJson(url)) { generateAPIResponse(request, response); } else { generateHTMLResponse(response); } ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { chain.doFilter(request, response); } }
Source:
public InternalCacheEntry<WrappedBytes, WrappedBytes> put(WrappedBytes key, InternalCacheEntry<WrappedBytes, WrappedBytes> value) { InternalCacheEntry<WrappedBytes, WrappedBytes> returnedValue; int hashCode = key.hashCode(); boolean shouldFree = true; long newAddress = offHeapEntryFactory.create(key, hashCode, value.getValue(), value.getMetadata()); try { int lockOffset = getLockOffset(hashCode); Lock lock = locks.getLockWithOffset(lockOffset).writeLock(); lock.lock(); try { checkDeallocation(); ensureTransferred(lockOffset); int memoryOffset = getMemoryOffset(hashCode); long address = memoryLookup.getMemoryAddressOffset(memoryOffset); returnedValue = performPut(address, 0, newAddress, key, memoryOffset, true, false); shouldFree = false; } finally { lock.unlock(); } } finally { if (shouldFree) { allocator.deallocate(newAddress, offHeapEntryFactory.getSize(newAddress, false)); } } if (returnedValue == null) { checkResize(); } return returnedValue; }

Target:
public InternalCacheEntry<WrappedBytes, WrappedBytes> put(WrappedBytes key, InternalCacheEntry<WrappedBytes, WrappedBytes> value) { InternalCacheEntry<WrappedBytes, WrappedBytes> returnedValue; int hashCode = key.hashCode(); int lockOffset = getLockOffset(hashCode); Lock lock = locks.getLockWithOffset(lockOffset).writeLock(); lock.lock(); try { checkDeallocation(); ensureTransferred(lockOffset); int memoryOffset = getMemoryOffset(hashCode); long address = memoryLookup.getMemoryAddressOffset(memoryOffset); long newAddress = offHeapEntryFactory.create(key, hashCode, value.getValue(), value.getMetadata()); returnedValue = performPut(address, 0, newAddress, key, memoryOffset, true, false); } finally { lock.unlock(); } if (returnedValue == null) { checkResize(); } return returnedValue; }
Source:
public void batchDelete(List<Entitlement> entitlements) { for (Entitlement ent : entitlements) { log.debug("Deleting entitlement: " + ent); log.debug("certs.size = " + ent.getCertificates().size()); for (EntitlementCertificate cert : ent.getCertificates()) { getEntityManager().remove(cert); } ent.getCertificates().clear(); getEntityManager().remove(ent); } for (Entitlement ent : entitlements) { ent.getCertificates().clear(); ent.getConsumer().getEntitlements().remove(ent); } }

Target:
public void batchDelete(List<Entitlement> entitlements) { for (Entitlement ent : entitlements) { log.debug("Deleting entitlement: {}", ent); log.debug("certs.size = {}", ent.getCertificates().size()); for (EntitlementCertificate cert : ent.getCertificates()) { getEntityManager().remove(cert); } ent.getCertificates().clear(); getEntityManager().remove(ent); } for (Entitlement ent : entitlements) { ent.getCertificates().clear(); ent.getConsumer().getEntitlements().remove(ent); } }
Source:
public void extend() { BackupFilesManager backupFilesManager = new BackupFilesManager( config.getStringProperty(MESSAGES_LOCAL_STORAGE_DIRECTORY), clock); if (config.getBooleanProperty(MESSAGES_LOCAL_STORAGE_V2_MIGRATION_ENABLED)) { List<File> temporaryBackupV2Files = backupFilesManager.getTemporaryBackupV2Files(); hooksHandler.addStartupHook((s) -> { temporaryBackupV2Files.forEach(f -> loadTemporaryBackupV2Messages(backupFilesManager, f)); backupMessagesLoader.clearTopicsAvailabilityCache(); }); } backupFilesManager.rolloverBackupFileIfExists(); List<File> rolledBackupFiles = backupFilesManager.getRolledBackupFiles(); if (!rolledBackupFiles.isEmpty()) { logger.info("Backup files were found. Number of files: {}. Files: {}", rolledBackupFiles.size(), rolledBackupFiles.stream().map(File::getName).collect(joining(", "))); hooksHandler.addStartupHook((s) -> { rolledBackupFiles.forEach(f -> loadOldMessages(backupFilesManager, f)); backupMessagesLoader.clearTopicsAvailabilityCache(); }); } if (config.getBooleanProperty(MESSAGES_LOCAL_STORAGE_ENABLED)) { int backupStorageSizeInBytes = config.getIntProperty(MESSAGES_LOCAL_STORAGE_SIZE_MB) * MEGABYTES_TO_BYTES_MULTIPLIER; int entries = backupStorageSizeInBytes / config.getIntProperty(MESSAGES_LOCAL_STORAGE_AVERAGE_MESSAGE_SIZE); int avgMessageSize = config.getIntProperty(MESSAGES_LOCAL_STORAGE_AVERAGE_MESSAGE_SIZE); MessageRepository repository = config.getBooleanProperty(MESSAGES_LOCAL_STORAGE_SIZE_REPORTING_ENABLED) ? ChronicleMapMessageRepository.create(backupFilesManager.getCurrentBackupFile(), hermesMetrics, entries, avgMessageSize) : ChronicleMapMessageRepository.create(backupFilesManager.getCurrentBackupFile(), entries, avgMessageSize); BrokerListener brokerListener = new BrokerListener(repository); listeners.addAcknowledgeListener(brokerListener); listeners.addErrorListener(brokerListener); listeners.addTimeoutListener(brokerListener); } }

Target:
public void extend() { BackupFilesManager backupFilesManager = new BackupFilesManager( config.getStringProperty(MESSAGES_LOCAL_STORAGE_DIRECTORY), clock); long backupStorageSizeInBytes = config.getLongProperty(MESSAGES_LOCAL_BUFFERED_STORAGE_SIZE); entries = (int) (backupStorageSizeInBytes / config.getIntProperty(MESSAGES_LOCAL_STORAGE_AVERAGE_MESSAGE_SIZE)); avgMessageSize = config.getIntProperty(MESSAGES_LOCAL_STORAGE_AVERAGE_MESSAGE_SIZE); if (config.getBooleanProperty(MESSAGES_LOCAL_STORAGE_V2_MIGRATION_ENABLED)) { loadTemporaryBackupV2Files(backupFilesManager); } backupFilesManager.rolloverBackupFileIfExists(); List<File> rolledBackupFiles = backupFilesManager.getRolledBackupFiles(); if (!rolledBackupFiles.isEmpty()) { rollBackupFiles(backupFilesManager, rolledBackupFiles); } if (config.getBooleanProperty(MESSAGES_LOCAL_STORAGE_ENABLED)) { enableLocalStorage(backupFilesManager); } }
Source:
public static void createQueue(String projectId, String locationId, String queueId) throws Exception { try (CloudTasksClient client = CloudTasksClient.create()) { String parent = LocationName.of(projectId, locationId).toString(); String queuePath = QueueName.of(projectId, locationId, queueId).toString(); Queue queue = client.createQueue(parent, Queue.newBuilder().setName(queuePath).build()); System.out.println("Queue created: " + queue.getName()); } }

Target:
public static void createQueue(String projectId, String locationId, String queueId) throws IOException { try (CloudTasksClient client = CloudTasksClient.create()) { String parent = LocationName.of(projectId, locationId).toString(); String queuePath = QueueName.of(projectId, locationId, queueId).toString(); Queue queue = client.createQueue(parent, Queue.newBuilder().setName(queuePath).build()); System.out.println("Queue created: " + queue.getName()); } }
Source:
public QueryControlResult create(final Tuple<String, AvroOperatorChainDag> tuple) { final QueryControlResult queryControlResult = new QueryControlResult(); queryControlResult.setQueryId(tuple.getKey()); try { planStore.saveAvroOpChainDag(tuple); final LogicalAndExecutionDag logicalAndExecutionDag = dagGenerator.generate(tuple); final String queryId = tuple.getKey(); logicalDagMap.putIfAbsent(queryId, logicalAndExecutionDag.getLogicalDag()); final String groupId = tuple.getValue().getGroupId(); if (!groupInfoMap.containsKey(groupId)) { groupInfoMap.put(groupId, Tang.Factory.getTang().newInjector().getInstance(GroupInfo.class)); } groupInfoMap.get(groupId).addQueryIdToGroup(queryId); queryStarter.start(logicalAndExecutionDag.getExecutionDag()); queryControlResult.setIsSuccess(true); queryControlResult.setMsg(ResultMessage.submitSuccess(tuple.getKey())); return queryControlResult; } catch (final Exception e) { LOG.log(Level.SEVERE, "An exception occurred while starting {0} query: {1}", new Object[] {tuple.getKey(), e.getMessage()}); queryControlResult.setIsSuccess(false); queryControlResult.setMsg(e.getMessage()); return queryControlResult; } }

Target:
public QueryControlResult create(final Tuple<String, AvroOperatorChainDag> tuple) { final QueryControlResult queryControlResult = new QueryControlResult(); queryControlResult.setQueryId(tuple.getKey()); try { planStore.saveAvroOpChainDag(tuple); final LogicalAndExecutionDag logicalAndExecutionDag = dagGenerator.generate(tuple); final String queryId = tuple.getKey(); logicalDagMap.putIfAbsent(queryId, logicalAndExecutionDag.getLogicalDag()); final String groupId = tuple.getValue().getGroupId(); if (!groupInfoMap.containsKey(groupId)) { groupInfoMap.putIfAbsent(groupId, Tang.Factory.getTang().newInjector().getInstance(GroupInfo.class)); } groupInfoMap.get(groupId).addQueryIdToGroup(queryId); queryStarter.start(logicalAndExecutionDag.getExecutionDag()); queryControlResult.setIsSuccess(true); queryControlResult.setMsg(ResultMessage.submitSuccess(tuple.getKey())); return queryControlResult; } catch (final Exception e) { LOG.log(Level.SEVERE, "An exception occurred while starting {0} query: {1}", new Object[] {tuple.getKey(), e.toString()}); queryControlResult.setIsSuccess(false); queryControlResult.setMsg(e.getMessage()); return queryControlResult; } }
Source:
private UserLayer store(SimpleFeatureCollection fc, String uuid, Map<String, String> formParams) throws ActionParamsException { try { UserLayer userLayer = createUserLayer(fc, uuid, formParams); UserLayerStyle userLayerStyle = createUserLayerStyle(formParams); List<UserLayerData> userLayerDataList = UserLayerDataService.createUserLayerData(fc, uuid); userLayer.setFeatures_count(userLayerDataList.size()); userLayer.setFeatures_skipped(fc.size() - userLayerDataList.size()); userLayerService.insertUserLayer(userLayer, userLayerStyle, userLayerDataList); return userLayer; } catch (JSONException e) { throw new ActionParamsException("Failed to encode feature as GeoJSON"); } catch (ServiceException e) { throw new ActionParamsException("Failed to store features to database", UserLayerHandlerHelper.createErrorJSON(e.getMessage())); } }

Target:
private UserLayer store(SimpleFeatureCollection fc, String uuid, Map<String, String> formParams) throws UserLayerException { UserLayer userLayer = createUserLayer(fc, uuid, formParams); UserLayerStyle userLayerStyle = createUserLayerStyle(formParams); List<UserLayerData> userLayerDataList = UserLayerDataService.createUserLayerData(fc, uuid); userLayer.setFeatures_count(userLayerDataList.size()); userLayer.setFeatures_skipped(fc.size() - userLayerDataList.size()); userLayerService.insertUserLayer(userLayer, userLayerStyle, userLayerDataList); return userLayer; }
Source:
private void clearRoutingDataPath() { for (String zkRealm : _baseAccessor .getChildNames(MetadataStoreRoutingConstants.ROUTING_DATA_PATH, AccessOption.PERSISTENT)) { _baseAccessor.remove(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + zkRealm, AccessOption.PERSISTENT); } }

Target:
private void clearRoutingDataPath() throws Exception { Assert.assertTrue(TestHelper.verify(() -> { for (String zkRealm : _zkClient .getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { _zkClient.delete(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + zkRealm); } return _zkClient.getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH).isEmpty(); }, TestHelper.WAIT_DURATION), "Routing data path should be deleted after the tests."); }
Source:
private Gateway3DSAuthorisationResponse authorise3DSSource(Auth3dsResponseGatewayRequest request) { try { Response authorisationResponse = createChargeFor3DSSource(request, request.getTransactionId().get()); StripeAuthorisationResponse stripeAuthResponse = new StripeAuthorisationResponse(authorisationResponse.readEntity(StripeCreateChargeResponse.class)); return Gateway3DSAuthorisationResponse.of(stripeAuthResponse.authoriseStatus(), stripeAuthResponse.getTransactionId()); } catch (GatewayClientException e) { Response response = e.getResponse(); int status = response.getStatus(); if (status == HttpStatus.SC_UNAUTHORIZED) { Gateway3DSAuthorisationResponse.of(BaseAuthoriseResponse.AuthoriseStatus.ERROR); } StripeErrorResponse stripeErrorResponse = response.readEntity(StripeErrorResponse.class); String errorId = UUID.randomUUID().toString(); logger.error("Authorisation failed for charge {}. Failure code from Stripe: {}, failure message from Stripe: {}. ErrorId: {}. Response code from Stripe: {}", request.getChargeExternalId(), stripeErrorResponse.getError().getCode(), stripeErrorResponse.getError().getMessage(), errorId, response.getStatus()); return Gateway3DSAuthorisationResponse.of(BaseAuthoriseResponse.AuthoriseStatus.REJECTED); } catch (DownstreamException e) { logger.error(format("Unexpected HTTP status code %s from gateway, error=[%s]", e.getStatusCode(), e.getMessage()), e); return Gateway3DSAuthorisationResponse.of(BaseAuthoriseResponse.AuthoriseStatus.EXCEPTION); } catch (GatewayException e) { logger.error(format("Authorisation exception for gateway url=%s, [cause=%s]", e.getUrl(), e.getCause()), e); return Gateway3DSAuthorisationResponse.of(BaseAuthoriseResponse.AuthoriseStatus.EXCEPTION); } }

Target:
private Gateway3DSAuthorisationResponse authorise3DSSource(Auth3dsResponseGatewayRequest request) { try { Response authorisationResponse = createChargeFor3DSSource(request, request.getTransactionId().get()); StripeAuthorisationResponse stripeAuthResponse = new StripeAuthorisationResponse(authorisationResponse.readEntity(StripeCreateChargeResponse.class)); return Gateway3DSAuthorisationResponse.of(stripeAuthResponse.authoriseStatus(), stripeAuthResponse.getTransactionId()); } catch (GatewayClientException e) { Response response = e.getResponse(); if (response.getStatus() == HttpStatus.SC_UNAUTHORIZED) { return Gateway3DSAuthorisationResponse.of(BaseAuthoriseResponse.AuthoriseStatus.ERROR); } StripeErrorResponse stripeErrorResponse = response.readEntity(StripeErrorResponse.class); logger.error("3DS Authorisation failed for charge {}. Failure code from Stripe: {}, failure message from Stripe: {}. Response code from Stripe: {}", request.getChargeExternalId(), stripeErrorResponse.getError().getCode(), stripeErrorResponse.getError().getMessage(), response.getStatus()); return Gateway3DSAuthorisationResponse.of(BaseAuthoriseResponse.AuthoriseStatus.REJECTED); } catch (DownstreamException | GatewayException e) { return Gateway3DSAuthorisationResponse.of(BaseAuthoriseResponse.AuthoriseStatus.EXCEPTION); } }
Source:
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_pocketpaint_more_options, menu); presenter.removeMoreOptionsItems(); return true; }

Target:
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_pocketpaint_more_options, menu); presenter.removeMoreOptionsItems(menu); return true; }
Source:
Optional<byte []> modifyIfNecessaryDeploymentHostCount(DeploymentType deployment, int hostCount) { Optional<byte[]> deploymentBytes = Optional.empty(); if ((deployment.getCluster().getKfactor()+1) > hostCount) { VoltDB.crashLocalVoltDB( "Number cluster members " + hostCount + " must greater than ksafety " + deployment.getCluster().getKfactor(), false, null ); return null; } if (deployment.getCluster().getHostcount() != hostCount) { deployment.getCluster().setHostcount(hostCount); String remarshalled = null; try { remarshalled = CatalogUtil.getDeployment(deployment, true ); } catch (IOException|RuntimeException e) { VoltDB.crashLocalVoltDB("Unable to marshal deployment configuration", false, e); return null; } deploymentBytes = Optional.of(remarshalled.getBytes(StandardCharsets.UTF_8)); try (FileWriter fw = new FileWriter(getConfigLogDeployment())) { fw.write(remarshalled); } catch (IOException|RuntimeException e) { VoltDB.crashLocalVoltDB("Unable to marshal deployment configuration", false, e); return null; } } return deploymentBytes; }

Target:
Optional<byte []> modifyIfNecessaryDeploymentHostCount(DeploymentType deployment, int hostCount) { Optional<byte[]> deploymentBytes = Optional.empty(); if ((deployment.getCluster().getKfactor()+1) > hostCount) { VoltDB.crashLocalVoltDB( "Number of cluster members " + hostCount + " must greater than ksafety " + deployment.getCluster().getKfactor(), false, null ); return Optional.empty(); } if (deployment.getCluster().getHostcount() != hostCount) { deployment.getCluster().setHostcount(hostCount); String remarshalled = null; try { remarshalled = CatalogUtil.getDeployment(deployment, true ); } catch (IOException|RuntimeException e) { VoltDB.crashLocalVoltDB("Unable to marshal deployment configuration", false, e); return Optional.empty(); } deploymentBytes = Optional.of(remarshalled.getBytes(StandardCharsets.UTF_8)); try (FileWriter fw = new FileWriter(getConfigLogDeployment())) { fw.write(remarshalled); } catch (IOException|RuntimeException e) { VoltDB.crashLocalVoltDB("Unable to marshal deployment configuration", false, e); return Optional.empty(); } } return deploymentBytes; }
Source:
public static String removeTimezone(String timeWithTimezone) throws CoreException { Matcher mb = PATTERN_TIME.matcher(timeWithTimezone); if (mb.find()) { return mb.group(); } throw new CoreException(new Status(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, timeWithTimezone + " is not a valide time")); }

Target:
public static String removeTimezone(String timeWithTimezone) throws CoreException { Matcher matcher = TIME_STAMP_PATTERN.matcher(timeWithTimezone); if (matcher.find()) { return matcher.group(); } throw new CoreException(new Status(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, NLS.bind( "{0} is not a valid time", timeWithTimezone))); }
Source:
private BufferedReader createBufferedReader(FileEntry fileEntry) throws IOException { if (fileEntry.file.exists() && fileEntry.file.canRead() && fileEntry.file.isFile()) { FileInputStream fis = new FileInputStream(fileEntry.file); InputStreamReader isr = null; String charsetName = fileEntry.charSetEncoding; if(!JOrphanUtils.isBlank(charsetName)) { isr = new InputStreamReader(fis, charsetName); } else { isr = new InputStreamReader(fis); } return new BufferedReader(isr); } else { throw new IllegalArgumentException("File "+ fileEntry.file.getName()+ " must exist and be readable"); } }

Target:
private BufferedReader createBufferedReader(FileEntry fileEntry) throws IOException { if (!fileEntry.file.canRead() || !fileEntry.file.isFile()) { throw new IllegalArgumentException("File "+ fileEntry.file.getName()+ " must exist and be readable"); } FileInputStream fis = new FileInputStream(fileEntry.file); InputStreamReader isr = null; String charsetName = fileEntry.charSetEncoding; if(!JOrphanUtils.isBlank(charsetName)) { isr = new InputStreamReader(fis, charsetName); } else { isr = new InputStreamReader(fis); } return new BufferedReader(isr); }
Source:
private CastType getCastType(final Type castFrom, final Type castTo) { String cast = castFrom + " " + castTo; switch (cast) { case "INT_TYPE STRING_TYPE": case "FLOAT_TYPE STRING_TYPE": case "DOUBLE_TYPE STRING_TYPE": case "LONG_TYPE STRING_TYPE": case "DATETIME_TYPE STRING_TYPE": return CastType.TOSTR; case "LONG_TYPE INT_TYPE": return CastType.LONGTOINT; case "FLOAT_TYPE INT_TYPE": case "DOUBLE_TYPE INT_TYPE": return CastType.FLOATSTOINT; case "INT_TYPE FLOAT_TYPE": case "LONG_TYPE FLOAT_TYPE": case "DOUBLE_TYPE FLOAT_TYPE": return CastType.NUMTOFLOAT; case "INT_TYPE DOUBLE_TYPE": case "LONG_TYPE DOUBLE_TYPE": case "FLOAT_TYPE DOUBLE_TYPE": return CastType.NUMTODOUBLE; case "INT_TYPE LONG_TYPE": return CastType.INTTOLONG; case "FLOAT_TYPE LONG_TYPE": case "DOUBLE_TYPE LONG_TYPE": return CastType.FLOATSTOLONG; case "STRING_TYPE INT_TYPE": return CastType.STRTOINT; case "STRING_TYPE FLOAT_TYPE": return CastType.STRTOFLOAT; case "STRING_TYPE DOUBLE_TYPE": return CastType.STRTODOUBLE; case "STRING_TYPE LONG_TYPE": return CastType.STRTOLONG; default: break; } return CastType.UNSUPPORTED; }

Target:
private CastType getCastType(final Type castFrom, final Type castTo) { switch (castFrom + "|" + castTo) { case "INT_TYPE|STRING_TYPE": case "FLOAT_TYPE|STRING_TYPE": case "DOUBLE_TYPE|STRING_TYPE": case "LONG_TYPE|STRING_TYPE": case "DATETIME_TYPE|STRING_TYPE": return CastType.TO_STR; case "LONG_TYPE|INT_TYPE": return CastType.LONG_TO_INT; case "FLOAT_TYPE|INT_TYPE": case "DOUBLE_TYPE|INT_TYPE": return CastType.FLOATS_TO_INT; case "INT_TYPE|FLOAT_TYPE": case "LONG_TYPE|FLOAT_TYPE": return CastType.INT_OR_LONG_TO_FLOAT; case "DOUBLE_TYPE|FLOAT_TYPE": return CastType.DOUBLE_TO_FLOAT; case "INT_TYPE|DOUBLE_TYPE": case "LONG_TYPE|DOUBLE_TYPE": case "FLOAT_TYPE|DOUBLE_TYPE": return CastType.NUM_TO_DOUBLE; case "INT_TYPE|LONG_TYPE": return CastType.INT_TO_LONG; case "FLOAT_TYPE|LONG_TYPE": case "DOUBLE_TYPE|LONG_TYPE": return CastType.FLOATS_TO_LONG; case "STRING_TYPE|INT_TYPE": return CastType.STR_TO_INT; case "STRING_TYPE|FLOAT_TYPE": return CastType.STR_TO_FLOAT; case "STRING_TYPE|DOUBLE_TYPE": return CastType.STR_TO_DOUBLE; case "STRING_TYPE|LONG_TYPE": return CastType.STR_TO_LONG; default: break; } return CastType.UNSUPPORTED; }