auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onNext(final byte[] bytes) { final ObjectSerializableCodec<String> codec = new ObjectSerializableCodec<>(); final String input = codec.decode(bytes); final String[] result = input.split("\\s+", 2); final String command = result[0]; final String serializedConf = result[1]; switch (command) { case SUBMIT_COMMAND: try { if (!executeJob(ConfigurationUtils.fromString(serializedConf))) { sendMessageToClient("Job Server has already been shut down and will not accept any jobs."); } } catch (InjectionException | IOException e) { throw new RuntimeException(e); } break; case SHUTDOWN_COMMAND: shutdown(); break; default: throw new RuntimeException("There is unexpected command"); } }

Target:
public void onNext(final byte[] bytes) { final String input = new String(bytes); final String[] result = input.split(COMMAND_DELIMITER, 2); final String command = result[0]; switch (command) { case SUBMIT_COMMAND: try { final String serializedConf = result[1]; executeJob(ConfigurationUtils.fromString(serializedConf)); } catch (InjectionException | IOException e) { throw new RuntimeException("The given job configuration is incomplete", e); } break; case SHUTDOWN_COMMAND: shutdown(); break; default: throw new RuntimeException("There is unexpected command"); } }
Source:
public void continueOrPropagate(RetryableException ex) { boolean isFastFailoverException = isFastFailoverException(ex); synchronized (this) { if (!isFastFailoverException && retrySemantics == RetrySemantics.NEVER_EXCEPT_ON_NON_LEADERS) { throw hardFailOwingToFailureOnLeader(ex); } if (mostRecentServerIndex.get() != null && mostRecentServerIndex.get() == failoverCount.get()) { long failures = failuresSinceLastSwitch.incrementAndGet(); if (isFastFailoverException || failures >= failuresBeforeSwitching) { if (isFastFailoverException) { numSwitches.set(0); startTimeOfFastFailover.compareAndSet(0, System.currentTimeMillis()); } else { numSwitches.incrementAndGet(); startTimeOfFastFailover.set(0); } failuresSinceLastSwitch.set(0); failoverCount.incrementAndGet(); } } } checkAndHandleFailure(ex); if (!isFastFailoverException) { pauseForBackOff(ex); } }

Target:
public void continueOrPropagate(RetryableException ex) { boolean isFastFailoverException = isFastFailoverException(ex); if (!isFastFailoverException && retrySemantics == RetrySemantics.NEVER_EXCEPT_ON_NON_LEADERS) { throw hardFailOwingToFailureOnLeader(ex); } synchronized (this) { if (mostRecentServerIndex.get() != null && mostRecentServerIndex.get() == failoverCount.get()) { long failures = failuresSinceLastSwitch.incrementAndGet(); if (isFastFailoverException || failures >= failuresBeforeSwitching) { if (isFastFailoverException) { numSwitches.set(0); startTimeOfFastFailover.compareAndSet(0, System.currentTimeMillis()); } else { numSwitches.incrementAndGet(); startTimeOfFastFailover.set(0); } failuresSinceLastSwitch.set(0); failoverCount.incrementAndGet(); } } } checkAndHandleFailure(ex); if (!isFastFailoverException) { pauseForBackOff(ex); } }
Source:
protected URI resolveUri(String path) { try { URI uri = new URI("file:/ if (Files.notExists(Paths.get(uri), LinkOption.NOFOLLOW_LINKS)) { return null; } return uri; } catch (URISyntaxException e) { return null; } }

Target:
protected URI resolveUri(String path) { String filename = prefix + path; try { URI uri = new URI(filename); File file = new File(uri); if (!file.exists()) { logger.debug("File '{}' not found", filename); return null; } return uri; } catch (URISyntaxException e) { logger.debug("Error resolving uri for '{}'", filename); return null; } }
Source:
public void addImportedInstance(WorkflowExecutionContext context) throws FalconException { String feedName = context.getOutputFeedNames(); String feedInstanceDataPath = context.getOutputFeedInstancePaths(); String datasourceName = context.getDatasourceName(); String sourceClusterName = context.getSrcClusterName(); LOG.info("Computing import feed instance for : name= path= {}, in cluster: " + "from datasource: {}", feedName, feedInstanceDataPath, sourceClusterName, datasourceName); String feedInstanceName = getFeedInstanceName(feedName, sourceClusterName, feedInstanceDataPath, context.getNominalTimeAsISO8601()); Vertex feedInstanceVertex = addFeedInstance( feedInstanceName, context, feedName, context.getSrcClusterName()); Map<RelationshipProperty, String> properties = new HashMap<RelationshipProperty, String>(); properties.put(RelationshipProperty.TIMESTAMP, context.getTimeStampAsISO8601()); addInstanceToEntity(feedInstanceVertex, datasourceName, RelationshipType.DATASOURCE_ENTITY, RelationshipLabel.DATASOURCE_IMPORT_EDGE, properties); addInstanceToEntity(feedInstanceVertex, sourceClusterName, RelationshipType.CLUSTER_ENTITY, RelationshipLabel.FEED_CLUSTER_EDGE, properties); }

Target:
public void addImportedInstance(WorkflowExecutionContext context) throws FalconException { String feedName = context.getOutputFeedNames(); String feedInstanceDataPath = context.getOutputFeedInstancePaths(); String datasourceName = context.getDatasourceName(); String sourceClusterName = context.getSrcClusterName(); LOG.info("Computing import feed instance for : name= path= {}, in cluster: " + "from datasource: {}", feedName, feedInstanceDataPath, sourceClusterName, datasourceName); String feedInstanceName = getFeedInstanceName(feedName, sourceClusterName, feedInstanceDataPath, context.getNominalTimeAsISO8601()); Vertex feedInstanceVertex = addFeedInstance( feedInstanceName, context, feedName, context.getSrcClusterName()); Map<RelationshipProperty, String> properties = edgePropertiesForIndexing(context); properties.put(RelationshipProperty.TIMESTAMP, context.getTimeStampAsISO8601()); addInstanceToEntity(feedInstanceVertex, datasourceName, RelationshipType.DATASOURCE_ENTITY, RelationshipLabel.DATASOURCE_IMPORT_EDGE, properties); addInstanceToEntity(feedInstanceVertex, sourceClusterName, RelationshipType.CLUSTER_ENTITY, RelationshipLabel.FEED_CLUSTER_EDGE, properties); }
Source:
private void createReasonNote(ActionForm form) { CuPurchasingAccountsPayableModuleService cuPurchasingAccountsPayableModuleService = (CuPurchasingAccountsPayableModuleService) SpringContext.getService("purchasingAccountsPayableModuleService"); PurchasingFormBase purForm = (PurchasingFormBase) form; cuPurchasingAccountsPayableModuleService.createAndSaveNote(purForm.getDocument(), purForm.getReasonToChange()); purForm.setReasonToChange(StringUtils.EMPTY); }

Target:
private void createReasonNote(ActionForm form) { CuPurchasingAccountsPayableModuleService cuPurchasingAccountsPayableModuleService = (CuPurchasingAccountsPayableModuleService) SpringContext.getBean(PurchasingAccountsPayableModuleService.class); PurchasingFormBase purForm = (PurchasingFormBase) form; cuPurchasingAccountsPayableModuleService.createAndSaveNote(purForm.getDocument(), purForm.getReasonToChange()); purForm.setReasonToChange(StringUtils.EMPTY); }
Source:
public void addAlignment(final SAMRecord alignment) { if (sortOrder.equals(SAMFileHeader.SortOrder.unsorted)) { writeAlignment(alignment); } else if (presorted) { assertPresorted(alignment); writeAlignment(alignment); } else { alignmentSorter.add(alignment); } }

Target:
public void addAlignment(final SAMRecord alignment) { if (null == alignment.getHeader()) { alignment.setHeader(header); } if (sortOrder.equals(SAMFileHeader.SortOrder.unsorted)) { writeAlignment(alignment); } else if (presorted) { assertPresorted(alignment); writeAlignment(alignment); } else { alignmentSorter.add(alignment); } }
Source:
public boolean checkTrigger(GameEvent event, Game game) { Permanent enchantment = game.getPermanent(this.getSourceId()); if (enchantment != null && enchantment.getAttachedTo() != null && game.getCombat().getPlayerDefenders(game).contains(enchantment.getAttachedTo())) { for (Effect effect: this.getEffects()) { effect.setTargetPointer(new FixedTarget(game.getCombat().getAttackerId())); } return true; } return false; }

Target:
public boolean checkTrigger(GameEvent event, Game game) { Permanent enchantment = game.getPermanentOrLKIBattlefield(this.getSourceId()); UUID controller = this.getControllerId(); if (enchantment != null && enchantment.getAttachedTo() != null && game.getCombat().getPlayerDefenders(game).contains(enchantment.getAttachedTo())) { if (!game.getCombat().getAttackerId().equals(controller)) { for (Effect effect: this.getEffects()) { effect.setTargetPointer(new FixedTarget(game.getCombat().getAttackerId())); } } return true; } return false; }
Source:
public JSONWithPadding addIndex(@Context UriInfo ui, @PathParam( "applicationId" ) final String applicationIdStr, Map<String, Object> config, @QueryParam( "callback" ) @DefaultValue( "callback" ) String callback) throws Exception{ ApiResponse response = createApiResponse(); final UUID appId = UUIDUtils.tryExtractUUID(applicationIdStr); if (!config.containsKey("replicas") || !config.containsKey("shards") || !(config.get("replicas") instanceof Integer) || !(config.get("shards") instanceof Integer)){ throw new IllegalArgumentException("body must contains 'replicas' of type int and 'shards' of type int"); } if(!config.containsKey("indexSuffix")) { throw new IllegalArgumentException("Please add an indexSuffix to your post"); } String writeConsistency = config.get("writeConsistency") != null ? (String)config.get("writeConsistency") : "one" ; emf.addIndex(appId, config.get("indexSuffix").toString(), (int) config.get("shards"),(int) config.get("replicas"),writeConsistency); response.setAction("Add index to alias"); return new JSONWithPadding(response, callback); }

Target:
public JSONWithPadding addIndex(@Context UriInfo ui, @PathParam( "applicationId" ) final String applicationIdStr, Map<String, Object> config, @QueryParam( "callback" ) @DefaultValue( "callback" ) String callback) throws Exception{ ApiResponse response = createApiResponse(); final UUID appId = UUIDUtils.tryExtractUUID(applicationIdStr); if (!config.containsKey("replicas") || !config.containsKey("shards") || !(config.get("replicas") instanceof Integer) || !(config.get("shards") instanceof Integer)){ throw new IllegalArgumentException("body must contains 'replicas' of type int and 'shards' of type int"); } if(!config.containsKey("indexSuffix")) { throw new IllegalArgumentException("Please add an indexSuffix to your post"); } emf.addIndex(appId, config.get("indexSuffix").toString(), (int) config.get("shards"),(int) config.get("replicas"),(String)config.get("writeConsistency")); response.setAction("Add index to alias"); return new JSONWithPadding(response, callback); }
Source:
private Document createContentsFile(List<GodToolsTranslation> godToolsTranslationList) throws ParserConfigurationException { Document contents = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element rootElement = contents.createElement("content"); contents.appendChild(rootElement); for(GodToolsTranslation godToolsTranslation : godToolsTranslationList) { Element resourceElement = contents.createElement("resource"); resourceElement.setAttribute("package", godToolsTranslation.getPackageCode()); resourceElement.setAttribute("language", godToolsTranslation.getLanguage().getPath()); resourceElement.setAttribute("config", godToolsTranslation.getTranslation().getId() + ".xml"); resourceElement.setAttribute("status", godToolsTranslation.isDraft() ? "draft" : "live"); resourceElement.setAttribute("name", godToolsTranslation.getPackageStructure().getPackageName()); resourceElement.setAttribute("version", godToolsTranslation.getVersionNumber().toPlainString()); if (!textOnly) { if (godToolsTranslation.getIcon() != null) { resourceElement.setAttribute("icon", GuavaHashGenerator.calculateHash(godToolsTranslation.getIcon().getImageContent()) + ".png"); } else { resourceElement.setAttribute("icon", "missing"); } rootElement.appendChild(resourceElement); } } return contents; }

Target:
private Document createContentsFile(List<GodToolsTranslation> godToolsTranslationList) throws ParserConfigurationException { Document contents = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element rootElement = contents.createElement("content"); contents.appendChild(rootElement); for(GodToolsTranslation godToolsTranslation : godToolsTranslationList) { Element resourceElement = contents.createElement("resource"); resourceElement.setAttribute("package", godToolsTranslation.getPackageCode()); resourceElement.setAttribute("language", godToolsTranslation.getLanguage().getPath()); resourceElement.setAttribute("config", godToolsTranslation.getTranslation().getId() + ".xml"); resourceElement.setAttribute("status", godToolsTranslation.isDraft() ? "draft" : "live"); resourceElement.setAttribute("name", godToolsTranslation.getPackageStructure().getPackageName()); resourceElement.setAttribute("version", godToolsTranslation.getVersionNumber().toPlainString()); if (includeImages) { if (godToolsTranslation.getIcon() != null) { resourceElement.setAttribute("icon", GuavaHashGenerator.calculateHash(godToolsTranslation.getIcon().getImageContent()) + ".png"); } else { resourceElement.setAttribute("icon", "missing"); } rootElement.appendChild(resourceElement); } } return contents; }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((outcomes == null) ? 0 : outcomes.hashCode()); result = prime * result + ((probs == null) ? 0 : probs.hashCode()); long temp; temp = Double.doubleToLongBits(score); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; }

Target:
public int hashCode() { return Objects.hash(outcomes, probs, score); }
Source:
private static DetailedSample getParent(DetailedSampleDto childDto) { DetailedSample parent = null; if (childDto.getParentId() != null) { parent = new DetailedSampleImpl(); parent.setId(childDto.getParentId()); } else { if (childDto instanceof SampleIdentityDto && childDto.getClass() != SampleIdentityDto.class) { parent = toIdentitySample((SampleIdentityDto) childDto); } if (childDto instanceof SampleTissueDto && childDto.getClass() != SampleTissueDto.class) { if (childDto.getParentSampleClassId() == null) { throw new IllegalArgumentException("No tissue class specified."); } DetailedSample tissue = toTissueSample((SampleTissueDto) childDto); tissue.setSampleClass(new SampleClassImpl()); tissue.getSampleClass().setId(childDto.getParentSampleClassId()); tissue.setParent(parent); parent = tissue; } if (childDto instanceof SampleStockDto && childDto.getClass() != SampleStockDto.class) { DetailedSample stock = toStockSample((SampleStockDto) childDto); stock.setSampleClass(new SampleClassImpl()); stock.getSampleClass().setId(((SampleAliquotDto) childDto).getStockClassId()); stock.setParent(parent); parent = stock; } } return parent; }

Target:
private static DetailedSample getParent(DetailedSampleDto childDto) { DetailedSample parent = null; if (childDto.getParentId() != null) { parent = new DetailedSampleImpl(); parent.setId(childDto.getParentId()); } else { if (childDto instanceof SampleIdentityDto && childDto.getClass() != SampleIdentityDto.class) { parent = toIdentitySample((SampleIdentityDto) childDto); } if (childDto instanceof SampleTissueDto && childDto.getClass() != SampleTissueDto.class) { if (childDto.getParentTissueSampleClassId() == null) { throw new IllegalArgumentException("No tissue class specified."); } DetailedSample tissue = toTissueSample((SampleTissueDto) childDto); tissue.setSampleClass(new SampleClassImpl()); tissue.getSampleClass().setId(childDto.getParentTissueSampleClassId()); tissue.setParent(parent); parent = tissue; } if (childDto instanceof SampleStockDto && childDto.getClass() != SampleStockDto.class) { DetailedSample stock = toStockSample((SampleStockDto) childDto); stock.setSampleClass(new SampleClassImpl()); stock.getSampleClass().setId(((SampleAliquotDto) childDto).getStockClassId()); stock.setParent(parent); parent = stock; } } return parent; }
Source:
Slice(boolean[] base, int offset, int length) { requireNonNull(base, "base is null"); checkPositionIndexes(offset, offset + length, base.length); this.base = base; this.address = ARRAY_BOOLEAN_BASE_OFFSET + (offset * ARRAY_BOOLEAN_INDEX_SCALE); this.size = length * ARRAY_BOOLEAN_INDEX_SCALE; this.retainedSize = INSTANCE_SIZE + base.length * ARRAY_BOOLEAN_INDEX_SCALE; this.reference = null; }

Target:
Slice(boolean[] base, int offset, int length) { requireNonNull(base, "base is null"); checkPositionIndexes(offset, offset + length, base.length); this.base = base; this.address = ARRAY_BOOLEAN_BASE_OFFSET + offset * ARRAY_BOOLEAN_INDEX_SCALE; this.size = length * ARRAY_BOOLEAN_INDEX_SCALE; this.retainedSize = INSTANCE_SIZE + base.length * ARRAY_BOOLEAN_INDEX_SCALE; this.reference = null; }
Source:
public DeleteTenant(RxSession session, MetricsService metricsService) { this.session = session; this.metricsService = metricsService; deleteTenant = session.getSession().prepare("DELETE FROM tenants WHERE id = ?"); deleteData = session.getSession().prepare( "DELETE FROM data WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = 0"); deleteFromMetricsIndex = session.getSession().prepare( "DELETE FROM metrics_idx WHERE tenant_id = ? AND type = ? AND metric = ?"); deleteTag = session.getSession().prepare("DELETE FROM metrics_tags_idx WHERE tenant_id = ? AND tname = ? " + "AND tvalue = ? AND type = ? AND metric = ?"); deleteRetentions = session.getSession().prepare("DELETE FROM retentions_idx WHERE tenant_id = ? AND type = ?"); }

Target:
public DeleteTenant(RxSession session, MetricsService metricsService) { this.session = session; this.metricsService = metricsService; deleteTenant = session.getSession().prepare("DELETE FROM tenants WHERE id = ?"); deleteData = session.getSession().prepare( "DELETE FROM data WHERE tenant_id = ? AND type = ? AND metric = ? AND dpart = 0"); deleteFromMetricsIndex = session.getSession().prepare( "DELETE FROM metrics_idx WHERE tenant_id = ? AND type = ?"); findTags = session.getSession().prepare("SELECT DISTINCT tenant_id, tname FROM metrics_tags_idx"); deleteTag = session.getSession().prepare("DELETE FROM metrics_tags_idx WHERE tenant_id = ? AND tname = ?"); deleteRetentions = session.getSession().prepare("DELETE FROM retentions_idx WHERE tenant_id = ? AND type = ?"); }
Source:
public void updateExistingPaymentWorksVendorInStagingTable(Integer id, String pmwRequestStatus, String kfsVendorProcessingStatus, Timestamp processingTimeStamp) { updateExistingPaymentWorksVendorInStagingTable(id, pmwRequestStatus, kfsVendorProcessingStatus, null, null, null, processingTimeStamp, null, null, null); }

Target:
public void updateExistingPaymentWorksVendorInStagingTable(Integer id, String pmwRequestStatus, String kfsVendorProcessingStatus, Timestamp processingTimeStamp) { updateExistingPaymentWorksVendorInStagingTable(id, pmwRequestStatus, kfsVendorProcessingStatus, KFSConstants.EMPTY_STRING, KFSConstants.EMPTY_STRING, KFSConstants.EMPTY_STRING, processingTimeStamp, null, null, null); }
Source:
public void theBundleRequestContainsAFindEventsAction(final Map<String, String> parameters) throws Throwable { final BundleRequest request = (BundleRequest) ScenarioContext.current() .get(PlatformSmartmeteringKeys.BUNDLE_REQUEST); final FindEventsRequest action = new FindEventsRequestBuilder().fromParameterMap(parameters).build(); this.addActionToBundleRequest(request, action); }

Target:
public void theBundleRequestContainsAFindEventsAction(final Map<String, String> parameters) throws Throwable { final FindEventsRequest action = new FindEventsRequestBuilder().fromParameterMap(parameters).build(); this.addActionToBundleRequest(action); }
Source:
public AlertsUpdateEtagTrigger() { super("portal.alerts_etags", 15); }

Target:
public AlertsUpdateEtagTrigger() { super(AlertEtags::incrementEtag, 15); }
Source:
public void testSendAndReceive() throws Exception { Binder binder = getBinder(); BindingProperties outputBindingProperties = createProducerBindingProperties(createProducerProperties()); DirectChannel moduleOutputChannel = createBindableChannel("output", outputBindingProperties); QueueChannel moduleInputChannel = new QueueChannel(); Binding<MessageChannel> producerBinding = binder.bindProducer("foo.0", moduleOutputChannel, outputBindingProperties.getProducer()); Binding<MessageChannel> consumerBinding = binder.bindConsumer("foo.0", "test", moduleInputChannel, createConsumerProperties()); Message<?> message = MessageBuilder.withPayload("foo").setHeader(MessageHeaders.CONTENT_TYPE, "foo/bar") .build(); binderBindUnbindLatency(); moduleOutputChannel.send(message); Message<?> inbound = receive(moduleInputChannel, 5); assertThat(inbound).isNotNull(); assertThat(inbound.getPayload()).isEqualTo("foo"); assertThat(inbound.getHeaders().get(BinderHeaders.BINDER_ORIGINAL_CONTENT_TYPE)).isNull(); assertThat(inbound.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isEqualTo("foo/bar"); producerBinding.unbind(); consumerBinding.unbind(); }

Target:
public void testSendAndReceive() throws Exception { Binder binder = getBinder(); BindingProperties outputBindingProperties = createProducerBindingProperties(createProducerProperties()); DirectChannel moduleOutputChannel = createBindableChannel("output", outputBindingProperties); QueueChannel moduleInputChannel = new QueueChannel(); Binding<MessageChannel> producerBinding = binder.bindProducer("foo.0", moduleOutputChannel, outputBindingProperties.getProducer()); Binding<MessageChannel> consumerBinding = binder.bindConsumer("foo.0", "test", moduleInputChannel, createConsumerProperties()); Message<?> message = MessageBuilder.withPayload("foo").setHeader(MessageHeaders.CONTENT_TYPE, "foo/bar") .build(); binderBindUnbindLatency(); moduleOutputChannel.send(message); Message<?> inbound = receive(moduleInputChannel); assertThat(inbound).isNotNull(); assertThat(inbound.getPayload()).isEqualTo("foo"); assertThat(inbound.getHeaders().get(BinderHeaders.BINDER_ORIGINAL_CONTENT_TYPE)).isNull(); assertThat(inbound.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isEqualTo("foo/bar"); producerBinding.unbind(); consumerBinding.unbind(); }
Source:
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { if ( isJettyMode() && !request.getContextPath().startsWith( CONTEXT_PATH ) ) { return; } if ( log.isDebug() ) { logDebug( BaseMessages.getString( PKG, "GetJobImageServlet.Log.JobImageRequested" ) ); } String jobName = request.getParameter( "name" ); String id = request.getParameter( "id" ); boolean useXML = "Y".equalsIgnoreCase( request.getParameter( "xml" ) ); Job job; CarteObjectEntry entry = null; if ( Utils.isEmpty( id ) ) { try { entry = getJobMap().getUniqueCarteObjectEntry( jobName ); } catch ( DuplicateKeyException e ) { buildDuplicateResponse( response, jobName, useXML ); } if ( entry == null ) { job = null; } else { id = entry.getId(); job = getJobMap().getJob( entry ); } } else { entry = new CarteObjectEntry( jobName, id ); job = getJobMap().getJob( entry ); } try { if ( job != null ) { response.setStatus( HttpServletResponse.SC_OK ); response.setCharacterEncoding( "UTF-8" ); response.setContentType( "image/png" ); BufferedImage image = generateJobImage( job.getJobMeta() ); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { ImageIO.write( image, "png", os ); } finally { os.flush(); } response.setContentLength( os.size() ); OutputStream out = response.getOutputStream(); out.write( os.toByteArray() ); } } catch ( Exception e ) { e.printStackTrace(); } }

Target:
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { if ( isJettyMode() && !request.getContextPath().startsWith( CONTEXT_PATH ) ) { return; } if ( log.isDebug() ) { logDebug( BaseMessages.getString( PKG, "GetJobImageServlet.Log.JobImageRequested" ) ); } String jobName = request.getParameter( "name" ); String id = request.getParameter( "id" ); boolean useXML = "Y".equalsIgnoreCase( request.getParameter( "xml" ) ); Job job; CarteObjectEntry entry; if ( Utils.isEmpty( id ) ) { try { entry = getJobMap().getUniqueCarteObjectEntry( jobName ); } catch ( DuplicateKeyException e ) { buildDuplicateResponse( response, jobName, useXML ); return; } if ( entry == null ) { job = null; } else { id = entry.getId(); job = getJobMap().getJob( entry ); } } else { entry = new CarteObjectEntry( jobName, id ); job = getJobMap().getJob( entry ); } try { if ( job != null ) { buildOkResponse( response, job ); } else { buildNotFoundResponse( response, jobName, id, useXML ); } } catch ( Exception e ) { e.printStackTrace(); } }
Source:
private KafkaLog4jAppender createKafkaAppender() { KafkaLog4jAppender kafkaProducer = new KafkaLog4jAppender(); Props azkProps = AzkabanExecutorServer.getApp().getAzkabanProps(); kafkaProducer.setSyncSend(false); kafkaProducer.setBrokerList(azkProps.getString("kafkaLogging.brokerList")); kafkaProducer.setTopic(azkProps.getString("kafkaLogging.topic")); JSONObject layout = new JSONObject(); layout.put("category", "%c{1}"); layout.put("level", "%p"); layout.put("message", "%m"); layout.put("projectname", props.getString("azkaban.flow.projectname")); layout.put("flowid", props.getString("azkaban.flow.flowid")); layout.put("submituser", props.getString("azkaban.flow.submituser")); layout.put("execid", props.getString("azkaban.flow.execid")); layout.put("projectversion", props.getString("azkaban.flow.projectversion")); layout.put("logsource", "userJob"); kafkaProducer.setLayout(new EnhancedPatternLayout(layout.toString())); kafkaProducer.activateOptions(); flowLogger.info("Created kafka appender for " + this.jobId); return kafkaProducer; }

Target:
private KafkaLog4jAppender createKafkaAppender() throws UndefinedPropertyException { KafkaLog4jAppender kafkaProducer = new KafkaLog4jAppender(); kafkaProducer.setSyncSend(false); kafkaProducer.setBrokerList(azkabanProps.getString(ServerProperties.AZKABAN_SERVER_LOGGING_KAFKA_BROKERLIST)); kafkaProducer.setTopic(azkabanProps.getString(ServerProperties.AZKABAN_SERVER_LOGGING_KAFKA_TOPIC)); JSONObject layout = new JSONObject(); layout.put("category", "%c{1}"); layout.put("level", "%p"); layout.put("message", "%m"); layout.put("projectname", props.getString(FlowProperties.AZKABAN_FLOW_PROJECT_NAME)); layout.put("flowid", props.getString(FlowProperties.AZKABAN_FLOW_FLOW_ID)); layout.put("submituser", props.getString(FlowProperties.AZKABAN_FLOW_SUBMIT_USER)); layout.put("execid", props.getString(FlowProperties.AZKABAN_FLOW_EXEC_ID)); layout.put("projectversion", props.getString(FlowProperties.AZKABAN_FLOW_PROJECT_VERSION)); layout.put("logsource", "userJob"); kafkaProducer.setLayout(new EnhancedPatternLayout(layout.toString())); kafkaProducer.activateOptions(); flowLogger.info("Created kafka appender for " + this.jobId); return kafkaProducer; }
Source:
public Collection getCollectionById(@ApiParam(hidden = true) @Auth Optional<User> user, @ApiParam(value = "Organisation ID.", required = true) @PathParam("organisationId") Long organisationId, @ApiParam(value = "Collection ID.", required = true) @PathParam("collectionId") Long collectionId) { if (!user.isPresent()) { Collection collection = collectionDAO.findById(collectionId); if (collection == null) { String msg = "Collection not found."; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_BAD_REQUEST); } Organisation organisation = organisationDAO.findApprovedById(collection.getOrganisation().getId()); if (organisation == null) { String msg = "Collection not found."; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_BAD_REQUEST); } return collection; } else { boolean doesCollectionExist = doesCollectionExistToUser(collectionId, user.get().getId()) || user.get().getIsAdmin() || user.get().isCurator(); if (!doesCollectionExist) { String msg = "Collection not found."; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_BAD_REQUEST); } Collection collection = collectionDAO.findById(collectionId); return collection; } }

Target:
public Collection getCollectionById(@ApiParam(hidden = true) @Auth Optional<User> user, @ApiParam(value = "Organisation ID.", required = true) @PathParam("organisationId") Long organisationId, @ApiParam(value = "Collection ID.", required = true) @PathParam("collectionId") Long collectionId) { if (!user.isPresent()) { Collection collection = collectionDAO.findById(collectionId); if (collection == null) { String msg = "Collection not found."; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_NOT_FOUND); } Organisation organisation = organisationDAO.findApprovedById(collection.getOrganisation().getId()); if (organisation == null) { String msg = "Collection not found."; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_NOT_FOUND); } return collection; } else { boolean doesCollectionExist = doesCollectionExistToUser(collectionId, user.get().getId()) || user.get().getIsAdmin() || user.get().isCurator(); if (!doesCollectionExist) { String msg = "Collection not found."; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_NOT_FOUND); } Collection collection = collectionDAO.findById(collectionId); return collection; } }
Source:
public void executeCommand() { super.executeImportVm(!isUnregisteredVM()); if (isUnregisteredVM()) { getUnregisteredOVFDataDao().removeEntity(ovfEntityData.getVmId(), ovfEntityData.getStorageDomainId()); } else if (!vmDisksToAttach.isEmpty()) { AuditLogDirector.log(this, attemptToAttachDisksToImportedVm(vmDisksToAttach)); } setActionReturnValue(getVm().getId()); }

Target:
public void executeCommand() { super.executeImportVm(!isUnregisteredVM()); if (getSucceeded()) { if (isUnregisteredVM()) { getUnregisteredOVFDataDao().removeEntity(ovfEntityData.getVmId(), ovfEntityData.getStorageDomainId()); } else if (!vmDisksToAttach.isEmpty()) { AuditLogDirector.log(this, attemptToAttachDisksToImportedVm(vmDisksToAttach)); } } setActionReturnValue(getVm().getId()); }
Source:
public Blob findOrCreateByPath(String tenantId, String path) { String sanitizedPath = utils.sanitizePath(path); if (Strings.isEmpty(sanitizedPath)) { throw new IllegalArgumentException("An empty path was provided!"); } String key = determinePathCacheKey(tenantId, sanitizedPath); Blob blob = blobByPathCache.get(key); if (blob == null) { blobByPathCache.remove(key); blob = fetchOrCreateByPath(tenantId, sanitizedPath); } return blob; }

Target:
public Blob findOrCreateByPath(String tenantId, String path) { String sanitizedPath = utils.sanitizePath(path); if (Strings.isEmpty(sanitizedPath)) { throw new IllegalArgumentException("An empty path was provided!"); } String key = determinePathCacheKey(tenantId, sanitizedPath); Blob blob = blobByPathCache.get(key); if (blob == null) { blobByPathCache.remove(key); blob = fetchOrCreateByPath(tenantId, sanitizedPath); blobByPathCache.put(key, blob); } return blob; }
Source:
public static void init() { if (!glusterModeSupported()) { log.debug("Gluster mode not supported. Will not schedule jobs for refreshing Gluster data."); return; } log.debug("Initializing Gluster Jobs Manager"); SchedulerUtil scheduler = SchedulerUtilQuartzImpl.getInstance(); scheduler.scheduleAFixedDelayJob(GlusterSyncJob.getInstance(), "refreshLightWeightData", new Class[0], new Object[0], getRefreshRate(ConfigValues.GlusterRefreshRateLight), getRefreshRate(ConfigValues.GlusterRefreshRateLight), TimeUnit.SECONDS); scheduler.scheduleAFixedDelayJob(GlusterSyncJob.getInstance(), "refreshHeavyWeightData", new Class[0], new Object[0], getRefreshRate(ConfigValues.GlusterRefreshRateHeavy), getRefreshRate(ConfigValues.GlusterRefreshRateHeavy), TimeUnit.SECONDS); scheduler.scheduleAFixedDelayJob(GlusterHookSyncJob.getInstance(), "refreshHooks", new Class[0], new Object[0], getRefreshRate(ConfigValues.GlusterRefreshRateHooks), getRefreshRate(ConfigValues.GlusterRefreshRateHooks), TimeUnit.SECONDS); scheduler.scheduleAFixedDelayJob(GlusterServiceSyncJob.getInstance(), "refreshGlusterServices", new Class[0], new Object[0], getRefreshRate(ConfigValues.GlusterRefreshRateLight), getRefreshRate(ConfigValues.GlusterRefreshRateLight), TimeUnit.SECONDS); scheduler.scheduleAFixedDelayJob(GlusterTasksSyncJob.getInstance(), "gluster_async_task_poll_event", new Class[0] , new Class [0], 30, 30, TimeUnit.SECONDS); }

Target:
public static void init() { if (!glusterModeSupported()) { log.debug("Gluster mode not supported. Will not schedule jobs for refreshing Gluster data."); return; } log.debug("Initializing Gluster Jobs Manager"); SchedulerUtil scheduler = SchedulerUtilQuartzImpl.getInstance(); scheduler.scheduleAFixedDelayJob(GlusterSyncJob.getInstance(), "refreshLightWeightData", new Class[0], new Object[0], getRefreshRate(ConfigValues.GlusterRefreshRateLight), getRefreshRate(ConfigValues.GlusterRefreshRateLight), TimeUnit.SECONDS); scheduler.scheduleAFixedDelayJob(GlusterSyncJob.getInstance(), "refreshHeavyWeightData", new Class[0], new Object[0], getRefreshRate(ConfigValues.GlusterRefreshRateHeavy), getRefreshRate(ConfigValues.GlusterRefreshRateHeavy), TimeUnit.SECONDS); scheduler.scheduleAFixedDelayJob(GlusterHookSyncJob.getInstance(), "refreshHooks", new Class[0], new Object[0], getRefreshRate(ConfigValues.GlusterRefreshRateHooks), getRefreshRate(ConfigValues.GlusterRefreshRateHooks), TimeUnit.SECONDS); scheduler.scheduleAFixedDelayJob(GlusterServiceSyncJob.getInstance(), "refreshGlusterServices", new Class[0], new Object[0], getRefreshRate(ConfigValues.GlusterRefreshRateLight), getRefreshRate(ConfigValues.GlusterRefreshRateLight), TimeUnit.SECONDS); scheduler.scheduleAFixedDelayJob(GlusterTasksSyncJob.getInstance(), "gluster_async_task_poll_event", new Class[0] , new Class [0], getRefreshRate(ConfigValues.GlusterRefreshRateTasks), getRefreshRate(ConfigValues.GlusterRefreshRateTasks), TimeUnit.SECONDS); }
Source:
public Collection<IPatternProvider> getPatternsList() { Collection<IPatternProvider> newPatternList = new ArrayList<IPatternProvider>(); ClassDiagramPattern pattern = new ClassDiagramPattern(); pattern.setPatternCommand(new InitializerCommand(resourceSet, selection)); newPatternList.add(pattern); return newPatternList; }

Target:
public Collection<IPatternProvider> getPatternsList() { Collection<IPatternProvider> newPatternList = new ArrayList<IPatternProvider>(); ClassDiagramPattern pattern = new ClassDiagramPattern(this.resourceSet, this.selection); newPatternList.add(pattern); return newPatternList; }
Source:
@BeforeClass public static void beforeClass() { service = AppiumDriverLocalService.buildDefaultService(); service.start(); if (service == null || !service.isRunning()) { throw new AppiumServerHasNotBeenStartedLocallyException( "An appium server node is not started!"); } File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "ApiDemos-debug.apk"); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.APPIUM); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); driver = new AndroidDriver<>(service.getUrl(), capabilities); }

Target:
@BeforeClass public static void beforeClass() { service = AppiumDriverLocalService.buildDefaultService(); service.start(); if (service == null || !service.isRunning()) { throw new AppiumServerHasNotBeenStartedLocallyException( "An appium server node is not started!"); } File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "ApiDemos-debug.apk"); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.ANDROID_UIAUTOMATOR2); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); driver = new AndroidDriver<>(service.getUrl(), capabilities); }
Source:
public void setOverrideAcceptedPatterns(String acceptablePatterns) { if (LOG.isWarnEnabled()) { LOG.warn("Overriding accepted patterns with [{}], be aware that this affects all instances and safety of your application!", acceptedPatterns, acceptablePatterns); } acceptedPatterns = new HashSet<>(); for (String pattern : TextParseUtil.commaDelimitedStringToSet(acceptablePatterns)) { acceptedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE)); } }

Target:
protected void setOverrideAcceptedPatterns(String acceptablePatterns) { LOG.warn("Overriding accepted patterns with [{}], be aware that this affects all instances and safety of your application!", acceptedPatterns, acceptablePatterns); acceptedPatterns = new HashSet<>(); for (String pattern : TextParseUtil.commaDelimitedStringToSet(acceptablePatterns)) { acceptedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE)); } }
Source:
public static QueryRunner makeMMappedQueryRunner( SegmentId segmentId, boolean rollup, boolean bitmaps, QueryRunnerFactory factory ) { QueryableIndex index = bitmaps ? rollup ? TestIndex.getMMappedTestIndex() : TestIndex.getNoRollupMMappedTestIndex() : TestIndex.getNoBitmapMMappedTestIndex(); return QueryRunnerTestHelper.makeQueryRunner( factory, segmentId, new QueryableIndexSegment(index, segmentId), null ); }

Target:
public static QueryRunner makeMMappedQueryRunner( SegmentId segmentId, boolean rollup, boolean bitmaps, QueryRunnerFactory factory ) { QueryableIndex index; if (bitmaps) { index = rollup ? TestIndex.getMMappedTestIndex() : TestIndex.getNoRollupMMappedTestIndex(); } else { index = TestIndex.getNoBitmapMMappedTestIndex(); } return QueryRunnerTestHelper.makeQueryRunner( factory, segmentId, new QueryableIndexSegment(index, segmentId), null ); }
Source:
public boolean isActionPermitted(Package updatedPack, Action action) { boolean permitted; Package currentPack = delegate().findOneById(updatedPack.getId()); if (action == CREATE || action == UPDATE || action == DELETE) { if ((PackageUtils.isSystemPackage(updatedPack) || PackageUtils.isSystemPackage(currentPack)) && !currentUserIsSystem()) { throw new SystemMetadataModificationException(); } } if (action == CREATE || action == DELETE) { permitted = isActionPermittedOnParent(updatedPack, action); } else if (action == UPDATE) { permitted = isActionPermittedOnParent(updatedPack, action) && internalIsActionPermitted(updatedPack.getId(), action); } else { permitted = internalIsActionPermitted(updatedPack.getId(), action); } return permitted; }

Target:
public boolean isActionPermitted(Package updatedPack, Action action) { boolean permitted; Package currentPack = delegate().findOneById(updatedPack.getId()); if ((action == CREATE || action == UPDATE || action == DELETE) && ((PackageUtils.isSystemPackage(updatedPack) || PackageUtils.isSystemPackage(currentPack)) && !currentUserIsSystem())) { throw new SystemMetadataModificationException(); } if (action == CREATE || action == DELETE) { permitted = isActionPermittedOnParent(updatedPack, action); } else if (action == UPDATE) { permitted = isActionPermittedOnParent(updatedPack, action) && internalIsActionPermitted(updatedPack.getId(), action); } else { permitted = internalIsActionPermitted(updatedPack.getId(), action); } return permitted; }
Source:
public Object create(String type, ApiRequest request, ResourceManager next) { Map<String, Object> data = CollectionUtils.toMap(request.getRequestObject()); Object imageUuid = data.get(InstanceConstants.FIELD_IMAGE_UUID); if (imageUuid != null) { String image = imageUuid.toString(); String userProvidedRegistry = DockerImage.parse(image).getServer(); String whitelist = WHITELIST_REGISTRIES.get(); String[] whitelist_registries; if (specified(whitelist)) { whitelist_registries = WHITELIST_REGISTRIES.get().split(","); if (!contains(whitelist_registries,userProvidedRegistry)) { throw new ValidationErrorException(ValidationErrorCodes.INVALID_OPTION, InstanceConstants.FIELD_IMAGE_UUID); } } } return super.create(type, request, next); }

Target:
public Object create(String type, ApiRequest request, ResourceManager next) { Map<String, Object> data = CollectionUtils.toMap(request.getRequestObject()); Object imageUuid = data.get(InstanceConstants.FIELD_IMAGE_UUID); if (imageUuid != null) { String image = imageUuid.toString(); String fullImageName = getImageUuid(image, storageService); if (!StringUtils.equals(image, fullImageName)) { data.put(InstanceConstants.FIELD_IMAGE_UUID, fullImageName); request.setRequestObject(data); } } return super.create(type, request, next); }
Source:
Mono<Response<NamedEntityResult>> recognizeEntitiesWithResponse(String text, String language, Context context) { List<TextDocumentInput> documentInputs = new ArrayList<>(); documentInputs.add(new TextDocumentInput(Integer.toString(0), text, language)); return recognizeBatchEntitiesWithResponse(documentInputs, null, context).flatMap(response -> { Iterator<NamedEntityResult> responseItem = response.getValue().iterator(); if (responseItem.hasNext()) { return Mono.just(new SimpleResponse<>(response, responseItem.next())); } return monoError(logger, new RuntimeException("Unable to recognize entities for the provided text.")); }); }

Target:
Mono<Response<RecognizeEntitiesResult>> recognizeEntitiesWithResponse(String text, String language, Context context) { Objects.requireNonNull(text, "'text' cannot be null."); return recognizeBatchEntitiesWithResponse( Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); }
Source:
private void setRouteTimeout(IResource resource, Connection connection, IProgressMonitor monitor) { monitor.subTask("Increasing route timeout while debugging..."); IRoute route = getRoute(resource, connection, monitor); if (route == null) { OpenShiftCoreActivator.pluginLog().logInfo( NLS.bind("Could not increase timeout for debugging: could not find any route for resource {0}", resource.getName())); return; } OpenShiftCoreActivator.pluginLog().logInfo( NLS.bind("Setting haproxy timeout for route {0}", route.getName())); if (!hasTimeoutAnnotation(route)) { route.setAnnotation(OpenShiftAPIAnnotations.TIMEOUT, ROUTE_DEBUG_TIMEOUT); safeSend(route, connection, monitor); } }

Target:
private void setRouteTimeout(IResource resource, Connection connection, IProgressMonitor monitor) throws CoreException { monitor.subTask("Increasing route timeout while debugging..."); IRoute route = new RouteTimeout(resource, connection).set(context, monitor); if (route != null) { safeSend(route, connection, monitor); } }
Source:
private void openFileFromExternalLibraryAndCheckDisplayedText() { projectExplorer.waitVisibilityByName("README.md"); projectExplorer.waitVisibilityByName("pom.xml"); projectExplorer.waitVisibilityByName("External Libraries"); projectExplorer.openItemByVisibleNameInExplorer("External Libraries"); projectExplorer.openItemByVisibleNameInExplorer("servlet-api-2.5.jar"); projectExplorer.openItemByVisibleNameInExplorer("javax.servlet"); projectExplorer.openItemByVisibleNameInExplorer("Filter"); editor.waitActive(); editor.waitTabIsPresent("Filter"); editor.waitTextIntoEditor(EXPECTED_EDITOR_TEXT); }

Target:
private void openFileFromExternalLibraryAndCheckDisplayedText() { projectExplorer.waitVisibilitySeveralItemsByName("README.md", "pom.xml", "External Libraries"); projectExplorer.openSeveralItemsByVisibleNameInExplorer( "External Libraries", "servlet-api-2.5.jar", "javax.servlet", CHECKING_FILE_NAME); editor.waitActive(); editor.waitTabIsPresent(CHECKING_FILE_NAME); editor.waitTextIntoEditor(EXPECTED_EDITOR_TEXT); }
Source:
protected void handleUnloadRequest(HttpServletRequest req, HttpServletResponse resp, String uiSessionId) { LOG.info("Unloading UI session with ID (requested by {})", uiSessionId, this.getClass().getSimpleName()); final HttpSession httpSession = req.getSession(); final ISessionStore sessionStore = BEANS.get(HttpSessionHelper.class).getSessionStore(httpSession); IUiSession uiSession = sessionStore.getUiSession(uiSessionId); if (uiSession != null) { final ReentrantLock uiSessionLock = uiSession.uiSessionLock(); uiSessionLock.lock(); try { uiSession.dispose(); } finally { uiSessionLock.unlock(); } } }

Target:
protected void handleUnloadRequest(HttpServletRequest req, HttpServletResponse resp, String uiSessionId) { LOG.info("Unloading UI session with ID (requested by UI)", uiSessionId); final HttpSession httpSession = req.getSession(); final ISessionStore sessionStore = BEANS.get(HttpSessionHelper.class).getSessionStore(httpSession); IUiSession uiSession = sessionStore.getUiSession(uiSessionId); if (uiSession != null) { final ReentrantLock uiSessionLock = uiSession.uiSessionLock(); uiSessionLock.lock(); try { uiSession.dispose(); } finally { uiSessionLock.unlock(); } } }
Source:
public void visitCompilationUnit(CompilationUnitTree tree) { PackageDeclarationTree packageDeclaration = tree.packageDeclaration(); if (packageDeclaration != null) { String packageName = PackageUtils.packageName(packageDeclaration, File.separator); File javaFile = context.getFile(); String dir = javaFile.getParent(); if (!dir.endsWith(packageName)) { String dirWithoutDots = dir.replace(".", "/"); String issueMessage = MessageFormat.format(MESSAGE, javaFile.getName(), packageName, dir); if (dirWithoutDots.endsWith(packageName)) { context.reportIssue(this, packageDeclaration.packageName(), issueMessage + "(Do not use dots in directory names)."); } else { context.reportIssue( this, packageDeclaration.packageName(), issueMessage + "."); } } } }

Target:
public void visitCompilationUnit(CompilationUnitTree tree) { PackageDeclarationTree packageDeclaration = tree.packageDeclaration(); if (packageDeclaration != null) { String packageName = PackageUtils.packageName(packageDeclaration, File.separator); File javaFile = context.getFile(); String dir = javaFile.getParent(); if (!dir.endsWith(packageName)) { String dirWithoutDots = dir.replace(".", File.separator); String issueMessage = MessageFormat.format(MESSAGE, javaFile.getName(), packageName, dir); if (dirWithoutDots.endsWith(packageName)) { context.reportIssue(this, packageDeclaration.packageName(), issueMessage + "(Do not use dots in directory names)."); } else { context.reportIssue( this, packageDeclaration.packageName(), issueMessage + "."); } } } }
Source:
public void setupTest() { this.mockQuery = Mockito.mock(Query.class); this.mockResult = Mockito.mock(Result.class); this.mockServer = Mockito.mock(Server.class); tvAddHostnameTagDefault = true; prepareSenderCalled = false; shutdownSenderCalled = false; startOutputCalled = false; finishOutputCalled = false; tvMetricLinesSent = new LinkedList<String>(); Mockito.when(this.mockResult.getValues()).thenReturn(ImmutableMap.of("x-att1-x", (Object) "120021")); Mockito.when(this.mockResult.getAttributeName()).thenReturn("X-ATT-X"); Mockito.when(this.mockResult.getClassName()).thenReturn("X-DOMAIN.PKG.CLASS-X"); Mockito.when(this.mockResult.getTypeName()). thenReturn("Type=x-type-x,Group=x-group-x,Other=x-other-x,Name=x-name-x"); Mockito.when(this.mockServer.getLabel()).thenReturn("myhostname"); }

Target:
public void setupTest() { this.mockQuery = Mockito.mock(Query.class); this.mockResult = Mockito.mock(Result.class); tvAddHostnameTagDefault = true; prepareSenderCalled = false; shutdownSenderCalled = false; startOutputCalled = false; finishOutputCalled = false; tvMetricLinesSent = new LinkedList<String>(); Mockito.when(this.mockResult.getValues()).thenReturn(ImmutableMap.of("x-att1-x", (Object) "120021")); Mockito.when(this.mockResult.getAttributeName()).thenReturn("X-ATT-X"); Mockito.when(this.mockResult.getClassName()).thenReturn("X-DOMAIN.PKG.CLASS-X"); Mockito.when(this.mockResult.getTypeName()). thenReturn("Type=x-type-x,Group=x-group-x,Other=x-other-x,Name=x-name-x"); }
Source:
protected int doWork() { IOUtil.assertFileIsWritable(CHART_OUTPUT); return super.doWork(); }

Target:
protected int doWork() { IOUtil.assertFileIsWritable(CHART_OUTPUT); IOUtil.assertFileIsReadable(INPUT); getSamReader(); this.collector = new WgsMetricsWithNonZeroCoverageCollector(COVERAGE_CAP, getIntervalsToExamine()); super.doWork(); final List<SAMReadGroupRecord> readGroups = getSamFileHeader().getReadGroups(); final String plotSubtitle = (readGroups.size() == 1) ? StringUtil.asEmptyIfNull(readGroups.get(0).getLibrary()) : ""; if (collector.areHistogramsEmpty()) { log.warn("No valid bases found in input file. No plot will be produced."); } else { final int rResult = RExecutor.executeFromClasspath("picard/analysis/wgsHistogram.R", OUTPUT.getAbsolutePath(), CHART_OUTPUT.getAbsolutePath(), INPUT.getName(), plotSubtitle); if (rResult != 0) { throw new PicardException("R script wgsHistogram.R failed with return code " + rResult); } } return 0; }