auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public WakeupResponse wakeup(@ApiParam("Internal id for workflow instance") @PathVariable("id") int id, @RequestBody @Valid @ApiParam("Expected states") WakeupRequest req) { WakeupResponse response = new WakeupResponse(); List<String> expectedStates = req.expectedStates != null ? req.expectedStates : emptyList(); response.wakeupSuccess = workflowInstances.wakeupWorkflowInstance(id, expectedStates); return response; }

Target:
public WakeupResponse wakeup(@ApiParam("Internal id for workflow instance") @PathVariable("id") int id, @RequestBody @Valid @ApiParam("Expected states") WakeupRequest req) { WakeupResponse response = new WakeupResponse(); List<String> expectedStates = ofNullable(req.expectedStates).orElseGet(Collections::emptyList); response.wakeupSuccess = workflowInstances.wakeupWorkflowInstance(id, expectedStates); return response; }
Source:
protected OAuthCredentials getOAuthCredentials(final WebContext context) { final String stateParameter = context.getRequestParameter("state"); if (stateParameter != null && !stateParameter.isEmpty()) { final String sessionState = (String) context.getSessionAttribute(getName() + STATE_PARAMETER); context.setSessionAttribute(getName() + STATE_PARAMETER, null); logger.debug("sessionState : / stateParameter : {}", sessionState, stateParameter); if (!stateParameter.equals(sessionState)) { final String message = "State parameter mismatch : session expired or possible threat of cross-site request forgery"; throw new OAuthCredentialsException(message); } } else if (requiresStateParameter()) { final String message = "Missing state parameter : session expired or possible threat of cross-site request forgery"; throw new OAuthCredentialsException(message); } final String verifierParameter = context.getRequestParameter(OAUTH_CODE); if (verifierParameter != null) { final String verifier = OAuthEncoder.decode(verifierParameter); logger.debug("verifier : {}", verifier); return new OAuthCredentials(verifier, getName()); } else { final String message = "No credential found"; throw new OAuthCredentialsException(message); } }

Target:
protected OAuthCredentials getOAuthCredentials(final WebContext context) { final String verifierParameter = context.getRequestParameter(OAUTH_CODE); if (verifierParameter != null) { final String verifier = OAuthEncoder.decode(verifierParameter); logger.debug("verifier : {}", verifier); return new OAuthCredentials(verifier, getName()); } else { final String message = "No credential found"; throw new OAuthCredentialsException(message); } }
Source:
protected static StereotypeModel getStereotype(StereotypeDefinition stereotypeDefinition, String namespace, Map<StereotypeDefinition, StereotypeModel> stereotypesCache) { return FunctionalUtils.computeIfAbsent(stereotypesCache, stereotypeDefinition, definition -> { if (!isValidStereotype(stereotypeDefinition, namespace)) { throw new IllegalModelDefinitionException(format( "Stereotype '%s' defines namespace '%s' which doesn't match extension stereotype '%s'. No extension can define " + "stereotypes on namespaces other than its own", stereotypeDefinition.getName(), stereotypeDefinition.getNamespace(), namespace)); } String resolvedNamespace = isBlank(stereotypeDefinition.getNamespace()) ? namespace : stereotypeDefinition.getNamespace(); final StereotypeModelBuilder builder = newStereotype(stereotypeDefinition.getName(), resolvedNamespace); stereotypeDefinition.getParent().ifPresent(parent -> { String parentNamespace = parent.getNamespace(); if (isBlank(parentNamespace)) { parentNamespace = namespace; } builder.withParent(getStereotype(parent, parentNamespace, stereotypesCache)); }); return builder.build(); }); }

Target:
protected static StereotypeModel getStereotype(StereotypeDefinition stereotypeDefinition, String namespace, Map<StereotypeDefinition, StereotypeModel> stereotypesCache) { return computeIfAbsent(stereotypesCache, stereotypeDefinition, definition -> { if (!isValidStereotype(stereotypeDefinition, namespace)) { throw new IllegalModelDefinitionException(format( "Stereotype '%s' defines namespace '%s' which doesn't match extension stereotype '%s'. No extension can define " + "stereotypes on namespaces other than its own", stereotypeDefinition.getName(), stereotypeDefinition.getNamespace(), namespace)); } String resolvedNamespace = isBlank(stereotypeDefinition.getNamespace()) ? namespace : stereotypeDefinition.getNamespace(); final StereotypeModelBuilder builder = newStereotype(stereotypeDefinition.getName(), resolvedNamespace); stereotypeDefinition.getParent().ifPresent(parent -> { String parentNamespace = parent.getNamespace(); if (isBlank(parentNamespace)) { parentNamespace = namespace; } builder.withParent(getStereotype(parent, parentNamespace, stereotypesCache)); }); return builder.build(); }); }
Source:
private void checkHandle() { if (!iterator.isOwningHandle()) { throw new IllegalStateException("RocksIterator handle is not valid"); } }

Target:
private void checkHandle() { if (!iterator.isOwningHandle()) { throw new IllegalStateException("RocksIterator has been closed"); } }
Source:
public void theUserClicksOnTabLink(String tab) throws Throwable { switch (tab) { case "Pozíciók": driverProvider.getDriver().findElement(By.id("positions_link")).click(); break; case "Csatornák": driverProvider.getDriver().findElement(By.id("channels_link")).click(); break; case "Jelszó-változtatás": driverProvider.getDriver().findElement(By.id("password_link")).click(); break; } }

Target:
public void theUserClicksOnTabLink(String tab) throws Throwable { switch (tab) { case "Pozíciók": getDriver().findElement(By.id("positions_link")).click(); break; case "Csatornák": getDriver().findElement(By.id("channels_link")).click(); break; case "Jelszó-változtatás": getDriver().findElement(By.id("password_link")).click(); break; } }
Source:
public Optional<XMLObject> get(final String messageID) { final LinkedHashMap<String, String> messages = getMessages(); final String o = messages.get(messageID); if (o == null) { log.debug("Message not found in session {}", messageID, context.getSessionStore().getOrCreateSessionId(context)); return Optional.empty(); } log.debug("Message found in session {}, clearing", messageID, context.getSessionStore().getOrCreateSessionId(context)); messages.clear(); updateSession(messages); try { XMLObject message = XMLObjectSupport.unmarshallFromReader( Configuration.getParserPool(), new StringReader(o)); return Optional.of(message); } catch (Exception e) { log.error("Error unmarshalling message from input stream", e); return Optional.empty(); } }

Target:
public Optional<XMLObject> get(final String messageID) { final LinkedHashMap<String, String> messages = getMessages(); final String o = messages.get(messageID); if (o == null) { log.debug("Message not found in session {}", messageID, context.getSessionStore().getOrCreateSessionId(context)); return Optional.empty(); } log.debug("Message found in session {}, clearing", messageID, context.getSessionStore().getOrCreateSessionId(context)); messages.clear(); updateSession(messages); return Configuration.deserializeSamlObject(o); }
Source:
private String buildPushFailedMessage(final PushRequest request, final RemoteRefUpdate remoteRefUpdate, final String currentBranch) { String message; if (remoteRefUpdate.getStatus().equals(RemoteRefUpdate.Status.UP_TO_DATE)) { message = INFO_PUSH_ATTEMPT_IGNORED_UP_TO_DATE; } else { String refspec = currentBranch + BRANCH_REFSPEC_SEPERATOR + request.getRefSpec().get(0).split(REFSPEC_COLON)[1]; if (remoteRefUpdate.getMessage() != null) { message = String.format(ERROR_PUSH_ATTEMPT_FAILED_WITHMSG, refspec, request.getRemote(), remoteRefUpdate.getStatus(), remoteRefUpdate.getMessage()); } else { message = String.format(ERROR_PUSH_ATTEMPT_FAILED_WITHOUTMSG, refspec, request.getRemote(), remoteRefUpdate.getStatus()); } } return message; }

Target:
private String buildPushFailedMessage(final PushRequest request, final RemoteRefUpdate remoteRefUpdate, final String currentBranch) { String message; if (remoteRefUpdate.getStatus() == RemoteRefUpdate.Status.UP_TO_DATE) { message = INFO_PUSH_ATTEMPT_IGNORED_UP_TO_DATE; } else { String refspec = currentBranch + BRANCH_REFSPEC_SEPERATOR + request.getRefSpec().get(0).split(REFSPEC_COLON)[1]; if (remoteRefUpdate.getMessage() != null) { message = String.format(ERROR_PUSH_ATTEMPT_FAILED_WITHMSG, refspec, request.getRemote(), remoteRefUpdate.getStatus(), remoteRefUpdate.getMessage()); } else { message = String.format(ERROR_PUSH_ATTEMPT_FAILED_WITHOUTMSG, refspec, request.getRemote(), remoteRefUpdate.getStatus()); } } return message; }
Source:
public EntityTypeRest findOne(Context context, Integer integer) { try { return entityTypeConverter.fromModel(entityTypeService.find(context, integer)); } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } }

Target:
public EntityTypeRest findOne(Context context, Integer integer) { try { EntityType entityType = entityTypeService.find(context, integer); if (entityType == null) { throw new ResourceNotFoundException("The entityType for ID: " + integer + " could not be found"); } return entityTypeConverter.fromModel(entityType); } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } }
Source:
private File allocate(String filename, long size) throws IOException { File segmentFile = new File(dataDir, filename); if (!segmentFile.exists()) { if (diskSpaceAllocator != null) { diskSpaceAllocator.allocate(segmentFile, size); } else { Utils.preAllocateFileIfNeeded(segmentFile, size); } } return segmentFile; }

Target:
private File allocate(String filename, long size) throws IOException { File segmentFile = new File(dataDir, filename); if (!segmentFile.exists()) { diskSpaceAllocator.allocate(segmentFile, size); } return segmentFile; }
Source:
private static AttributeDefinition getListAttributeDefinition(String name, ModelType modelType) { return new StringListAttributeDefinition.Builder(name) .setRequired(false) .setAllowExpression(false) .setValidator(JavaIdListValidator.INSTANCE) .build(); }

Target:
private static AttributeDefinition getListAttributeDefinition(String name, ModelType modelType) { return new StringListAttributeDefinition.Builder(name) .setRequired(false) .setAllowExpression(true) .setValidator(JavaIdListValidator.INSTANCE) .build(); }
Source:
public void testInvoke() throws AxisFault { GlobalRequestCountHandler globalRequestCountHandler = new GlobalRequestCountHandler(); MessageContext messageContext; Counter counter = new Counter(); Parameter parameter = new Parameter(); parameter.setValue(counter); messageContext = Mockito.mock(MessageContext.class, Mockito.CALLS_REAL_METHODS); Mockito.doReturn(parameter).when(messageContext).getParameter(Mockito.anyString()); Handler.InvocationResponse response = globalRequestCountHandler.invoke(messageContext); Assert.assertEquals(response, Handler.InvocationResponse.CONTINUE); Assert.assertEquals(counter.getCount(), 1); }

Target:
public void testInvoke() throws Exception { GlobalRequestCountHandler globalRequestCountHandler = new GlobalRequestCountHandler(); MessageContext messageContext; Counter counter = new Counter(); Parameter parameter = new Parameter(); parameter.setValue(counter); messageContext = Mockito.mock(MessageContext.class, Mockito.CALLS_REAL_METHODS); Mockito.doReturn(parameter).when(messageContext).getParameter(Mockito.anyString()); Handler.InvocationResponse response = globalRequestCountHandler.invoke(messageContext); Assert.assertEquals("Asserting the response of the method",response, Handler.InvocationResponse.CONTINUE); Assert.assertEquals("Counter should be incremented to 1", counter.getCount(), 1); }
Source:
public void onHarvest(ActivateEvent event, EntityRef entity) { EntityRef target = event.getTarget(); EntityRef harvester = entity.equals(target) ? event.getInstigator() : entity; if (!event.isConsumed() && target.exists() && harvester.exists() && target.hasComponent(BushDefinitionComponent.class)) { BushDefinitionComponent bushComponent = target.getComponent(BushDefinitionComponent.class); if (bushComponent.currentStage == bushComponent.stages.length - 1) { EntityRef produce; try { produce = entityManager.create(bushComponent.produce); boolean giveSuccess = inventoryManager.giveItem(harvester, target, produce); if (!giveSuccess) { Vector3f position = event.getTargetLocation().add(0, 0.5f, 0); produce.send(new DropItemEvent(position)); produce.send(new ImpulseEvent(random.nextVector3f(15.0f))); } } catch (NullPointerException e) { logger.error("Unable to create produce: " + bushComponent.produce); } if (bushComponent.sustainable) { doBushGrowth(bushComponent, -1); } else { entity.send(new DoDestroyPlant()); worldProvider.setBlock(bushComponent.position, blockManager.getBlock(BlockManager.AIR_ID)); } event.consume(); } } }

Target:
public void onHarvest(ActivateEvent event, EntityRef entity) { EntityRef target = event.getTarget(); EntityRef harvester = entity.equals(target) ? event.getInstigator() : entity; if (!event.isConsumed() && areValidHarvestEntities(target, harvester)) { BushDefinitionComponent bushComponent = target.getComponent(BushDefinitionComponent.class); if (isInLastStage(bushComponent)) { dropProduce(bushComponent.produce, event.getTargetLocation(), harvester, target); if (bushComponent.sustainable) { resetDelay(doBushGrowth(bushComponent, -1), bushComponent.stages[bushComponent.currentStage].minTime, bushComponent.stages[bushComponent.currentStage].maxTime); } else { entity.send(new DoDestroyPlant()); worldProvider.setBlock(bushComponent.position, blockManager.getBlock(BlockManager.AIR_ID)); } event.consume(); } } }
Source:
public AbstractBuilder withPushObjectList(final List<CosemObjectDefinitionDto> pushObjectList) { if (pushObjectList == null) { this.pushObjectList = null; } else { this.pushObjectList = new ArrayList<>(pushObjectList); } return this; }

Target:
public AbstractBuilder withPushObjectList(final List<CosemObjectDefinitionDto> pushObjectList) { if (pushObjectList == null) { this.pushObjectList = null; } else { this.pushObjectList = pushObjectList; } return this; }
Source:
public final void init(Config config, TaskContext context) throws Exception { ApplicationRunner runner = ApplicationRunner.fromConfig(config); StreamGraphImpl streams = new StreamGraphImpl(runner); this.graphBuilder.init(streams, config); this.contextManager = streams.getContextManager(); Map<SystemStream, MessageStreamImpl> inputBySystemStream = new HashMap<>(); context.getSystemStreamPartitions().forEach(ssp -> { if (!inputBySystemStream.containsKey(ssp.getSystemStream())) { inputBySystemStream.putIfAbsent(ssp.getSystemStream(), streams.getInputStream(ssp.getSystemStream())); } }); operatorGraph.init(inputBySystemStream, config, this.contextManager.initTaskContext(config, context)); }

Target:
public final void init(Config config, TaskContext context) throws Exception { StreamGraphImpl streamGraph = new StreamGraphImpl(this.runner, config); this.graphBuilder.init(streamGraph, config); this.contextManager = streamGraph.getContextManager(); Map<SystemStream, MessageStreamImpl> inputBySystemStream = new HashMap<>(); context.getSystemStreamPartitions().forEach(ssp -> { if (!inputBySystemStream.containsKey(ssp.getSystemStream())) { inputBySystemStream.putIfAbsent(ssp.getSystemStream(), streamGraph.getInputStream(ssp.getSystemStream())); } }); operatorGraph.init(inputBySystemStream, config, this.contextManager.initTaskContext(config, context)); }
Source:
private Collection<String> getExistingIds(final BranchContext context, final Collection<String> ids, final Class<? extends SnomedComponentDocument> clazz) { return context.service(RevisionIndex.class).read(context.branch().path(), new RevisionIndexRead<Collection<String>>() { @Override public Collection<String> execute(final RevisionSearcher index) throws IOException { final Hits<? extends SnomedComponentDocument> hits = index.searcher() .search(Query.select(clazz) .where(RevisionDocument.Expressions.ids(ids)) .limit(ids.size()) .build()); return FluentIterable.from(hits).transform(ComponentUtils.getIdFunction()).toSet(); } }); }

Target:
private Collection<String> getExistingIds(final BranchContext context, final Collection<String> ids, final Class<? extends SnomedComponentDocument> clazz) { try { Hits<? extends SnomedComponentDocument> hits = context.service(RevisionSearcher.class).search(Query.select(clazz) .where(RevisionDocument.Expressions.ids(ids)) .limit(ids.size()) .build()); return FluentIterable.from(hits).transform(ComponentUtils.getIdFunction()).toSet(); } catch (IOException e) { throw new SnowowlRuntimeException(e); } }
Source:
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { log.trace("doPost"); int idx = Integer.parseInt(request.getParameter("idx"), 10); log.debug("Removing index {}", idx); InputStream is = request.getResource().getChild(RedirectMapModel.MAP_FILE_NODE).adaptTo(InputStream.class); List<String> lines = IOUtils.readLines(is); log.debug("Loaded lines", lines.size()); lines.remove(idx); log.debug("Removed line..."); ModifiableValueMap mvm = request.getResource().getChild(RedirectMapModel.MAP_FILE_NODE) .getChild(JcrConstants.JCR_CONTENT).adaptTo(ModifiableValueMap.class); mvm.put(JcrConstants.JCR_DATA, StringUtils.join(lines, "\n")); request.getResourceResolver().commit(); request.getResourceResolver().refresh(); log.debug("Changes saved..."); super.doGet(request, response); }

Target:
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { log.trace("doPost"); int idx = Integer.parseInt(request.getParameter("idx"), 10); log.debug("Removing index {}", idx); List<String> lines = RedirectEntriesUtils.readEntries(request); lines.remove(idx); log.debug("Removed line..."); RedirectEntriesUtils.updateRedirectMap(request, lines); RedirectEntriesUtils.writeEntriesToResponse(request, response); }
Source:
private void clientRequest(Tracing brave, String serviceName, ExchangeSendingEvent event) { ZipkinState state = event.getExchange().getProperty(ZipkinState.KEY, ZipkinState.class); if (state == null) { state = new ZipkinState(); event.getExchange().setProperty(ZipkinState.KEY, state); } Span last = state.peekServerSpan(); Span span; if (last != null) { span = brave.tracer().newChild(last.context()); } else { span = brave.tracer().nextSpan(); } span.kind(Span.Kind.CLIENT).start(); ZipkinClientRequestAdapter parser = new ZipkinClientRequestAdapter(this, event.getEndpoint()); INJECTOR.inject(span.context(), event.getExchange().getIn()); parser.onRequest(event.getExchange(), span.customizer()); state.pushClientSpan(span); if (LOG.isDebugEnabled()) { TraceContext context = span.context(); String traceId = "" + context.traceIdString(); String spanId = "" + context.spanId(); MDC.put("traceId", traceId); MDC.put("spanId", spanId); String parentId = context.parentId() != null ? "" + context.parentId() : null; if (parentId != null) { LOG.debug(String.format("clientRequest [service=%s, traceId=%20s, spanId=%20s, parentId=%20s]", serviceName, traceId, spanId, parentId)); MDC.put("parentId", parentId); } else { LOG.debug(String.format("clientRequest [service=%s, traceId=%20s, spanId=%20s]", serviceName, traceId, spanId)); } } }

Target:
private void clientRequest(Tracing brave, String serviceName, ExchangeSendingEvent event) { ZipkinState state = event.getExchange().getProperty(ZipkinState.KEY, ZipkinState.class); if (state == null) { state = new ZipkinState(); event.getExchange().setProperty(ZipkinState.KEY, state); } Span last = state.peekServerSpan(); Span span; if (last != null) { span = brave.tracer().newChild(last.context()); } else { span = brave.tracer().nextSpan(); } span.kind(Span.Kind.CLIENT).start(); ZipkinClientRequestAdapter parser = new ZipkinClientRequestAdapter(this, event.getEndpoint()); INJECTOR.inject(span.context(), event.getExchange().getIn()); parser.onRequest(event.getExchange(), span.customizer()); state.pushClientSpan(span); TraceContext context = span.context(); String traceId = "" + context.traceIdString(); String spanId = "" + context.spanId(); String parentId = context.parentId() != null ? "" + context.parentId() : null; if (camelContext.isUseMDCLogging()) { MDC.put("traceId", traceId); MDC.put("spanId", spanId); MDC.put("parentId", parentId); } if (LOG.isDebugEnabled()) { if (parentId != null) { LOG.debug(String.format("clientRequest [service=%s, traceId=%20s, spanId=%20s, parentId=%20s]", serviceName, traceId, spanId, parentId)); } else { LOG.debug(String.format("clientRequest [service=%s, traceId=%20s, spanId=%20s]", serviceName, traceId, spanId)); } } }
Source:
private void resetToFileBasedWriter() throws IOException { this.out.close(); BoundedByteArrayOutputStream bout = (BoundedByteArrayOutputStream) this.rawOut.getWrappedStream(); if (outputPath == null) { outputPath = taskOutput.getOutputFileForWrite(); } LOG.info("Creating file " + outputPath); FSDataOutputStream newRawOut = fs.create(outputPath); this.rawOut = newRawOut; this.checksumOut = new IFileOutputStream(this.rawOut); if (fileCodec != null) { this.compressor = CodecPool.getCompressor(fileCodec); if (this.compressor != null) { this.compressor.reset(); this.compressOutput = true; this.compressedOut = fileCodec.createOutputStream(checksumOut, compressor); this.out = new FSDataOutputStream(this.compressedOut, null); } else { LOG.warn("Could not obtain compressor from CodecPool"); this.out = new FSDataOutputStream(checksumOut, null); } } else { this.out = new FSDataOutputStream(checksumOut, null); } headerWritten = false; writeHeader(newRawOut); int sPos = HEADER.length; int len = (bout.size() - checksumSize - HEADER.length); this.out.write(bout.getBuffer(), sPos, len); bufferFull = true; bout.reset(); }

Target:
private void resetToFileBasedWriter() throws IOException { this.out.close(); BoundedByteArrayOutputStream bout = (BoundedByteArrayOutputStream) this.rawOut.getWrappedStream(); if (outputPath == null) { outputPath = taskOutput.getOutputFileForWrite(); } LOG.info("Switching from mem stream to disk stream. File: " + outputPath); FSDataOutputStream newRawOut = fs.create(outputPath); this.rawOut = newRawOut; this.ownOutputStream = true; setupOutputStream(fileCodec); headerWritten = false; writeHeader(newRawOut); int sPos = HEADER.length; int len = (bout.size() - checksumSize - HEADER.length); this.out.write(bout.getBuffer(), sPos, len); bufferFull = true; bout.reset(); }
Source:
public Snippet getSnippet(Integer snippetId) throws GitLabApiException { if (snippetId == null) { throw new RuntimeException("snippetId can't be null"); } Response response = get(Response.Status.OK, null, "snippets", snippetId); Snippet snippet = response.readEntity(Snippet.class); snippet.setContent(getSnippetContent(snippet.getId())); return snippet; }

Target:
public Snippet getSnippet(Integer snippetId) throws GitLabApiException { return getSnippet(snippetId, false); }
Source:
public void addVariable() { TestSuiteModel testSuite = new TestSuiteModel(); String variable_indentifier = "variable_indentifier"; String variable_content = "variable_content"; String variable_description = "variable_description"; assertEquals(0, testSuite.getVariables().size()); testSuite.addVariable(variable_indentifier, variable_content, variable_description); assertEquals(1, testSuite.getVariables().size()); assertEquals(variable_indentifier, testSuite.getVariables().get(0).getName()); assertEquals(variable_content, testSuite.getVariables().get(0).getContent()); assertEquals(variable_description, testSuite.getVariables().get(0).getDescription()); String variable_indentifier_1 = variable_indentifier + "_1"; String variable_content_1 = "variable_content" + "_1"; String variable_description_1 = "variable_description" + "_1"; testSuite.addVariable(variable_indentifier_1, variable_content_1, variable_description_1); assertEquals(2, testSuite.getVariables().size()); assertEquals(variable_indentifier, testSuite.getVariables().get(0).getName()); assertEquals(variable_content, testSuite.getVariables().get(0).getContent()); assertEquals(variable_description, testSuite.getVariables().get(0).getDescription()); assertEquals(variable_indentifier_1, testSuite.getVariables().get(1).getName()); assertEquals(variable_content_1, testSuite.getVariables().get(1).getContent()); assertEquals(variable_description_1, testSuite.getVariables().get(1).getDescription()); }

Target:
public void addVariable() { TestSuiteModel testSuite = new TestSuiteModel(); for (int index = 0; index < elements; index++) { testSuite.setVariable(variableIndentifier[index], variableContent[index], variableDescription[index]); assertEquals(variableIndentifier[index], testSuite.getVariable(variableIndentifier[index]).getName()); assertEquals(variableContent[index], testSuite.getVariable(variableIndentifier[index]).getContent()); assertEquals(variableDescription[index], testSuite.getVariable(variableIndentifier[index]).getDescription()); } }
Source:
public Field build() { return new Field().setName(super.getName()).setType(super.getDataType()).setSearchable(true) .setKey(super.isKey()).setSortable(super.isSortable()).setFilterable(super.isFilterable()) .setHidden(super.isHidden()).setFacetable(super.isFacetable()).setAnalyzer(this.analyzer) .setSearchAnalyzer(this.searchAnalyzer).setIndexAnalyzer(this.indexAnalyzer) .setSynonymMaps(this.synonymMaps); }

Target:
public Field build() { return new Field() .setName(super.getName()) .setType(super.getDataType()) .setSearchable(true) .setKey(super.isKey()) .setSortable(super.isSortable()) .setFilterable(super.isFilterable()) .setHidden(super.isHidden()) .setFacetable(super.isFacetable()) .setAnalyzer(this.analyzer) .setSearchAnalyzer(this.searchAnalyzer) .setIndexAnalyzer(this.indexAnalyzer) .setSynonymMaps(this.synonymMapNames); }
Source:
public static List<String> getResourceFiles(String path) throws IOException { List<String> fileNames = new ArrayList<>(); try ( InputStream in = getResourceAsStream(path); BufferedReader br = new BufferedReader(new InputStreamReader(in)) ) { String resource; while ((resource = br.readLine()) != null) { if (resource.endsWith("code.ser") || resource.endsWith("conf.ser")) { fileNames.add(path + "/" + resource); } } Collections.sort(fileNames); } return fileNames; }

Target:
public static List<String> getResourceFiles(String path) throws IOException { List<String> fileNames = new ArrayList<>(); try ( InputStream in = getResourceAsStream(path); BufferedReader br = new BufferedReader(new InputStreamReader(in)) ) { String resource; while ((resource = br.readLine()) != null) { if (resource.endsWith(COMPRESSED_SERIALIZED_TOPOLOGY_FILENAME_ENDING) || resource.endsWith(COMPRESSED_SERIALIZED_CONFIG_FILENAME_ENDING)) { fileNames.add(path + "/" + resource); } } Collections.sort(fileNames); } return fileNames; }
Source:
public void onAttached(Run<?, ?> r) { ParametersDefinitionProperty p = r.getParent().getProperty(ParametersDefinitionProperty.class); if (p != null) { this.parameterDefinitionNames = p.getParameterDefinitionNames(); } else { this.parameterDefinitionNames = Collections.emptyList(); } if (wasInitializedWithNullParameters) { LOGGER.log(Level.WARNING, "ParametersAction has been initialized with null parameter list for Run {0}. It is a bug in the plugin, which created this action (see JENKINS-39495).", r); } this.run = r; }

Target:
public void onAttached(Run<?, ?> r) { ParametersDefinitionProperty p = r.getParent().getProperty(ParametersDefinitionProperty.class); if (p != null) { this.parameterDefinitionNames = p.getParameterDefinitionNames(); } else { this.parameterDefinitionNames = Collections.emptyList(); } if (wasInitializedWithNullParameters) { LOGGER.log(Level.FINE, "ParametersAction has been initialized with null parameter list for Run {0}. It is a bug in a plugin or script, which created this action (see JENKINS-39495).", r); } this.run = r; }
Source:
private boolean isNetworkSelectionNeeded(List<ScanDetail> scanDetails, WifiInfo wifiInfo, boolean connected, boolean disconnected) { if (scanDetails.size() == 0) { localLog("Empty connectivity scan results. Skip network selection."); return false; } if (connected) { if (!mEnableAutoJoinWhenAssociated) { localLog("Switching networks in connected state is not allowed." + " Skip network selection."); return false; } if (mLastNetworkSelectionTimeStamp != INVALID_TIME_STAMP) { long gap = mClock.getElapsedSinceBootMillis() - mLastNetworkSelectionTimeStamp; if (gap < MINIMUM_NETWORK_SELECTION_INTERVAL_MS) { localLog("Too short since last network selection: " + gap + " ms." + " Skip network selection."); return false; } } boolean is5GHzAvailable = is5GHzNetworkAvailable(scanDetails); if (isCurrentNetworkSufficient(wifiInfo, is5GHzAvailable)) { localLog("Current connected network already sufficient. Skip network selection."); return false; } else { localLog("Current connected network is not sufficient."); return true; } } else if (disconnected) { return true; } else { localLog("WifiStateMachine is in neither CONNECTED nor DISCONNECTED state." + " Skip network selection."); return false; } }

Target:
private boolean isNetworkSelectionNeeded(List<ScanDetail> scanDetails, WifiInfo wifiInfo, boolean connected, boolean disconnected) { if (scanDetails.size() == 0) { localLog("Empty connectivity scan results. Skip network selection."); return false; } if (connected) { if (!mEnableAutoJoinWhenAssociated) { localLog("Switching networks in connected state is not allowed." + " Skip network selection."); return false; } if (mLastNetworkSelectionTimeStamp != INVALID_TIME_STAMP) { long gap = mClock.getElapsedSinceBootMillis() - mLastNetworkSelectionTimeStamp; if (gap < MINIMUM_NETWORK_SELECTION_INTERVAL_MS) { localLog("Too short since last network selection: " + gap + " ms." + " Skip network selection."); return false; } } if (isCurrentNetworkSufficient(wifiInfo, scanDetails)) { localLog("Current connected network already sufficient. Skip network selection."); return false; } else { localLog("Current connected network is not sufficient."); return true; } } else if (disconnected) { return true; } else { localLog("WifiStateMachine is in neither CONNECTED nor DISCONNECTED state." + " Skip network selection."); return false; } }
Source:
public List<Event> getEvents(@QueryParam("client") String client, @QueryParam("user") String user, @QueryParam("dateFrom") String dateFrom, @QueryParam("dateTo") String dateTo, @QueryParam("ipAddress") String ipAddress, @QueryParam("first") Integer firstResult, @QueryParam("max") Integer maxResults) { auth.init(RealmAuth.Resource.EVENTS).requireView(); EventStoreProvider eventStore = session.getProvider(EventStoreProvider.class); EventQuery query = eventStore.createQuery().realm(realm.getId()); if (client != null) { query.client(client); } List<String> types = uriInfo.getQueryParameters().get("type"); if (types != null) { EventType[] t = new EventType[types.size()]; for (int i = 0; i < t.length; i++) { t[i] = EventType.valueOf(types.get(i)); } query.type(t); } if (user != null) { query.user(user); } if(dateFrom != null) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date from = null; try { from = df.parse(dateFrom); } catch (ParseException e) { e.printStackTrace(); } query.fromDate(from); } if(dateTo != null) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date to = null; try { to = df.parse(dateFrom); } catch (ParseException e) { e.printStackTrace(); } query.toDate(to); } if (ipAddress != null) { query.ipAddress(ipAddress); } if (firstResult != null) { query.firstResult(firstResult); } if (maxResults != null) { query.maxResults(maxResults); } return query.getResultList(); }

Target:
public List<Event> getEvents(@QueryParam("client") String client, @QueryParam("user") String user, @QueryParam("dateFrom") String dateFrom, @QueryParam("dateTo") String dateTo, @QueryParam("ipAddress") String ipAddress, @QueryParam("first") Integer firstResult, @QueryParam("max") Integer maxResults) { auth.init(RealmAuth.Resource.EVENTS).requireView(); EventStoreProvider eventStore = session.getProvider(EventStoreProvider.class); EventQuery query = eventStore.createQuery().realm(realm.getId()); if (client != null) { query.client(client); } List<String> types = uriInfo.getQueryParameters().get("type"); if (types != null) { EventType[] t = new EventType[types.size()]; for (int i = 0; i < t.length; i++) { t[i] = EventType.valueOf(types.get(i)); } query.type(t); } if (user != null) { query.user(user); } if(dateFrom != null) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date from = null; try { from = df.parse(dateFrom); } catch (ParseException e) { throw new BadRequestException("Invalid value for 'Date(From)', excepted format is yyyy-MM-dd"); } query.fromDate(from); } if(dateTo != null) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date to = null; try { to = df.parse(dateTo); } catch (ParseException e) { throw new BadRequestException("Invalid value for 'Date(To)', excepted format is yyyy-MM-dd"); } query.toDate(to); } if (ipAddress != null) { query.ipAddress(ipAddress); } if (firstResult != null) { query.firstResult(firstResult); } if (maxResults != null) { query.maxResults(maxResults); } return query.getResultList(); }
Source:
public void testImportWithCheckGroups() throws IOException { File tmzFile = folder.newFile("CheckGroup.tmz"); Lib.inputStreamToFile(getClass().getResourceAsStream("CheckGroup.tmz"), tmzFile); TmzImporter importer = new TmzImporter(null, factory); OperationReport report = new OperationReport(); List<DispoItem> results = importer.importDirectory(new HashMap<String, DispoItem>(), folder.getRoot(), report); Assert.assertEquals(1, results.size()); DispoItem result = results.get(0); Assert.assertEquals("CheckGroup", result.getName()); Assert.assertEquals(2, result.getDiscrepanciesList().size()); Assert.assertEquals("113054", result.getVersion()); boolean firstFound = false, thirdFound = false; for (String key : result.getDiscrepanciesList().keySet()) { Discrepancy discrepancy = result.getDiscrepanciesList().get(key); if (Integer.valueOf(discrepancy.getLocation()) == 1) { firstFound = true; Assert.assertEquals( "Failure at Test Point 1. Check Group with Checkpoint Failures: Check Point: CODE. Expected: 1500. Actual: NULL. Check Point: STATE. Expected: TRUE. Actual: NULL. Check Point: IBOT. Expected: FALSE. Actual: NULL. Check Point: BOT_CODE. Expected: 0. Actual: NULL. Check Point: FILTER_TIME. Expected: 10000. Actual: NULL. ", discrepancy.getText()); } else if (Integer.valueOf(discrepancy.getLocation()) == 3) { thirdFound = true; Assert.assertEquals( "Failure at Test Point 3. Check Point: CheckPoint_BOT. Expected: ORANGE = FALSE. Actual: ORANGE = NULL. ", discrepancy.getText()); } } Assert.assertTrue(firstFound); Assert.assertTrue(thirdFound); }

Target:
public void testImportWithCheckGroups() throws IOException { File tmzFile = folder.newFile("CheckGroup.tmz"); Lib.inputStreamToFile(getClass().getResourceAsStream("CheckGroup.tmz"), tmzFile); TmzImporter importer = new TmzImporter(null, factory); OperationReport report = new OperationReport(); List<DispoItem> results = importer.importDirectory(new HashMap<String, DispoItem>(), folder.getRoot(), report); Assert.assertEquals(1, results.size()); DispoItem result = results.get(0); Assert.assertEquals("CheckGroup", result.getName()); Assert.assertEquals(2, result.getDiscrepanciesList().size()); Assert.assertEquals("113054", result.getVersion()); boolean firstFound = false, thirdFound = false; for (String key : result.getDiscrepanciesList().keySet()) { Discrepancy discrepancy = result.getDiscrepanciesList().get(key); if (discrepancy.getLocation().equals("1")) { firstFound = true; Assert.assertEquals( "Failure at Test Point 1. Check Group with Checkpoint Failures: Check Point: CODE. Expected: 1500. Actual: NULL. Check Point: STATE. Expected: TRUE. Actual: NULL. Check Point: IBOT. Expected: FALSE. Actual: NULL. Check Point: BOT_CODE. Expected: 0. Actual: NULL. Check Point: FILTER_TIME. Expected: 10000. Actual: NULL. ", discrepancy.getText()); } else if (discrepancy.getLocation().equals("3")) { thirdFound = true; Assert.assertEquals( "Failure at Test Point 3. Check Point: CheckPoint_BOT. Expected: ORANGE = FALSE. Actual: ORANGE = NULL. ", discrepancy.getText()); } } Assert.assertTrue(firstFound); Assert.assertTrue(thirdFound); }
Source:
public static String nullLiteral() { return NullHandlingHelper.useDefaultValuesForNull() ? "''" : null; }

Target:
public static String nullLiteral() { return "null"; }
Source:
private Cookie getSessionCookie(TestEnvironmentEntity testEnv) { Cookie cookie = new Cookie(TestEnvUtils.SESSION_COOKIE, testEnv.getSessionId()); cookie.setMaxAge(environmentsTtlMinutes * 60); return cookie; }

Target:
private Cookie getSessionCookie(TestEnvironmentEntity testEnv) { Cookie cookie = new Cookie(TestEnvUtils.SESSION_COOKIE, testEnv.getSessionId()); cookie.setMaxAge(environmentsTtlMinutes * 60); cookie.setPath("/"); return cookie; }
Source:
private Version createVersion(ProjectHistory projectHistory, Project projectState, LogMessage logMessage, ACUser user, Version previousVersion) throws ESException { final Version newVersion = VersioningFactory.eINSTANCE.createVersion(); long computedChecksum = ModelUtil.NO_CHECKSUM; try { if (ServerConfiguration.isComputeChecksumOnCommitActive()) { computedChecksum = ModelUtil.computeChecksum(projectState); ModelUtil.logProjectDetails( MessageFormat.format("Checksum computaion during version create: {0}", computedChecksum), user.getName(), projectHistory.getProjectName(), projectHistory.getProjectId().getId(), null, -1); } } catch (final SerializationException exception) { throw new ESException(MessageFormat.format( Messages.VersionSubInterfaceImpl_ChecksumComputationFailed, projectHistory.getProjectName()), exception); } logMessage.setDate(new Date()); logMessage.setAuthor(user.getName()); newVersion.setLogMessage(logMessage); newVersion.setPrimarySpec(Versions.createPRIMARY(previousVersion.getPrimarySpec(), projectHistory.getVersions() .size())); newVersion.getPrimarySpec().setProjectStateChecksum(computedChecksum); newVersion.setNextVersion(null); projectHistory.getVersions().add(newVersion); return newVersion; }

Target:
private Version createVersion(ProjectHistory projectHistory, Project projectState, LogMessage logMessage, ACUser user, Version previousVersion) throws ESException { final Version newVersion = VersioningFactory.eINSTANCE.createVersion(); long computedChecksum = ModelUtil.NO_CHECKSUM; try { if (ServerConfiguration.isComputeChecksumOnCommitActive()) { computedChecksum = ModelUtil.computeChecksum(projectState); ModelUtil.logProjectDetails( MessageFormat.format("Checksum computation during version create: {0}", computedChecksum), user.getName(), projectHistory.getProjectName(), projectHistory.getProjectId().getId(), null, -1); } } catch (final SerializationException exception) { throw new ESException(MessageFormat.format( Messages.VersionSubInterfaceImpl_ChecksumComputationFailed, projectHistory.getProjectName()), exception); } logMessage.setDate(new Date()); logMessage.setAuthor(user.getName()); newVersion.setLogMessage(logMessage); newVersion.setPrimarySpec(Versions.createPRIMARY(previousVersion.getPrimarySpec(), projectHistory.getVersions() .size())); newVersion.getPrimarySpec().setProjectStateChecksum(computedChecksum); newVersion.setNextVersion(null); projectHistory.getVersions().add(newVersion); return newVersion; }
Source:
public void testIsEmpty() { assertTrue( Version.isEmpty( null ) ); assertTrue( Version.isEmpty( "" ) ); assertTrue( Version.isEmpty( String.format( " %n" ) ) ); assertFalse( Version.isEmpty( "a" ) ); assertFalse( Version.isEmpty( String.format ( "a %n" ) ) ); }

Target:
public void testIsEmpty() { assertTrue( Version.isEmpty(null) ); assertTrue( Version.isEmpty("") ); assertTrue( Version.isEmpty(" " + System.lineSeparator() ) ); assertFalse( Version.isEmpty( "a") ); assertFalse( Version.isEmpty( " a " + System.lineSeparator() ) ); }
Source:
public void addOrUpdateAlert(final Alert alert) { assertIsOpen(); LOGGER.debug() .setMessage("Upserting alert") .addData("alert", alert) .log(); final Transaction transaction = Ebean.beginTransaction(); try { models.ebean.Alert ebeanAlert = Ebean.find(models.ebean.Alert.class) .where() .eq("uuid", alert.getId()) .findUnique(); boolean created = false; if (ebeanAlert == null) { ebeanAlert = new models.ebean.Alert(); created = true; } ebeanAlert.setCluster(alert.getCluster()); ebeanAlert.setUuid(alert.getId()); ebeanAlert.setMetric(alert.getMetric()); ebeanAlert.setContext(alert.getContext()); ebeanAlert.setNagiosExtension(getNagiosExtensionFromMap(alert.getExtensions())); ebeanAlert.setName(alert.getName()); ebeanAlert.setOperator(alert.getOperator()); ebeanAlert.setPeriod(alert.getPeriod().toStandardSeconds().getSeconds()); ebeanAlert.setQuantityValue(alert.getValue().getValue()); ebeanAlert.setQuantityUnit(alert.getValue().getUnit().isPresent() ? alert.getValue().getUnit().get() : null); ebeanAlert.setStatistic(alert.getStatistic()); ebeanAlert.setService(alert.getService()); _alertQueryGenerator.saveAlert(ebeanAlert); transaction.commit(); LOGGER.info() .setMessage("Upserted alert") .addData("alert", alert) .addData("isCreated", created) .log(); } finally { transaction.end(); } }

Target:
public void addOrUpdateAlert(final Alert alert) { assertIsOpen(); LOGGER.debug() .setMessage("Upserting alert") .addData("alert", alert) .log(); try (Transaction transaction = Ebean.beginTransaction()) { models.ebean.Alert ebeanAlert = Ebean.find(models.ebean.Alert.class) .where() .eq("uuid", alert.getId()) .findUnique(); boolean created = false; if (ebeanAlert == null) { ebeanAlert = new models.ebean.Alert(); created = true; } ebeanAlert.setCluster(alert.getCluster()); ebeanAlert.setUuid(alert.getId()); ebeanAlert.setMetric(alert.getMetric()); ebeanAlert.setContext(alert.getContext()); ebeanAlert.setNagiosExtension(convertToEbeanNagiosExtension(alert.getNagiosExtension())); ebeanAlert.setName(alert.getName()); ebeanAlert.setOperator(alert.getOperator()); ebeanAlert.setPeriod(alert.getPeriod().toStandardSeconds().getSeconds()); ebeanAlert.setQuantityValue(alert.getValue().getValue()); ebeanAlert.setQuantityUnit(alert.getValue().getUnit().orNull()); ebeanAlert.setStatistic(alert.getStatistic()); ebeanAlert.setService(alert.getService()); _alertQueryGenerator.saveAlert(ebeanAlert); transaction.commit(); LOGGER.info() .setMessage("Upserted alert") .addData("alert", alert) .addData("isCreated", created) .log(); } catch (final IOException | RuntimeException e) { LOGGER.error() .setMessage("Failed to upsert alert") .addData("alert", alert) .setThrowable(e) .log(); throw new PersistenceException(e); } }
Source:
public BitstreamResource uploadBitstream(HttpServletRequest request, @PathVariable UUID uuid, @RequestParam("file") MultipartFile uploadfile, @RequestParam(value = "properties", required = false) String properties) { Context context = ContextUtil.obtainContext(request); Item item = null; Bitstream bitstream = null; try { item = itemService.find(context, uuid); } catch (SQLException e) { log.error("Something went wrong trying to find the Item with uuid: " + uuid, e); } if (item == null) { throw new ResourceNotFoundException("The given uuid did not resolve to an Item on the server: " + uuid); } InputStream fileInputStream = null; try { fileInputStream = uploadfile.getInputStream(); } catch (IOException e) { log.error("Something went wrong when trying to read the inputstream from the given file in the request"); throw new UnprocessableEntityException("The InputStream from the file couldn't be read"); } try { bitstream = processBitstreamCreation(context, item, fileInputStream, properties, uploadfile.getOriginalFilename()); itemService.update(context, item); context.commit(); } catch (AuthorizeException | IOException | SQLException e) { log.error( "Something went wrong with trying to create the single bitstream for file with filename: " + uploadfile .getOriginalFilename() + " for item with uuid: " + uuid + " and possible properties: " + properties); } return new BitstreamResource(bitstreamConverter.fromModel(bitstream), utils); }

Target:
public BitstreamResource uploadBitstream(HttpServletRequest request, @PathVariable UUID uuid, @RequestParam("file") MultipartFile uploadfile, @RequestParam(value = "properties", required = false) String properties) { Context context = ContextUtil.obtainContext(request); Item item = null; Bitstream bitstream = null; try { item = itemService.find(context, uuid); } catch (SQLException e) { log.error("Something went wrong trying to find the Item with uuid: " + uuid, e); } if (item == null) { throw new ResourceNotFoundException("The given uuid did not resolve to an Item on the server: " + uuid); } InputStream fileInputStream = null; try { fileInputStream = uploadfile.getInputStream(); } catch (IOException e) { log.error("Something went wrong when trying to read the inputstream from the given file in the request", e); throw new UnprocessableEntityException("The InputStream from the file couldn't be read", e); } try { bitstream = processBitstreamCreation(context, item, fileInputStream, properties, uploadfile.getOriginalFilename()); itemService.update(context, item); context.commit(); } catch (AuthorizeException | IOException | SQLException e) { String message = "Something went wrong with trying to create the single bitstream for file with filename: " + uploadfile.getOriginalFilename() + " for item with uuid: " + uuid + " and possible properties: " + properties; log.error(message, e); throw new RuntimeException(message, e); } return new BitstreamResource(bitstreamConverter.fromModel(bitstream), utils); }
Source:
public String toString() { try { return new ObjectMapper().writeValueAsString(this); } catch (Exception e) { return ""; } }

Target:
public String toString() { try { return OBJECT_MAPPER.writeValueAsString(this); } catch (Exception e) { return ""; } }
Source:
public void suspend() { switch (state()) { case CREATED: case SUSPENDED: log.info("Skip suspending since state is {}", state()); break; case RESTORING: case RUNNING: try { closeTopology(); } finally { transitionTo(State.SUSPENDED); log.info("Suspended"); } break; case CLOSED: throw new IllegalStateException("Illegal state " + state() + " while suspending active task " + id); default: throw new IllegalStateException("Unknown state " + state() + " while suspending active task " + id); } }

Target:
public void suspend() { switch (state()) { case CREATED: case SUSPENDED: log.info("Skip suspending since state is {}", state()); break; case RESTORING: transitionTo(State.SUSPENDED); log.info("Suspended restoring"); break; case RUNNING: try { ENDED even if user code throws in `Processor#close()` closeTopology(); } finally { transitionTo(State.SUSPENDED); log.info("Suspended running"); } break; case CLOSED: throw new IllegalStateException("Illegal state " + state() + " while suspending active task " + id); default: throw new IllegalStateException("Unknown state " + state() + " while suspending active task " + id); } }
Source:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (StringUtils.isEmpty(SSOUtils.getParameter(request, SSOUtils.POST_ACTION_URL))) { throw new RuntimeException("No post action url found in request."); } HttpSession session = request.getSession(true); if (SSOUtils.isUserAuthenticated(session)) { request.getRequestDispatcher(SSOUtils.LOGIN_PHASE3_URI).forward(request, response); } else { authenticateUser(session, request, response); } }

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); try { if (SSOUtils.isUserAuthenticated(session)) { request.getRequestDispatcher(SSOUtils.LOGIN_PHASE3_URI).forward(request, response); } else { authenticateUser(session, request, response); } } catch (AuthenticationException ex) { request.getRequestDispatcher("/WEB-INF/login.jsp?msg=" + ex.getMessage()).forward(request, response); } finally { request.getSession().removeAttribute(SSOUtils.USER_CREDENTIALS); } }
Source:
public Iterable<String> names() throws IOException { assert this.dir != null; assert this.user != null; assert this.label != null; return Arrays.asList(this.friends.list()); }

Target:
public Iterable<String> names() { return Arrays.asList(this.friends.list()); }