auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testGdbSyncServiceCanSwitchGDBStackFrame() throws Throwable { ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<MIStoppedEvent>(fMultiRunControl.getSession(), MIStoppedEvent.class); SyncUtil.addBreakpoint(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_ALL_THREADS_STARTED"), false); SyncUtil.addBreakpoint("36", false); SyncUtil.resumeAll(); IMIExecutionDMContext[] threads = SyncUtil.getExecutionContexts(); System.out.println(threads.toString()); eventWaitor.waitForEvent(2000); eventWaitor.waitForEvent(2000); eventWaitor.waitForEvent(2000); eventWaitor.waitForEvent(2000); eventWaitor.waitForEvent(2000); for (int i = 0; i < 2; i++) { fGdbSync.setCurrentGDBStackFrame(SyncUtil.getStackFrame(1, 1)); assertEquals("1", getCurrentStackFrameLevel()); fGdbSync.setCurrentGDBStackFrame(SyncUtil.getStackFrame(1, 0)); assertEquals("0", getCurrentStackFrameLevel()); } }

Target:
public void testGdbSyncServiceCanSwitchGDBStackFrame() throws Throwable { ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<MIStoppedEvent>(fMultiRunControl.getSession(), MIStoppedEvent.class); SyncUtil.addBreakpoint(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_ALL_THREADS_STARTED"), false); SyncUtil.addBreakpoint("36", false); SyncUtil.resumeAll(); IMIExecutionDMContext[] threads = SyncUtil.getExecutionContexts(); System.out.println(threads.toString()); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); for (int i = 0; i < 2; i++) { fGdbSync.setCurrentGDBStackFrame(SyncUtil.getStackFrame(1, 1)); assertEquals("1", getCurrentStackFrameLevel()); fGdbSync.setCurrentGDBStackFrame(SyncUtil.getStackFrame(1, 0)); assertEquals("0", getCurrentStackFrameLevel()); } }
Source:
protected String buildUrl() { if (isEmpty(serverURL)) { throw new IllegalStateException("server can not be null"); } final StringBuilder sb = new StringBuilder(); sb.append(serverURL).append("rest/sender/"); return sb.toString(); }

Target:
protected String buildUrl() { if (isEmpty(serverURL)) { throw new IllegalStateException("server can not be null"); } return serverURL + "rest/sender/"; }
Source:
private static JSONObject contact(Patient patient) { String name = "PhenomeCentral"; String institution = "PhenomeCentral"; String href = "mailto:matchmaker@phenomecentral.org"; PatientData<String> data = patient.getData("contact"); if (data != null && data.isNamed()) { name = data.get("name"); institution = data.get("institution"); String email = data.get("email"); if (!StringUtils.isBlank(email)) { href = "mailto:" + email; } } JSONObject contactJson = new JSONObject(); contactJson.put(ApiConfiguration.JSON_CONTACT_NAME, name); contactJson.put(ApiConfiguration.JSON_CONTACT_INSTITUTION, institution); contactJson.put(ApiConfiguration.JSON_CONTACT_HREF, href); return contactJson; }

Target:
private static JSONObject contact(Patient patient) { String name = "PhenomeCentral Support"; String institution = "PhenomeCentral"; String href = "mailto:matchmaker@phenomecentral.org"; PatientData<String> data = patient.getData("contact"); if (data != null && data.isNamed()) { String contactName = data.get("name"); if (!StringUtils.isBlank(contactName)) { name = contactName; } institution = data.get("institution"); String email = data.get("email"); if (!StringUtils.isBlank(email)) { href = "mailto:" + email; } } JSONObject contactJson = new JSONObject(); contactJson.put(ApiConfiguration.JSON_CONTACT_NAME, name); if (!StringUtils.isBlank(institution)) { contactJson.put(ApiConfiguration.JSON_CONTACT_INSTITUTION, institution); } contactJson.put(ApiConfiguration.JSON_CONTACT_HREF, href); return contactJson; }
Source:
public void importTable(String tableName, String importDir) throws TableExistsException, AccumuloException, AccumuloSecurityException { checkArgument(tableName != null, "tableName is null"); checkArgument(importDir != null, "importDir is null"); checkArgument(tableName.length() <= MAX_TABLE_NAME_LEN, "Table name is longer than 1024 characters"); try { importDir = checkPath(importDir, "Table", "").toString(); } catch (IOException e) { throw new AccumuloException(e); } try { FileSystem fs = new Path(importDir).getFileSystem(context.getHadoopConf()); Map<String,String> props = getExportedProps(fs, new Path(importDir, Constants.EXPORT_FILE)); for (Entry<String,String> entry : props.entrySet()) { if (Property.isClassProperty(entry.getKey()) && !entry.getValue().contains(Constants.CORE_PACKAGE_NAME)) { LoggerFactory.getLogger(this.getClass()).info( "Imported table sets '{}' to '{}'. Ensure this class is on Accumulo classpath.", sanitize(entry.getKey()), sanitize(entry.getValue())); } } } catch (IOException ioe) { LoggerFactory.getLogger(this.getClass()).warn( "Failed to check if imported table references external java classes : {}", ioe.getMessage()); } List<ByteBuffer> args = Arrays.asList(ByteBuffer.wrap(tableName.getBytes(UTF_8)), ByteBuffer.wrap(importDir.getBytes(UTF_8))); Map<String,String> opts = Collections.emptyMap(); try { doTableFateOperation(tableName, AccumuloException.class, FateOperation.TABLE_IMPORT, args, opts); } catch (TableNotFoundException e) { throw new AssertionError(e); } }

Target:
public void importTable(String tableName, String importDir) throws TableExistsException, AccumuloException, AccumuloSecurityException { checkArgument(tableName != null, "tableName is null"); checkArgument(importDir != null, "importDir is null"); checkArgument(tableName.length() <= MAX_TABLE_NAME_LEN, "Table name is longer than " + MAX_TABLE_NAME_LEN + " characters"); try { importDir = checkPath(importDir, "Table", "").toString(); } catch (IOException e) { throw new AccumuloException(e); } try { FileSystem fs = new Path(importDir).getFileSystem(context.getHadoopConf()); Map<String,String> props = getExportedProps(fs, new Path(importDir, Constants.EXPORT_FILE)); for (Entry<String,String> entry : props.entrySet()) { if (Property.isClassProperty(entry.getKey()) && !entry.getValue().contains(Constants.CORE_PACKAGE_NAME)) { LoggerFactory.getLogger(this.getClass()).info( "Imported table sets '{}' to '{}'. Ensure this class is on Accumulo classpath.", sanitize(entry.getKey()), sanitize(entry.getValue())); } } } catch (IOException ioe) { LoggerFactory.getLogger(this.getClass()).warn( "Failed to check if imported table references external java classes : {}", ioe.getMessage()); } List<ByteBuffer> args = Arrays.asList(ByteBuffer.wrap(tableName.getBytes(UTF_8)), ByteBuffer.wrap(importDir.getBytes(UTF_8))); Map<String,String> opts = Collections.emptyMap(); try { doTableFateOperation(tableName, AccumuloException.class, FateOperation.TABLE_IMPORT, args, opts); } catch (TableNotFoundException e) { throw new AssertionError(e); } }
Source:
private void handleSentImage(Intent intent) { Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); if (imageUri != null) { displayFAB(false); displayChatBox(true); String loadingMsg = getResources().getString(R.string.uploading_message); sendingMessage(true, loadingMsg); String imageFilePath = FilePathHelper.getPath(this, imageUri); uploadFile(imageFilePath); } else { Toast.makeText(this, "Could not find the image", Toast.LENGTH_SHORT).show(); } }

Target:
private void handleSentImage(Intent intent) { mImageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); if (mImageUri != null) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_READ_CONTACTS); } else { startFileUpload(); } } else { Toast.makeText(this, R.string.cannot_find_image, Toast.LENGTH_SHORT).show(); } }
Source:
private void test(byte[] input) throws IOException { random.nextBytes(input); byte[][] split = fragmenter.split(input); for (byte[] bytes : split) { int length = bytes.length; assertTrue(length >= 0); assertTrue(length <= Fragment.MAX_LENGTH); } byte[] recombine = fragmenter.recombine(split, input.length); assertTrue("recombine(split(input)) = input", Arrays.equals(input, recombine)); }

Target:
private void test(byte[] input) throws IOException { random.nextBytes(input); byte[][] split = fragmenter.split(input); for (byte[] bytes : split) { int length = bytes.length; assertTrue(length > 0); assertTrue(length <= Fragment.MAX_LENGTH); } byte[] recombine = fragmenter.recombine(split, input.length); assertTrue("recombine(split(input)) = input", Arrays.equals(input, recombine)); }
Source:
protected void killProcess(String[] killCommand, List<ProcessInfo> process) throws ProcessHandlerException { try { for (ProcessInfo eachProcess : process) { log.info("Killing process : " + eachProcess); String[] cmd = new String[killCommand.length + 1]; cmd[cmd.length] = eachProcess.getProcessId(); Process output = Runtime.getRuntime().exec(cmd); int returnCode = output.waitFor(); if (returnCode != 0) { log.info("Printing possible errors " + convertStreamToString(output.getErrorStream())); } output.destroy(); } log.info("Successfully killed all stalled processes"); } catch (IOException | InterruptedException e) { throw new ProcessHandlerException(e); } }

Target:
protected void killProcess(String[] killCommand, List<ProcessInfo> process) throws ProcessHandlerException { try { for (ProcessInfo eachProcess : process) { log.info("Killing process : " + eachProcess); String[] cmd = Arrays.copyOf(killCommand, killCommand.length + 1); cmd[cmd.length] = eachProcess.getProcessId(); Process output = Runtime.getRuntime().exec(cmd); int returnCode = output.waitFor(); if (returnCode != 0) { log.info("Printing possible errors " + convertStreamToString(output.getErrorStream())); } output.destroy(); } log.info("Successfully killed all stalled processes"); } catch (IOException | InterruptedException e) { throw new ProcessHandlerException(e); } }
Source:
private static boolean isLegacyConnectorOptions( CatalogTable catalogTable, CatalogSchemaTable schemaTable) { if (catalogTable.getOptions().containsKey(ConnectorDescriptorValidator.CONNECTOR_TYPE)) { return true; } else { try { TableFactoryUtil.findAndCreateTableSource( schemaTable.getCatalog(), schemaTable.getTableIdentifier(), catalogTable, new Configuration()); return true; } catch (Throwable e) { return false; } } }

Target:
private static boolean isLegacyConnectorOptions( CatalogTable catalogTable, CatalogSchemaTable schemaTable) { DescriptorProperties properties = new DescriptorProperties(true); properties.putProperties(catalogTable.getOptions()); if (properties.containsKey(ConnectorDescriptorValidator.CONNECTOR_TYPE)) { return true; } else { try { TableFactoryUtil.findAndCreateTableSource( schemaTable.getCatalog(), schemaTable.getTableIdentifier(), catalogTable, new Configuration()); return true; } catch (Throwable e) { return false; } } }
Source:
public void update() { if (toolItem != null) { toolItem.setEnabled(canCreateNewForm() || canEditForm()); final PageFlow pageFlow = unwrap(selectionProvider.getSelection()); if (pageFlow != null) { if (pageFlow instanceof Pool) { toolItem.setToolTipText(NLS.bind(Messages.newFormTooltip, Messages.pool)); } else { toolItem.setToolTipText(NLS.bind(Messages.newFormTooltip, Messages.task)); } } } }

Target:
public void update() { if (toolItem != null) { toolItem.setEnabled(true); final PageFlow pageFlow = unwrap(selectionProvider.getSelection()); if (pageFlow != null) { if (pageFlow instanceof Pool) { toolItem.setToolTipText(NLS.bind(Messages.newFormTooltip, Messages.pool)); } else { toolItem.setToolTipText(NLS.bind(Messages.newFormTooltip, Messages.task)); } } } }
Source:
public void subscribeToConnection(ConnectionSubscriber subscriber) { BufferedReader receiver = null; try { receiver = new BufferedReader( new InputStreamReader(mSocket.getInputStream())); } catch (IOException e) { subscriber.updateOnConnectionProblem(e); return; } String pushMessage = null; do { try { pushMessage = receiver.readLine(); if(pushMessage != null) { Log.d("Y:" + this.getClass().getName(), "response : " + pushMessage); Response response = new Response(pushMessage); subscriber.updateOn(response); } } catch (IOException e) { subscriber.updateOnConnectionProblem(e); } catch (JSONException e) { subscriber.updateOnParsingProblem(e); } } while (pushMessage != null); try { this.close(); } catch (IOException e) { Log.d("Y:" + this.getClass().getName(),"Connection was already closed."); } finally { subscriber.updateOnConnectionProblem(new IOException("Server imput is shutdown")); } }

Target:
public void subscribeToConnection(ConnectionSubscriber subscriber) { BufferedReader receiver = null; try { receiver = new BufferedReader( new InputStreamReader(mSocket.getInputStream())); } catch (IOException e) { subscriber.updateOnConnectionProblem(e); return; } String pushMessage = null; do { try { pushMessage = receiver.readLine(); if(pushMessage != null) { Log.d("Y:" + this.getClass().getName(), "response : " + pushMessage); Response response = new Response(pushMessage); subscriber.updateOn(response); } } catch (IOException e) { subscriber.updateOnConnectionProblem(e); } catch (JSONException e) { subscriber.updateOnParsingProblem(e); } } while (pushMessage != null); try { this.close(); } catch (IOException e) { Log.d("Y:" + this.getClass().getName(),"Connection was already closed."); } finally { subscriber.updateOnConnectionProblem(new IOException("Server input is shutdown")); } }
Source:
public void setUp() throws Exception { super.setUp(); Transaction tx = openSession().beginTransaction(); A a = new A(); a.value = "1"; getSession().save( a ); tx.commit(); getSession().close(); this.fullTextSession = Search.getFullTextSession( openSession() ); }

Target:
public void setUp() throws Exception { super.setUp(); Transaction tx = openSession().beginTransaction(); getSession().save( new A() ); tx.commit(); getSession().close(); this.fullTextSession = Search.getFullTextSession( openSession() ); }
Source:
public void testVideoType() { DocumentType videoType = session.getDocumentType(VideoConstants.VIDEO_TYPE); assertNotNull("Does our type exist?", videoType); DocumentModel docModel = session.createDocumentModel("/", "doc", VideoConstants.VIDEO_TYPE); assertNotNull(docModel); assertNull(docModel.getPropertyValue("common:icon")); assertNull(docModel.getPropertyValue("dc:title")); assertNull(docModel.getPropertyValue("picture:credit")); assertNull(docModel.getPropertyValue("uid:uid")); assertNull(docModel.getPropertyValue(VideoConstants.DURATION_PROPERTY)); docModel.setPropertyValue("common:icon", "/icons/video.png"); docModel.setPropertyValue("dc:title", "testTitle"); docModel.setPropertyValue("picture:credit", "testUser"); docModel.setPropertyValue("uid:uid", "testUid"); DocumentModel docModelResult = session.createDocument(docModel); assertNotNull(docModelResult); assertEquals("/icons/video.png", docModelResult.getPropertyValue("common:icon")); assertEquals("testTitle", docModelResult.getPropertyValue("dc:title")); assertEquals("testUser", docModelResult.getPropertyValue("picture:credit")); assertEquals("testUid", docModelResult.getPropertyValue("uid:uid")); docModelResult = session.getDocument(docModelResult.getRef()); assertNull(docModelResult.getPropertyValue(VideoConstants.DURATION_PROPERTY)); assertEquals(Collections.emptyList(), docModel.getPropertyValue(VideoConstants.STORYBOARD_PROPERTY)); assertEquals(Collections.emptyList(), docModel.getPropertyValue(VideoConstants.TRANSCODED_VIDEOS_PROPERTY)); }

Target:
public void testVideoType() { DocumentType videoType = session.getDocumentType(VIDEO_TYPE); assertNotNull("Does our type exist?", videoType); DocumentModel docModel = session.createDocumentModel("/", "doc", VIDEO_TYPE); assertNotNull(docModel); assertNull(docModel.getPropertyValue("common:icon")); assertNull(docModel.getPropertyValue("dc:title")); assertNull(docModel.getPropertyValue("picture:credit")); assertNull(docModel.getPropertyValue("uid:uid")); assertNull(docModel.getPropertyValue(DURATION_PROPERTY)); docModel.setPropertyValue("common:icon", "/icons/video.png"); docModel.setPropertyValue("dc:title", "testTitle"); docModel.setPropertyValue("picture:credit", "testUser"); docModel.setPropertyValue("uid:uid", "testUid"); DocumentModel docModelResult = session.createDocument(docModel); assertNotNull(docModelResult); assertEquals("/icons/video.png", docModelResult.getPropertyValue("common:icon")); assertEquals("testTitle", docModelResult.getPropertyValue("dc:title")); assertEquals("testUser", docModelResult.getPropertyValue("picture:credit")); assertEquals("testUid", docModelResult.getPropertyValue("uid:uid")); docModelResult = session.getDocument(docModelResult.getRef()); assertNull(docModelResult.getPropertyValue(DURATION_PROPERTY)); assertEquals(Collections.emptyList(), docModel.getPropertyValue(STORYBOARD_PROPERTY)); assertEquals(Collections.emptyList(), docModel.getPropertyValue(TRANSCODED_VIDEOS_PROPERTY)); }
Source:
private void startNewDispatcherLeaderProcess(UUID leaderSessionID) { try { stopDispatcherLeaderProcess(); dispatcherLeaderProcess = createNewDispatcherLeaderProcess(leaderSessionID); final DispatcherLeaderProcess newDispatcherLeaderProcess = dispatcherLeaderProcess; FutureUtils.assertNoException( previousDispatcherLeaderProcessTerminationFuture.thenRun(newDispatcherLeaderProcess::start)); } catch (Throwable t) { terminationFuture.completeExceptionally(t); throw t; } }

Target:
private void startNewDispatcherLeaderProcess(UUID leaderSessionID) { stopDispatcherLeaderProcess(); dispatcherLeaderProcess = createNewDispatcherLeaderProcess(leaderSessionID); final DispatcherLeaderProcess newDispatcherLeaderProcess = dispatcherLeaderProcess; FutureUtils.assertNoException( previousDispatcherLeaderProcessTerminationFuture.thenRun(newDispatcherLeaderProcess::start)); }
Source:
protected void addVmStatic() { logImportEvents(); getVm().getStaticData().setId(getVmId()); getVm().getStaticData().setCreationDate(new Date()); getVm().getStaticData().setClusterId(getParameters().getClusterId()); getVm().getStaticData().setMinAllocatedMem(computeMinAllocatedMem()); getVm().getStaticData().setQuotaId(getParameters().getQuotaId()); if (!vmHandler.validateDedicatedVdsExistOnSameCluster(getVm().getStaticData()).isValid()) { getVm().setDedicatedVmForVdsList(Collections.emptyList()); } if (getVm().getOriginalTemplateGuid() != null && !VmTemplateHandler.BLANK_VM_TEMPLATE_ID.equals(getVm().getOriginalTemplateGuid())) { VmTemplate originalTemplate = vmTemplateDao.get(getVm().getOriginalTemplateGuid()); if (originalTemplate != null) { getVm().getStaticData().setOriginalTemplateName(originalTemplate.getName()); } } if (getParameters().getCopyCollapse()) { getVm().setVmtGuid(VmTemplateHandler.BLANK_VM_TEMPLATE_ID); } vmHandler.autoSelectResumeBehavior(getVm().getStaticData(), getCluster().getCompatibilityVersion()); vmStaticDao.save(getVm().getStaticData()); getCompensationContext().snapshotNewEntity(getVm().getStaticData()); }

Target:
protected void addVmStatic() { logImportEvents(); getVm().getStaticData().setId(getVmId()); getVm().getStaticData().setCreationDate(new Date()); getVm().getStaticData().setClusterId(getParameters().getClusterId()); getVm().getStaticData().setMinAllocatedMem(computeMinAllocatedMem()); getVm().getStaticData().setQuotaId(getParameters().getQuotaId()); if (!vmHandler.validateDedicatedVdsExistOnSameCluster(getVm().getStaticData()).isValid()) { getVm().setDedicatedVmForVdsList(Collections.emptyList()); } if (getVm().getOriginalTemplateGuid() != null && !VmTemplateHandler.BLANK_VM_TEMPLATE_ID.equals(getVm().getOriginalTemplateGuid())) { VmTemplate originalTemplate = vmTemplateDao.get(getVm().getOriginalTemplateGuid()); if (originalTemplate != null) { getVm().getStaticData().setOriginalTemplateName(originalTemplate.getName()); } } if (getParameters().getCopyCollapse()) { getVm().setVmtGuid(VmTemplateHandler.BLANK_VM_TEMPLATE_ID); } vmHandler.autoSelectResumeBehavior(getVm().getStaticData(), getCluster()); vmStaticDao.save(getVm().getStaticData()); getCompensationContext().snapshotNewEntity(getVm().getStaticData()); }
Source:
public static Integer getDp(Object obj) { if (obj instanceof Number) { return (Integer) obj; } else if (obj.getClass().equals(String.class)) { String str = (String) obj; if (str.substring(Math.max(str.length() - 2, 0)).equals("px")) { try { int px = Integer.parseInt(str.substring(0, str.length() - 2)); return (int) ( (int)px * 1f / (ScanditSDK.DISPLAY.densityDpi / 160f)); } catch (NumberFormatException e) { Log.e("ScanditSDK", "Can not recognize dp value of String " + str + " - returning 0"); return 0; } } else { try { return Integer.parseInt(str); } catch (NumberFormatException e) { Log.e("ScanditSDK", "Can not recognize dp value of String " + str + " - returning 0"); return 0; } } } else { Log.e("ScanditSDK", "Can not recognize dp value - returning 0"); return 0; } }

Target:
public static Integer getDp(Object obj) { if (obj instanceof Number) { return ((Number) obj).intValue(); } else if (obj.getClass().equals(String.class)) { String str = (String) obj; if (str.substring(Math.max(str.length() - 2, 0)).equals("px")) { try { int px = Integer.parseInt(str.substring(0, str.length() - 2)); return (int) ( (int)px * 1f / (ScanditSDK.DISPLAY.densityDpi / 160f)); } catch (NumberFormatException e) { Log.e("ScanditSDK", "Can not recognize dp value of String " + str + " - returning 0"); return 0; } } else { try { return Integer.parseInt(str); } catch (NumberFormatException e) { Log.e("ScanditSDK", "Can not recognize dp value of String " + str + " - returning 0"); return 0; } } } else { Log.e("ScanditSDK", "Can not recognize dp value - returning 0"); return 0; } }
Source:
public Set<String> undocumentedThrownExceptions() { Map<String, List<String>> thrownExceptionsMap = getJavadocExceptions(); List<String> exceptionNames = elementExceptionNames; if (exceptionNames.size() == 1 && GENERIC_EXCEPTIONS.contains(toSimpleName(exceptionNames.get(0))) && !thrownExceptionsMap.isEmpty()) { return thrownExceptionsMap.entrySet().stream() .filter(e -> isEmptyDescription(e.getValue())) .map(Map.Entry::getKey) .map(Javadoc::toSimpleName) .collect(Collectors.toSet()); } return exceptionNames.stream() .map(Javadoc::toSimpleName) .filter(simpleName -> noDescriptionForException(thrownExceptionsMap, simpleName)) .collect(Collectors.toSet()); }

Target:
public List<String> undocumentedThrownExceptions() { return undocumentedNamedTags.computeIfAbsent(BlockTag.EXCEPTIONS, key -> computeUndocumentedThrownExceptions()); }
Source:
public VmManagementParametersBase(VmStatic vmStatic) { super(vmStatic.getId()); _vmStatic = vmStatic; privateStorageDomainId = Guid.Empty; consoleEnabled = false; balloonEnabled = true; }

Target:
public VmManagementParametersBase(VmStatic vmStatic) { super(vmStatic.getId()); _vmStatic = vmStatic; privateStorageDomainId = Guid.Empty; consoleEnabled = Boolean.FALSE; balloonEnabled = true; }
Source:
public static ConversationKey fromJsonString(String json) { if(json.equals("Other")) { return forOther(); } final Object[] array = gson.fromJson(json, Object[].class); if (array.length != 5) { throw new IllegalArgumentException("Invalid conversation key string: " + json); } return new ConversationKey((String)array[0], ((Number)array[1]).intValue(), (String)array[2], (String)array[3], (String)array[4]); }

Target:
public static ConversationKey fromJsonString(String json) { final Object[] array = gson.fromJson(json, Object[].class); if (array.length != 5) { throw new IllegalArgumentException("Invalid conversation key string: " + json); } return new ConversationKey((String)array[0], ((Number)array[1]).intValue(), (String)array[2], (String)array[3], (String)array[4]); }
Source:
private Subfield.PathElement matchUnquotedSubscript() { int start = index; while (hasNextCharacter() && isUnquotedSubscriptCharacter(peekCharacter())) { nextCharacter(); } int end = index; String token = path.substring(start, end); if (token.isEmpty()) { throw invalidSubfieldPath(); } return new Subfield.LongSubscript(Long.valueOf(token)); }

Target:
private Subfield.PathElement matchUnquotedSubscript() { int start = index; while (hasNextCharacter() && isUnquotedSubscriptCharacter(peekCharacter())) { nextCharacter(); } int end = index; String token = path.substring(start, end); if (token.isEmpty()) { throw invalidSubfieldPath(); } long index; try { index = Long.valueOf(token); } catch (NumberFormatException e) { throw invalidSubfieldPath(); } return new Subfield.LongSubscript(index); }
Source:
public RecordReader<E, Void> asRecordReader() { Preconditions.checkArgument(incoming instanceof FSDataInputStream, "Cannot use in a record reader", incoming.getClass()); return new CSVRecordReader(); }

Target:
public RecordReader<E, Void> asRecordReader() { Preconditions.checkArgument(incoming instanceof FSDataInputStream, "Cannot use in a record reader", incoming.getClass()); return new JSONRecordReader(); }
Source:
public void handle(HttpExchange exchange) throws IOException { ClassLoader loader = StaticHandler.class.getClassLoader(); InputStream is = loader.getResourceAsStream(mResourceName); if (is == null) { exchange.getResponseHeaders().add("Content-Type", "text/html"); exchange.sendResponseHeaders(404, 0); PrintStream ps = new PrintStream(exchange.getResponseBody()); HtmlDoc doc = new HtmlDoc(ps, DocString.text("ahat"), DocString.uri("style.css")); doc.big(DocString.text("Resource not found.")); doc.close(); } else { exchange.getResponseHeaders().add("Content-Type", mContentType); exchange.sendResponseHeaders(200, 0); OutputStream os = exchange.getResponseBody(); int read; byte[] buf = new byte[4096]; while ((read = is.read(buf)) > 0) { os.write(buf, 0, read); } is.close(); os.close(); } }

Target:
public void handle(HttpExchange exchange) throws IOException { ClassLoader loader = StaticHandler.class.getClassLoader(); InputStream is = loader.getResourceAsStream(mResourceName); if (is == null) { exchange.getResponseHeaders().add("Content-Type", "text/html"); exchange.sendResponseHeaders(404, 0); PrintStream ps = new PrintStream(exchange.getResponseBody()); HtmlDoc doc = new HtmlDoc(ps, DocString.text("ahat"), DocString.uri("style.css")); doc.big(DocString.text("Resource not found.")); doc.close(); } else { exchange.getResponseHeaders().add("Content-Type", mContentType); exchange.sendResponseHeaders(200, 0); OutputStream os = exchange.getResponseBody(); int read; byte[] buf = new byte[4096]; while ((read = is.read(buf)) >= 0) { os.write(buf, 0, read); } is.close(); os.close(); } }
Source:
private static boolean checkArtifactUsingHttp(String url, String username, String password) { try { HttpURLConnection.setFollowRedirects(false); HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("HEAD"); if (!username.isEmpty() && !password.isEmpty()) { String usernameColonPassword = username + ":" + password; String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes()); con.addRequestProperty("Authorization", basicAuthPayload); } return (con.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { LOGGER.debug("Artifact doesn't exist" + e); return false; } }

Target:
private static boolean checkArtifactUsingHttp(String url, String username, String password) { try { HttpURLConnection.setFollowRedirects(false); HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("HEAD"); if (!username.isEmpty() && !password.isEmpty()) { String usernameColonPassword = username + ":" + password; String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes()); con.addRequestProperty("Authorization", basicAuthPayload); } return (con.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { LOGGER.debug("Artifact doesn't exist: " + url, e); return false; } }
Source:
public AzureProfile(AzureEnvironment environment, boolean loadEnvironmentVariables) { Objects.requireNonNull(environment); if (loadEnvironmentVariables) { Configuration configuration = Configuration.getGlobalConfiguration().clone(); this.tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); this.subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); } }

Target:
public AzureProfile(AzureEnvironment environment, boolean loadEnvironmentVariables) { Objects.requireNonNull(environment); this.environment = environment; if (loadEnvironmentVariables) { Configuration configuration = Configuration.getGlobalConfiguration(); this.tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); this.subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); } }
Source:
public void testTextBinding() { CredentialsPage mc = new CredentialsPage(jenkins, ManagedCredentials.DEFAULT_DOMAIN); mc.open(); StringCredentials cred = mc.add(StringCredentials.class); cred.scope.select("GLOBAL"); cred.secret.set(SECRET_TEXT); mc.create(); FreeStyleJob job = jenkins.jobs.create(); job.configure(); job.check("Use secret text(s) or file(s)"); ManagedCredentialsBinding mcb = new ManagedCredentialsBinding(job); SecretStringCredentialsBinding cb = mcb.addCredentialBinding(SecretStringCredentialsBinding.class); cb.variable.set("BINDED_SECRET"); ShellBuildStep shell = job.addBuildStep(ShellBuildStep.class); shell.command("if [ \"$BINDED_SECRET\" = \"" + SECRET_TEXT + "\" ] \n then \n echo \"true\" \n fi"); job.save(); Build b = job.scheduleBuild(); b.shouldSucceed(); assertThat(b.getConsole(), containsString("true")); }

Target:
public void testTextBinding() { CredentialsPage mc = new CredentialsPage(jenkins, ManagedCredentials.DEFAULT_DOMAIN); mc.open(); StringCredentials cred = mc.add(StringCredentials.class); cred.scope.select("GLOBAL"); cred.secret.set(SECRET_TEXT); mc.create(); FreeStyleJob job = jenkins.jobs.create(); job.configure(); job.check("Use secret text(s) or file(s)"); ManagedCredentialsBinding mcb = new ManagedCredentialsBinding(job); SecretStringCredentialsBinding cb = mcb.addCredentialBinding(SecretStringCredentialsBinding.class); cb.variable.set("BINDED_SECRET"); ShellBuildStep shell = job.addBuildStep(ShellBuildStep.class); shell.command("if [ \"$BINDED_SECRET\" = \"" + SECRET_TEXT + "\" ] \n then \n echo \"" + SECRET_OUTPUT + "\" \n fi"); job.save(); Build b = job.scheduleBuild(); b.shouldSucceed(); assertThat(b.getConsole(), containsString(SECRET_OUTPUT)); }
Source:
public Optional<UUID> getId() { if (id == null) { return Optional.empty(); } return Optional.of(id); }

Target:
public Optional<UUID> getId() { return Optional.ofNullable(id); }
Source:
public static HistoryFileType getHistoryFileType(QualifiedJobId qualifiedJobId, byte[] historyFileContents) { if (historyFileContents == null) throw new IllegalArgumentException("Null job history file"); if ((qualifiedJobId != null) && Constants.FRAMEWORK_CONF_SPARK_VALUE .equalsIgnoreCase(qualifiedJobId.getJobPrefix())) { return HistoryFileType.SPARK; } if(historyFileContents.length > HADOOP2_VERSION_LENGTH) { String version2Part = new String(historyFileContents, 0, HADOOP2_VERSION_LENGTH); if (StringUtils.equalsIgnoreCase(version2Part, HADOOP2_VERSION_STRING)) { return HistoryFileType.TWO; } else { if(historyFileContents.length > HADOOP1_VERSION_LENGTH) { String version1Part = new String(historyFileContents, 0,HADOOP1_VERSION_LENGTH); if (StringUtils.equalsIgnoreCase(version1Part, HADOOP1_VERSION_STRING)) { return HistoryFileType.ONE; } } } } throw new IllegalArgumentException(" Unknown format of job history file: " + historyFileContents); }

Target:
public static HistoryFileType getHistoryFileType(QualifiedJobId qualifiedJobId, byte[] historyFileContents) { if (historyFileContents == null) { throw new IllegalArgumentException("Null job history file"); } if ((qualifiedJobId != null) && Constants.FRAMEWORK_CONF_SPARK_VALUE .equalsIgnoreCase(qualifiedJobId.getJobPrefix())) { return HistoryFileType.SPARK; } if(historyFileContents.length > HADOOP2_VERSION_LENGTH) { String version2Part = new String(historyFileContents, 0, HADOOP2_VERSION_LENGTH); if (StringUtils.equalsIgnoreCase(version2Part, HADOOP2_VERSION_STRING)) { return HistoryFileType.TWO; } else { if(historyFileContents.length > HADOOP1_VERSION_LENGTH) { String version1Part = new String(historyFileContents, 0,HADOOP1_VERSION_LENGTH); if (StringUtils.equalsIgnoreCase(version1Part, HADOOP1_VERSION_STRING)) { return HistoryFileType.ONE; } } } } throw new IllegalArgumentException(" Unknown format of job history file: " + historyFileContents); }
Source:
public void deserialize(ConsumerRecord<byte[], byte[]> record, Collector<T> collector) throws IOException { if (deserializer == null) { try (TemporaryClassLoaderContext ignored = TemporaryClassLoaderContext.of(userCodeClassLoader)) { deserializer = (Deserializer<T>) InstantiationUtil.instantiate( deserializerClass, Deserializer.class, getClass().getClassLoader()); if (deserializer instanceof Configurable) { ((Configurable) deserializer).configure(config); } } catch (Exception e) { throw new IOException( "Failed to instantiate the deserializer of class " + deserializerClass, e); } } T value = deserializer.deserialize(record.topic(), record.value()); LOG.trace("Deserialized [partition: {}-{}, offset: {}, timestamp: {}, value: {}]", record.topic(), record.partition(), record.offset(), record.timestamp(), value); collector.collect(value); }

Target:
public void deserialize(ConsumerRecord<byte[], byte[]> record, Collector<T> collector) throws IOException { if (deserializer == null) { throw new IllegalStateException( "The deserializer has not been created. Make sure the open() method has been " + "invoked."); } T value = deserializer.deserialize(record.topic(), record.value()); LOG.trace("Deserialized [partition: {}-{}, offset: {}, timestamp: {}, value: {}]", record.topic(), record.partition(), record.offset(), record.timestamp(), value); collector.collect(value); }
Source:
protected void internalExecute(ScenarioSimulationContext context) { final ScenarioSimulationContext.Status status = context.getStatus(); SimulationDescriptor simulationDescriptor = status.getSimulation().getSimulationDescriptor(); int columnIndex = status.getColumnIndex(); FactMapping factMapping = simulationDescriptor.getFactMappingByIndex(columnIndex); String placeholder = ScenarioSimulationUtils.isExpressionType(factMapping) ? ScenarioSimulationEditorConstants.INSTANCE.insertExpression() : ScenarioSimulationUtils.getPlaceholder(factMapping.getClassName()); context.getModel().setCellValue(status.getRowIndex(), columnIndex, new ScenarioGridCellValue(status.getGridCellValue(), placeholder)); context.getModel().resetError(status.getRowIndex(), columnIndex); }

Target:
protected void internalExecute(ScenarioSimulationContext context) { final ScenarioSimulationContext.Status status = context.getStatus(); ScesimModelDescriptor simulationDescriptor = status.getSimulation().getScesimModelDescriptor(); int columnIndex = status.getColumnIndex(); FactMapping factMapping = simulationDescriptor.getFactMappingByIndex(columnIndex); ScenarioGridColumn selectedColumn = (ScenarioGridColumn) context.getSelectedScenarioGridModel().getColumns().get(columnIndex); String placeholder = ScenarioSimulationUtils.getPlaceHolder(selectedColumn.isInstanceAssigned(), selectedColumn.isPropertyAssigned(), factMapping.getFactMappingValueType(), factMapping.getClassName()); context.getSelectedScenarioGridModel().setCellValue(status.getRowIndex(), columnIndex, new ScenarioGridCellValue(status.getGridCellValue(), placeholder)); context.getSelectedScenarioGridModel().resetError(status.getRowIndex(), columnIndex); }
Source:
public BlockFamilyDefinitionFormat(AssetManager assetManager, BlockFamilyRegistry blockFamilyRegistry) { super("block"); this.assetManager = assetManager; this.blockFamilyRegistry = blockFamilyRegistry; gson = new GsonBuilder() .registerTypeAdapterFactory(new CaseInsensitiveEnumTypeAdapterFactory()) .registerTypeAdapterFactory(new AssetTypeAdapterFactory(assetManager)) .registerTypeAdapter(BlockFamilyDefinitionData.class, new BlockFamilyDefinitionDataHandler()) .registerTypeAdapter(Vector3f.class, new Vector3fTypeAdapter()) .registerTypeAdapter(Vector4f.class, new Vector4fTypeAdapter()) .registerTypeAdapter(Class.class, new BlockFamilyHandler(blockFamilyRegistry)) .create(); }

Target:
public BlockFamilyDefinitionFormat(AssetManager assetManager, BlockFamilyRegistry blockFamilyRegistry) { super("block"); this.assetManager = assetManager; gson = new GsonBuilder() .registerTypeAdapterFactory(new CaseInsensitiveEnumTypeAdapterFactory()) .registerTypeAdapterFactory(new AssetTypeAdapterFactory(assetManager)) .registerTypeAdapter(BlockFamilyDefinitionData.class, new BlockFamilyDefinitionDataHandler()) .registerTypeAdapter(Vector3f.class, new Vector3fTypeAdapter()) .registerTypeAdapter(Vector4f.class, new Vector4fTypeAdapter()) .registerTypeAdapter(Class.class, new BlockFamilyHandler(blockFamilyRegistry)) .create(); }
Source:
private CacheBuilder<CacheKey, TypeCodec<?>> defaultCacheBuilder() { CacheBuilder<CacheKey, TypeCodec<?>> builder = CacheBuilder.newBuilder() .initialCapacity(100) .weigher(new TypeCodecWeigher()) .maximumWeight(1000); if (logger.isTraceEnabled()) builder = builder.removalListener(new TypeCodecRemovalListener()); return builder; }

Target:
private CacheBuilder<CacheKey, TypeCodec<?>> defaultCacheBuilder() { CacheBuilder<CacheKey, TypeCodec<?>> builder = CacheBuilder.newBuilder() .initialCapacity(100) .maximumWeight(1000) .weigher(new TypeCodecWeigher()); if (logger.isTraceEnabled()) builder = builder.removalListener(new TypeCodecRemovalListener()); return builder; }
Source:
public Object read(Object request, Map kvp, Map rawKvp) throws Exception { GetFeatureType gf = (GetFeatureType) super.read(request, kvp, rawKvp); Filter filter = getFullFilter(kvp); querySet(gf, "filter", Collections.singletonList(filter)); if (!kvp.containsKey("outputFormat")) { gf.setOutputFormat(null); } if (kvp.containsKey("resolution")) { gf.setResolution((String) kvp.get("resolution")); } return gf; }

Target:
public Object read(Object request, Map kvp, Map rawKvp) throws Exception { GetFeatureType gf = (GetFeatureType) super.read(request, kvp, rawKvp); Filter filter = getFullFilter(kvp); querySet(gf, "filter", Collections.singletonList(filter)); if (!kvp.containsKey("outputFormat")) { gf.setOutputFormat(null); } if (kvp.containsKey("resolution")) { gf.setResolution((Integer) kvp.get("resolution")); } return gf; }
Source:
public void echoTest() throws ExecutionException, InterruptedException, JSONException { String inputText = "loremIpsum"; String uri = AdminBlobStorageService.ECHO + "?" + EchoHandler.TEXT_KEY + "=" + inputText; FullHttpRequest request = buildRequest(HttpMethod.GET, uri, null, null); Queue<HttpObject> responseParts = nettyClient.sendRequest(request, null, null).get(); HttpResponse response = (HttpResponse) responseParts.poll(); assertEquals("Unexpected status", HttpResponseStatus.OK, response.getStatus()); assertEquals("Unexpected Content-Type", "application/json", HttpHeaders.getHeader(response, HttpHeaders.Names.CONTENT_TYPE)); ByteBuffer buffer = getContent(response, responseParts); String echoedText = new JSONObject(new String(buffer.array())).getString(EchoHandler.TEXT_KEY); assertEquals("Did not get expected response", inputText, echoedText); }

Target:
public void echoTest() throws ExecutionException, InterruptedException, JSONException { String inputText = "loremIpsum"; String uri = AdminBlobStorageService.ECHO + "?" + EchoHandler.TEXT_KEY + "=" + inputText; FullHttpRequest httpRequest = buildRequest(HttpMethod.GET, uri, null, null); Queue<HttpObject> responseParts = nettyClient.sendRequest(httpRequest, null, null).get(); HttpResponse response = (HttpResponse) responseParts.poll(); assertEquals("Unexpected status", HttpResponseStatus.OK, response.getStatus()); assertEquals("Unexpected Content-Type", "application/json", HttpHeaders.getHeader(response, HttpHeaders.Names.CONTENT_TYPE)); ByteBuffer buffer = getContent(response, responseParts); String echoedText = new JSONObject(new String(buffer.array())).getString(EchoHandler.TEXT_KEY); assertEquals("Did not get expected response", inputText, echoedText); }
Source:
public HelixParticipantTest() throws Exception { List<com.github.ambry.utils.TestUtils.ZkInfo> zkInfoList = new ArrayList<>(); zkInfoList.add(new com.github.ambry.utils.TestUtils.ZkInfo(null, "DC0", (byte) 0, 2199, false)); JSONObject zkJson = constructZkLayoutJSON(zkInfoList); props = new Properties(); props.setProperty("clustermap.host.name", "localhost"); props.setProperty("clustermap.port", "2200"); props.setProperty("clustermap.cluster.name", clusterName); props.setProperty("clustermap.datacenter.name", "DC0"); props.setProperty("clustermap.dcs.zk.connect.strings", zkJson.toString(2)); propsDummy = new Properties(props); propsDummy.setProperty("clustermap.host.name", "dummyHost"); propsDummy.setProperty("clustermap.port", "2200"); propsDummy.setProperty("clustermap.cluster.name", clusterName); propsDummy.setProperty("clustermap.datacenter.name", "DC0"); propsDummy.setProperty("clustermap.dcs.zk.connect.strings", zkJson.toString(2)); helixManagerFactory = new MockHelixManagerFactory(); }

Target:
public HelixParticipantTest() throws Exception { List<com.github.ambry.utils.TestUtils.ZkInfo> zkInfoList = new ArrayList<>(); zkInfoList.add(new com.github.ambry.utils.TestUtils.ZkInfo(null, "DC0", (byte) 0, 2199, false)); zkJson = constructZkLayoutJSON(zkInfoList); props = new Properties(); props.setProperty("clustermap.host.name", "localhost"); props.setProperty("clustermap.port", "2200"); props.setProperty("clustermap.cluster.name", clusterName); props.setProperty("clustermap.datacenter.name", "DC0"); props.setProperty("clustermap.dcs.zk.connect.strings", zkJson.toString(2)); helixManagerFactory = new MockHelixManagerFactory(); }
Source:
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { return wrapped.createSocket(s, host, port, autoClose); }

Target:
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { Socket socket = wrapped.createSocket(s, host, port, autoClose); setSslParams(socket); return socket; }
Source:
public PID fetchContainer(PID child, Resource membershipRelation) { Resource relationship = (membershipRelation != null) ? membershipRelation : PcdmModels.hasMember; String queryString = String.format( "select ?pid where { ?pid <%1$s> <%2$s> }", relationship, child.getURI()); Query query = QueryFactory.create(queryString); try (QueryExecution qexec = QueryExecutionFactory.sparqlService("http://localhost:8080/fuseki/test/query", query)) { ResultSet results = qexec.execSelect(); for (; results.hasNext();) { QuerySolution soln = results.nextSolution(); Resource res = soln.getResource("pid"); if (res != null) { return PIDs.get(res.getURI()); } } } return null; }

Target:
public PID fetchContainer(PID child, Resource membershipRelation) { Resource relationship = (membershipRelation != null) ? membershipRelation : PcdmModels.hasMember; String queryString = String.format( "select ?pid where { ?pid <%1$s> <%2$s> }", relationship, child.getURI()); Query query = QueryFactory.create(queryString); try (QueryExecution qexec = QueryExecutionFactory.sparqlService(fusekiQueryURL, query)) { ResultSet results = qexec.execSelect(); for (; results.hasNext();) { QuerySolution soln = results.nextSolution(); Resource res = soln.getResource("pid"); if (res != null) { return PIDs.get(res.getURI()); } } } return null; }
Source:
private void checkObjectCollision(PackedObjectInfo obj) throws IOException { ObjectTypeAndSize info = openDatabase(obj, new ObjectTypeAndSize()); final byte[] readBuffer = buffer(); final byte[] curBuffer = new byte[readBuffer.length]; long sz = info.size; long szForRecord = sz; try (ObjectStream cur = readCurs.open(obj, info.type).openStream()) { if (cur.getSize() != sz) { throw new IOException(MessageFormat.format( JGitText.get().collisionOn, obj.name())); } try (InputStream pck = inflate(Source.DATABASE, sz)) { while (0 < sz) { int n = (int) Math.min(readBuffer.length, sz); IO.readFully(cur, curBuffer, 0, n); IO.readFully(pck, readBuffer, 0, n); for (int i = 0; i < n; i++) { if (curBuffer[i] != readBuffer[i]) { throw new IOException(MessageFormat.format( JGitText.get().collisionOn, obj.name())); } } sz -= n; } } stats.increaseNumBytesDuplicated(szForRecord); stats.incrementObjectsDuplicated(); } catch (MissingObjectException notLocal) { } }

Target:
private void checkObjectCollision(PackedObjectInfo obj) throws IOException { ObjectTypeAndSize info = openDatabase(obj, new ObjectTypeAndSize()); final byte[] readBuffer = buffer(); final byte[] curBuffer = new byte[readBuffer.length]; long sz = info.size; try (ObjectStream cur = readCurs.open(obj, info.type).openStream()) { if (cur.getSize() != sz) { throw new IOException(MessageFormat.format( JGitText.get().collisionOn, obj.name())); } try (InputStream pck = inflate(Source.DATABASE, sz)) { while (0 < sz) { int n = (int) Math.min(readBuffer.length, sz); IO.readFully(cur, curBuffer, 0, n); IO.readFully(pck, readBuffer, 0, n); for (int i = 0; i < n; i++) { if (curBuffer[i] != readBuffer[i]) { throw new IOException(MessageFormat.format( JGitText.get().collisionOn, obj.name())); } } sz -= n; } } stats.incrementObjectsDuplicated(); stats.increaseNumBytesDuplicated(obj.getSize()); } catch (MissingObjectException notLocal) { } }
Source:
public void testGettingOfSpecialFields() throws Exception { RulesetManagementInterface underTest = new RulesetManagement(); underTest.load(new File("src/test/resources/testAnExtensiveRulesetCanBeLoaded.xml")); assertThat(underTest.getIdsOfKeysForSpecialField(SpecialField.TITLE), contains("TitleDocMain")); assertThat(underTest.getIdsOfKeysForSpecialField(SpecialField.AUTHOR_LAST_NAME), contains("Person/LastName")); }

Target:
public void testGettingOfSpecialFields() throws Exception { RulesetManagement rulesetManagement= new RulesetManagement(); rulesetManagement.load(new File("src/test/resources/testAnExtensiveRulesetCanBeLoaded.xml")); assertThat("TitleDocMain was not found!", rulesetManagement.getFunctionalKeys(FunctionalMetadata.TITLE), contains("TitleDocMain")); assertThat("Person@LastName was not found!", rulesetManagement.getFunctionalKeys(FunctionalMetadata.AUTHOR_LAST_NAME), contains("Person@LastName")); assertThat("Something was found!", rulesetManagement.getFunctionalKeys(FunctionalMetadata.DATA_SOURCE), is(empty())); assertThat("shelfmarksource was not found!", rulesetManagement.getFunctionalKeys(FunctionalMetadata.RECORD_IDENTIFIER), contains("shelfmarksource")); assertThat("shelfmarksource was not found!", rulesetManagement.getFunctionalKeys(FunctionalMetadata.HIGHERLEVEL_IDENTIFIER), contains("shelfmarksource")); }
Source:
protected int doWork() { try { final ReferenceSequenceFile refSeq = ReferenceSequenceFileFactory.getReferenceSequenceFile(REFERENCE_SEQUENCE); final ExtendedIlluminaManifest manifest = new ExtendedIlluminaManifest(EXTENDED_ILLUMINA_MANIFEST); final VCFHeader vcfHeader = createVCFHeader(manifest, infiniumGTCFile, gtcGender, CLUSTER_FILE, REFERENCE_SEQUENCE, refSeq.getSequenceDictionary()); final SortingCollection<VariantContext> contexts = SortingCollection.newInstance( VariantContext.class, new VCFRecordCodec(vcfHeader), new VariantContextComparator(refSeq.getSequenceDictionary()), MAX_RECORDS_IN_RAM, TMP_DIR); fillContexts(contexts, infiniumGTCFile, manifest, infiniumEGTFile); writeVcf(contexts, OUTPUT, refSeq.getSequenceDictionary(), vcfHeader); } catch (final IOException ioe) { throw new RuntimeIOException(ioe); } return 0; }

Target:
protected int doWork() { final Build37ExtendedIlluminaManifest manifest = setupAndGetManifest(); final VCFHeader vcfHeader = createVCFHeader(manifest, infiniumGTCFile, gtcGender, CLUSTER_FILE, REFERENCE_SEQUENCE, refSeq.getSequenceDictionary()); final SortingCollection<VariantContext> contexts = SortingCollection.newInstance( VariantContext.class, new VCFRecordCodec(vcfHeader), new VariantContextComparator(refSeq.getSequenceDictionary()), MAX_RECORDS_IN_RAM, TMP_DIR.stream().map(File::toPath).toArray(Path[]::new)); fillContexts(contexts, infiniumGTCFile, manifest, infiniumEGTFile); writeVcf(contexts, OUTPUT, refSeq.getSequenceDictionary(), vcfHeader); return 0; }