auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Event findFirstCapturedEventOrElseThrow(String event) { return findFirstCapturedEvent(event).orElseThrow(() -> new AssertionError("Unable to find first Event")); }

Target:
public Event findFirstCapturedEventOrElseThrow(String event) { return findFirstCapturedEvent(event).orElseThrow( () -> new AssertionError("Unable to find first Event for event: " + event)); }
Source:
public void testRefAltAssignmentInConstructor() { Variant variant = new Variant("1", 1, 1, "C", "T"); assertEquals("C", variant.getReference()); assertEquals("T", variant.getAlternate()); variant = new Variant("1", 1, 1, "", "T"); assertEquals("", variant.getReference()); assertEquals("T", variant.getAlternate()); variant = new Variant("1", 1, 1, "T", ""); assertEquals("T", variant.getReference()); assertEquals("", variant.getAlternate()); }

Target:
public void testRefAltAssignmentInConstructor() { Variant variant = new Variant("1", 1, 1, "C", "T"); assertEquals("C", variant.getReference()); assertEquals("T", variant.getAlternate()); }
Source:
public void testTooManyFiles() { when(diffs.size()).thenReturn(1); when(configurable.getIntegerProperty(anyString(), anyString())).thenReturn(0); Set<LargeCommitWarning> warnings = generator.generateWarnings(commit, gitPush); verify(diffs).size(); assertFalse(warnings.isEmpty()); assertEquals(1, warnings.size()); assertEquals(testEquals, warnings); }

Target:
public void testTooManyFiles() throws IOException { List<AbstractDiffModel.DiffFile<AbstractDiffModel.DiffContext<AbstractDiffModel.DiffLine>>> diffs = Lists.newArrayList(); for (int i = 0; i < MAX_AMOUNT_OF_FILES + 2; i++) { diffs.add(diffFile); } diffModel.setDiffs(diffs); Set<LargeCommitWarning> warnings = generator.generateWarnings(commit, gitPush); assertEquals(1, warnings.size()); assertEquals(testEquals, warnings); }
Source:
public Response<ResponseBody> simpleGet(String uri, Map<String, String> httpParams, Map<String, String> httpHeaders) throws IOException { HashMap<String, String> headers = getHeaders(""); headers.putAll(httpHeaders); ModernHttpRequester requester = CommCareApplication.instance().createGetRequester( CommCareApplication.instance(), uri, httpParams, headers, new AuthInfo.ProvidedAuth(username, password), null); Response<ResponseBody> response = requester.makeRequest(); if (response.code() == 404) { throw new FileNotFoundException("No Data available at URL " + uri); } return response; }

Target:
public Response<ResponseBody> simpleGet(String uri, Map<String, String> httpParams, Map<String, String> httpHeaders) throws IOException { HashMap<String, String> headers = new HashMap<>(getHeaders(null)); headers.putAll(httpHeaders); ModernHttpRequester requester = CommCareApplication.instance().createGetRequester( CommCareApplication.instance(), uri, httpParams, headers, new AuthInfo.ProvidedAuth(username, password), null); Response<ResponseBody> response = requester.makeRequest(); if (response.code() == 404) { throw new FileNotFoundException("No Data available at URL " + uri); } return response; }
Source:
private void validateSourceWithKio(final CloudTrailEvent event, final String applicationId, final String applicationVersion, final String team, final String source, final String artifact) { if (!source.equals(artifact)) { violationSink.put( new ViolationBuilder( format("Application: %s has not a valid artifact for version: %s.", applicationId, applicationVersion)).withEventId(getCloudTrailEventId(event)).withRegion( getCloudTrailEventRegion(event)).withAccoundId(getCloudTrailEventAccountId(event)).build()); } Map<String, String> tags = Maps.newHashMap(); try { tags = this.pieroneOperations.listTags(team, applicationId); } catch (HttpClientErrorException e) { LOG.error("Could not get the tags for team and applicationId {}", team, applicationId, e); } if (tags.isEmpty()) { violationSink.put(new ViolationBuilder(format("Source: %s is not present in pierone.", source)).withEventId( getCloudTrailEventId(event)).withRegion(getCloudTrailEventRegion(event)).withAccoundId( getCloudTrailEventAccountId(event)).build()); } else { String value = tags.get(applicationVersion); if (value == null) { violationSink.put(new ViolationBuilder(format("Source: %s is not present in pierone.", source)) .withEventId(getCloudTrailEventId(event)).withRegion(getCloudTrailEventRegion(event)) .withAccoundId(getCloudTrailEventAccountId(event)).build()); } } }

Target:
private void validateSourceWithKio(final CloudTrailEvent event, final String applicationId, final String applicationVersion, final String team, final String source, final String artifact) { if (!source.equals(artifact)) { violationSink.put( new ViolationBuilder( format("Application: %s has not a valid artifact for version: %s.", applicationId, applicationVersion)).withEventId(getCloudTrailEventId(event)).withRegion( getCloudTrailEventRegion(event)).withAccoundId(getCloudTrailEventAccountId(event)).build()); } Map<String, String> tags = Maps.newHashMap(); try { tags = this.pieroneOperations.listTags(team, applicationId); } catch (HttpClientErrorException e) { LOG.warn("Could not get the tags for team and applicationId {}", team, applicationId, e); } if (tags.isEmpty()) { violationSink.put(new ViolationBuilder(format("Source: %s is not present in pierone.", source)).withEventId( getCloudTrailEventId(event)).withRegion(getCloudTrailEventRegion(event)).withAccoundId( getCloudTrailEventAccountId(event)).build()); } else { String value = tags.get(applicationVersion); if (value == null) { violationSink.put(new ViolationBuilder(format("Source: %s is not present in pierone.", source)) .withEventId(getCloudTrailEventId(event)).withRegion(getCloudTrailEventRegion(event)) .withAccoundId(getCloudTrailEventAccountId(event)).build()); } } }
Source:
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR)); final ModelNode bufferSizeModel = BUFFER_SIZE.resolveModelAttribute(context, model); final ModelNode maxPoolSizeModel = MAX_POOL_SIZE.resolveModelAttribute(context, model); final ModelNode directModel = DIRECT.resolveModelAttribute(context, model); final int threadLocalCacheSize = THREAD_LOCAL_CACHE_SIZE.resolveModelAttribute(context, model).asInt(); final int leakDetectionPercent = LEAK_DETECTION_PERCENT.resolveModelAttribute(context, model).asInt(); final int bufferSize = bufferSizeModel.isDefined() ? bufferSizeModel.asInt() : defaultBufferSize; final int maxPoolSize = maxPoolSizeModel.isDefined() ? maxPoolSizeModel.asInt() : -1; final boolean direct = directModel.isDefined() ? directModel.asBoolean() : defaultDirectBuffers; final ByteBufferPoolService service = new ByteBufferPoolService(direct, bufferSize, maxPoolSize, threadLocalCacheSize, leakDetectionPercent); context.getCapabilityServiceTarget().addCapability(UNDERTOW_BUFFER_POOL_RUNTIME_CAPABILITY, service) .setInitialMode(ServiceController.Mode.ACTIVE) .install(); }

Target:
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { final ModelNode bufferSizeModel = BUFFER_SIZE.resolveModelAttribute(context, model); final ModelNode maxPoolSizeModel = MAX_POOL_SIZE.resolveModelAttribute(context, model); final ModelNode directModel = DIRECT.resolveModelAttribute(context, model); final int threadLocalCacheSize = THREAD_LOCAL_CACHE_SIZE.resolveModelAttribute(context, model).asInt(); final int leakDetectionPercent = LEAK_DETECTION_PERCENT.resolveModelAttribute(context, model).asInt(); final int bufferSize = bufferSizeModel.asInt(defaultBufferSize); final int maxPoolSize = maxPoolSizeModel.asInt(-1); final boolean direct = directModel.asBoolean(defaultDirectBuffers); final ByteBufferPoolService service = new ByteBufferPoolService(direct, bufferSize, maxPoolSize, threadLocalCacheSize, leakDetectionPercent); context.getCapabilityServiceTarget().addCapability(UNDERTOW_BUFFER_POOL_RUNTIME_CAPABILITY, service) .setInitialMode(ServiceController.Mode.ACTIVE) .install(); }
Source:
private void scanInstalledLibraries(UserLibraryFolder folderDesc) { File list[] = folderDesc.folder.listFiles(OnlyDirs.ONLY_DIRS); if (list == null) return; for (File subfolder : list) { String subfolderName = subfolder.getName(); if (!BaseNoGui.isSanitaryName(subfolderName)) { if (!badLibNotified.contains(subfolderName)) { badLibNotified.add(subfolderName); String mess = I18n.format(tr("The library \"{0}\" cannot be used.\n" + "Library folder names must contain only basic letters and numbers\n" + "(ASCII only and no spaces), and be less than 64 characters long."), subfolderName); BaseNoGui.showMessage(tr("Ignoring bad library name"), mess); } continue; } try { scanLibrary(new UserLibraryFolder(subfolder, folderDesc.location)); } catch (IOException e) { System.out.println(I18n.format(tr("Invalid library found in {0}: {1}"), subfolder, e.getMessage())); } } }

Target:
private void scanInstalledLibraries(UserLibraryFolder folderDesc) { File list[] = folderDesc.folder.listFiles(OnlyDirs.ONLY_DIRS); if (list == null) return; for (File subfolder : list) { String subfolderName = subfolder.getName(); if (!BaseNoGui.isSanitaryName(subfolderName)) { if (!badLibNotified.contains(subfolderName)) { badLibNotified.add(subfolderName); String mess = I18n.format(tr("The library \"{0}\" cannot be used.\n" + "Library folder names must start with a letter or number, followed by letters,\n" + "numbers, dashes, dots and underscores. Maximum length is 63 characters."), subfolderName); BaseNoGui.showMessage(tr("Ignoring bad library name"), mess); } continue; } try { scanLibrary(new UserLibraryFolder(subfolder, folderDesc.location)); } catch (IOException e) { System.out.println(I18n.format(tr("Invalid library found in {0}: {1}"), subfolder, e.getMessage())); } } }
Source:
public <K, V> ConcurrentMap<K, V> createConcurrentMap() { return new ConcurrentParallelHashMapV8<K, V>( AnyEquivalence.<K>getInstance(), AnyEquivalence.<V>getInstance()); }

Target:
public <K, V> ConcurrentMap<K, V> createConcurrentMap() { return new EquivalentConcurrentHashMapV8<K, V>( AnyEquivalence.<K>getInstance(), AnyEquivalence.<V>getInstance()); }
Source:
private void updateOptions() { getCompulsoryActions().clear(); getOptionalActions().clear(); if (getEntity() == null) { return; } startProgress(null); if (getEntity().getStoragePoolId() != null) { AsyncDataProvider.getInstance().getDataCenterById(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { ClusterGuideModel model = (ClusterGuideModel) target; model.dataCenter = (StoragePool) returnValue; if (model.dataCenter == null || !model.dataCenter.isLocal()) { model.updateOptionsNonLocalFSData(); } else { model.updateOptionsLocalFSData(); } } }), getEntity().getStoragePoolId()); } else if (getEntity().getStoragePoolId() == null) { AsyncDataProvider.getInstance().getDataCenterList(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { ClusterGuideModel model = (ClusterGuideModel) target; @SuppressWarnings("unchecked") List<StoragePool> dataCenters = (ArrayList<StoragePool>) returnValue; final List<StoragePool> localDataCenters = new ArrayList<StoragePool>(); boolean enableButton = false; for (StoragePool dataCenter: dataCenters) { if (model.getEntity().getCompatibilityVersion().compareTo( dataCenter.getCompatibilityVersion()) >= 0 ) { if (dataCenter.isLocal()) { localDataCenters.add(dataCenter); } else { enableButton = true; break; } } } if (enableButton || localDataCenters.isEmpty()) { model.updateOptionsRequiredAddDataCenter(enableButton); } else { model.updateOptionsRequiredAddDataCenter(localDataCenters); } } } )); } }

Target:
private void updateOptions() { getCompulsoryActions().clear(); getOptionalActions().clear(); if (getEntity() == null) { return; } startProgress(null); if (getEntity().getStoragePoolId() != null) { AsyncDataProvider.getInstance().getDataCenterById(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { ClusterGuideModel model = (ClusterGuideModel) target; model.dataCenter = (StoragePool) returnValue; if (model.dataCenter == null || !model.dataCenter.isLocal()) { model.updateOptionsNonLocalFSData(); } else { model.updateOptionsLocalFSData(); } } }), getEntity().getStoragePoolId()); } else { AsyncDataProvider.getInstance().getDataCenterList(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { ClusterGuideModel model = (ClusterGuideModel) target; @SuppressWarnings("unchecked") List<StoragePool> dataCenters = (ArrayList<StoragePool>) returnValue; final List<StoragePool> localDataCenters = new ArrayList<StoragePool>(); boolean enableButton = false; for (StoragePool dataCenter: dataCenters) { if (model.getEntity().getCompatibilityVersion().compareTo( dataCenter.getCompatibilityVersion()) >= 0 ) { if (dataCenter.isLocal()) { localDataCenters.add(dataCenter); } else { enableButton = true; break; } } } if (enableButton || localDataCenters.isEmpty()) { model.updateOptionsRequiredAddDataCenter(enableButton); } else { model.updateOptionsRequiredAddDataCenter(localDataCenters); } } } )); } }
Source:
protected static int appendPattern(boolean[] target, int pos, int[] pattern, boolean startColor) { int numAdded = 9; for (int bit : pattern) { target[pos++] = bit == 0 ? false : true; } return numAdded; }

Target:
protected static int appendPattern(boolean[] target, int pos, int[] pattern, boolean startColor) { for (int bit : pattern) { target[pos++] = bit != 0; } return 9; }
Source:
public void onMapReady(@NonNull MapboxMap mapboxMap) { MultipleGeometriesActivity.this.mapboxMap = mapboxMap; mapboxMap.setStyle(Style.LIGHT, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { createGeoJsonSource(); addPolygonLayer(); addPointsLayer(); } }); }

Target:
public void onMapReady(@NonNull MapboxMap mapboxMap) { mapboxMap.setStyle(Style.LIGHT, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { createGeoJsonSource(style); addPolygonLayer(style); addPointsLayer(style); } }); }
Source:
public void onResume() { super.onResume(); contributionsPresenter.onAttachView(this); firstLocationUpdate = true; locationManager.addLocationListener(this); boolean isSettingsChanged = store.getBoolean(Prefs.IS_CONTRIBUTION_COUNT_CHANGED, false); store.putBoolean(Prefs.IS_CONTRIBUTION_COUNT_CHANGED, false); if (store.getBoolean("displayNearbyCardView", true)) { checkPermissionsAndShowNearbyCardView(); if (nearbyNotificationCardView.cardViewVisibilityState == NearbyNotificationCardView.CardViewVisibilityState.READY) { nearbyNotificationCardView.setVisibility(View.VISIBLE); } } else { nearbyNotificationCardView.setVisibility(View.GONE); } fetchCampaigns(); }

Target:
public void onResume() { super.onResume(); contributionsPresenter.onAttachView(this); firstLocationUpdate = true; locationManager.addLocationListener(this); if (store.getBoolean("displayNearbyCardView", true)) { checkPermissionsAndShowNearbyCardView(); if (nearbyNotificationCardView.cardViewVisibilityState == NearbyNotificationCardView.CardViewVisibilityState.READY) { nearbyNotificationCardView.setVisibility(View.VISIBLE); } } else { nearbyNotificationCardView.setVisibility(View.GONE); } fetchCampaigns(); }
Source:
public boolean isConnected(IProgressMonitor monitor) { boolean needStrategy = client.getAuthorizationStrategy() == null; if(needStrategy) { client.setAuthorizationStrategy(getAuthorizationStrategy()); } try { IAuthorizationContext context = client.getContext(client.getBaseURL().toString()); return context.isAuthorized(); } catch (UnauthorizedException e) { needStrategy = false; return false; } finally { if(needStrategy) { connect(); } } }

Target:
public boolean isConnected(IProgressMonitor monitor) { boolean needStrategy = initAuthorizationStrategy(); try { IAuthorizationContext context = client.getContext(client.getBaseURL().toString()); return context.isAuthorized(); } catch (UnauthorizedException e) { needStrategy = false; return false; } finally { if(needStrategy) { connect(); } } }
Source:
public List<JudgmentEnrichmentTags> fetchEnrichmentTagsForJudgments(List<Long> judgmentIds) { List<EnrichmentTag> enrichmentTags = enrichmentTagRepository.findAllByJudgmentIds(judgmentIds); List<Object[]> enrichmentTagsWithReference = fetchJudgmentsReferencingTags(judgmentIds); Map<Long, JudgmentEnrichmentTags> judgmentsEnrichmentTagsMap = Maps.newHashMapWithExpectedSize(judgmentIds.size()); initializeJudgmentsEnrichmentTagsMap(judgmentsEnrichmentTagsMap, judgmentIds); collectJudgmentsEnrichmentTags(judgmentsEnrichmentTagsMap, enrichmentTags); collectJudgmentsReferencingEnrichmentTags(judgmentsEnrichmentTagsMap, enrichmentTagsWithReference); return Lists.newLinkedList(judgmentsEnrichmentTagsMap.values()); }

Target:
public List<JudgmentEnrichmentTags> fetchEnrichmentTagsForJudgments(List<Long> judgmentIds) { Map<Long, JudgmentEnrichmentTags> judgmentsDirectEnrichmentTagsMap = fetchJudgmentsDirectTags(judgmentIds); Map<Long, JudgmentEnrichmentTags> judgmentsReferencingEnrichmentTags = fetchJudgmentsReferencingTags(judgmentIds); Map<Long, JudgmentEnrichmentTags> judgmentsEnrichmentTagsMap = initializeJudgmentsEnrichmentTagsMap(judgmentIds); mergeJudgmentsEnrichmentTagsMaps(judgmentsDirectEnrichmentTagsMap, judgmentsEnrichmentTagsMap); mergeJudgmentsEnrichmentTagsMaps(judgmentsReferencingEnrichmentTags, judgmentsEnrichmentTagsMap); return Lists.newLinkedList(judgmentsEnrichmentTagsMap.values()); }
Source:
public String getMessage(EObject eObject, String value) { URI uri = eObject.eResource().getURI(); if (uri != null && uri.isPlatformPlugin() && uri.segmentCount() > 1) { Bundle bundle = Platform.getBundle(uri.segment(1)); return MessageTranslator.INSTANCE.getMessage(bundle, value); } return value; }

Target:
public String getMessage(EObject eObject, String value) { if (eObject.eResource() != null) { URI uri = eObject.eResource().getURI(); if (uri != null && uri.isPlatformPlugin() && uri.segmentCount() > 1) { Bundle bundle = Platform.getBundle(uri.segment(1)); return MessageTranslator.INSTANCE.getMessage(bundle, value); } } return value; }
Source:
protected Buffer getBuffer(Dsn dsn) { File bufferDir; String bufferDirOpt = Lookup.lookup(BUFFER_DIR_OPTION, dsn); if (bufferDirOpt != null) { bufferDir = new File(bufferDirOpt); } else { bufferDir = new File(this.ctx.getCacheDir().getAbsolutePath(), DEFAULT_BUFFER_DIR); } Log.d(TAG, "Using buffer dir: " + bufferDir.getAbsolutePath()); return new DiskBuffer(bufferDir, getBufferSize(dsn)); }

Target:
protected Buffer getBuffer(Dsn dsn) { File bufferDir; String bufferDirOpt = Lookup.lookup(BUFFER_DIR_OPTION, dsn); if (bufferDirOpt != null) { bufferDir = new File(bufferDirOpt); } else { bufferDir = new File(ctx.getCacheDir().getAbsolutePath(), DEFAULT_BUFFER_DIR); } Log.d(TAG, "Using buffer dir: " + bufferDir.getAbsolutePath()); return new DiskBuffer(bufferDir, getBufferSize(dsn)); }
Source:
public ProjectEditPage insertProjectData(Project project) { titleInput.sendKeys(project.getTitle()); pagesAmountInput.clear(); pagesAmountInput.sendKeys(project.getNumberOfPages().toString()); volumeAmountInput.clear(); volumeAmountInput.sendKeys(project.getNumberOfVolumes().toString()); selectTrigger.click(); WebElement option = Browser.getDriver().findElement(By.id("editForm:projectTabView:client_1")); option.click(); startDateInput.clear(); if (SystemUtils.USER_LANGUAGE.equals("en")) { startDateInput.sendKeys("05/08/18"); endDateInput.clear(); endDateInput.sendKeys("05/08/19"); } else { startDateInput.sendKeys("05.08.18"); endDateInput.clear(); endDateInput.sendKeys("05.08.19"); } return this; }

Target:
public ProjectEditPage insertProjectData(Project project) { titleInput.sendKeys(project.getTitle()); pagesAmountInput.clear(); pagesAmountInput.sendKeys(project.getNumberOfPages().toString()); volumeAmountInput.clear(); volumeAmountInput.sendKeys(project.getNumberOfVolumes().toString()); selectTrigger.click(); WebElement option = Browser.getDriver().findElement(By.id("editForm:projectTabView:client_1")); option.click(); startDateInput.clear(); endDateInput.clear(); if (SystemUtils.USER_LANGUAGE.equals("en")) { startDateInput.sendKeys("08/05/18"); endDateInput.sendKeys("08/05/19"); } else { startDateInput.sendKeys("05.08.18"); endDateInput.sendKeys("05.08.19"); } return this; }
Source:
private Enumerator<T> enumeratorBasedOnPeparedStatement() { Connection connection = null; PreparedStatement statement = null; try { connection = dataSource.getConnection(); statement = connection.prepareStatement(sql); setTimeoutIfPossible(statement); consumer.accept(statement); if (statement.execute()) { final ResultSet resultSet = statement.getResultSet(); statement = null; connection = null; return new ResultSetEnumerator<>(resultSet, rowBuilderFactory); } else { Integer updateCount = statement.getUpdateCount(); return Linq4j.singletonEnumerator((T) updateCount); } } catch (SQLException e) { throw new RuntimeException("while executing SQL [" + sql + "]", e); } finally { closeIfPossible(connection, statement); } }

Target:
private Enumerator<T> enumeratorBasedOnPeparedStatement() { Connection connection = null; PreparedStatement statement = null; try { connection = dataSource.getConnection(); statement = connection.prepareStatement(sql); setTimeoutIfPossible(statement); preparedStatementEnricher.enrich(statement); if (statement.execute()) { final ResultSet resultSet = statement.getResultSet(); statement = null; connection = null; return new ResultSetEnumerator<>(resultSet, rowBuilderFactory); } else { Integer updateCount = statement.getUpdateCount(); return Linq4j.singletonEnumerator((T) updateCount); } } catch (SQLException e) { throw Static.RESOURCE.exceptionWhilePerformingQueryOnJDBSubschema(sql).ex(e); } finally { closeIfPossible(connection, statement); } }
Source:
private void showResultDialog() { BranchResultDialog.show(bop.getResult(), repository, refName); if (refName == null && bop.getResult().getStatus() == CheckoutResult.Status.OK) showDetachedHeadWarning(); }

Target:
private void showResultDialog() { BranchResultDialog.show(bop.getResult(), repository, refName); try { if (ObjectId.isId(repository.getFullBranch()) && bop.getResult().getStatus() == CheckoutResult.Status.OK) showDetachedHeadWarning(); } catch (IOException e) { } }
Source:
protected void onCreate(Bundle arg0) { if (isLandscape()) { setTheme(android.R.style.Theme_NoTitleBar_Fullscreen); } super.onCreate(arg0); updateActionBarShadow(); logger.debug( "created"); }

Target:
protected void onCreate(Bundle arg0) { super.onCreate(arg0); updateActionBarShadow(); logger.debug( "created"); }
Source:
public static JsonObject beanToJson(Object bean) { if (bean == null) { throw new RuntimeException("Cannot convert null to a JSON object"); } try { return Json.parse(objectMapper.writeValueAsString(bean)); } catch (JsonProcessingException e) { throw new RuntimeException("Error converting bean to JSON", e); } }

Target:
public static JsonObject beanToJson(Object bean) { Objects.requireNonNull(bean, "Cannot convert null to a JSON object"); try { return Json.parse(objectMapper.writeValueAsString(bean)); } catch (JsonProcessingException e) { throw new RuntimeException("Error converting bean to JSON", e); } }
Source:
public void doRequest( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { ToolUser user = AuthenticationFilter.Static.getUser(request); if (user != null) { Schedule currentSchedule = Query.from(Schedule.class).where("_id = ?", request.getParameter("_scheduleId")).first(); if (currentSchedule == null) { currentSchedule = user.getCurrentSchedule(); } Date date = ObjectUtils.to(Date.class, request.getParameter("_date")); if (currentSchedule != null || date != null || PageFilter.Static.isPreview(request)) { try { PreviewDatabase pd = new PreviewDatabase(); pd.setDelegate(Database.Static.getDefault()); if (currentSchedule != null) { pd.addChanges(currentSchedule); } else if (date != null) { pd.setDate(date); } Database.Static.overrideDefault(pd); State mainState = State.getInstance(PageFilter.Static.getMainObject(request)); if (mainState != null) { mainState.setDatabase(null); mainState.setResolveInvisible(true); mainState.setValues(State.getInstance(pd.applyChanges(Query .fromAll() .where("_id = ?", mainState.getId()) .resolveInvisible() .noCache() .first())).getSimpleValues()); } chain.doFilter(request, response); } finally { Database.Static.restoreDefault(); } return; } } chain.doFilter(request, response); }

Target:
public void doRequest( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { ToolUser user = AuthenticationFilter.Static.getUser(request); if (user != null) { Schedule currentSchedule = Query.from(Schedule.class).where("_id = ?", request.getParameter("_scheduleId")).first(); if (currentSchedule == null) { currentSchedule = user.getCurrentSchedule(); } Date date = ObjectUtils.to(Date.class, request.getParameter("_date")); if (currentSchedule != null || date != null || PageFilter.Static.isPreview(request)) { try { PreviewDatabase pd = new PreviewDatabase(); pd.setDelegate(Database.Static.getDefault()); if (currentSchedule != null) { pd.addChanges(currentSchedule); } else if (date != null) { pd.setDate(date); } Database.Static.overrideDefault(pd); Object mainObject = PageFilter.Static.getMainObject(request); State mainState = State.getInstance(PageFilter.Static.getMainObject(request)); if (mainState != null) { Object originalObject = Query .fromAll() .where("_id = ?", mainState.getId()) .resolveInvisible() .noCache() .first(); mainState.setDatabase(null); mainState.setResolveInvisible(true); if (originalObject != null) { mainState.setValues(State.getInstance(pd.applyChanges(originalObject)).getSimpleValues()); } else { mainState.setValues(State.getInstance(pd.applyChanges(mainObject)).getSimpleValues()); } } chain.doFilter(request, response); } finally { Database.Static.restoreDefault(); } return; } } chain.doFilter(request, response); }
Source:
public void doesNotBatchRequestsIfBatchingNotEnabled() { when(config.namespace()).thenReturn(Optional.of(CLIENT)); setUpTimeLockBlockInRuntimeConfig(); when(runtimeConfig.timestampClient()).thenReturn(ImmutableTimestampClientConfig.of(false)); createLockAndTimestampServicesForConfig(config, runtimeConfig).timelock().getFreshTimestamp(); availableServer.verify(postRequestedFor(urlEqualTo(TIMELOCK_TIMESTAMP_PATH))); }

Target:
public void doesNotBatchRequestsIfBatchingNotEnabled() { setUpTimeLockBlockInRuntimeConfig(); when(runtimeConfig.timestampClient()).thenReturn(ImmutableTimestampClientConfig.of(false)); createLockAndTimestampServicesForConfig(config, runtimeConfig).timelock().getFreshTimestamp(); availableServer.verify(postRequestedFor(urlEqualTo(TIMELOCK_TIMESTAMP_PATH))); }
Source:
protected NIOServerCnxn createConnection(SocketChannel sock, SelectionKey sk, SelectorThread selectorThread) throws IOException { NIOServerCnxn cnxn = null; if (serverCnxnClassCtr != null) { try { cnxn = serverCnxnClassCtr.newInstance(zkServer, sock, sk, this, selectorThread); } catch (InstantiationException e1) { LOG.debug("Can not instantiate class for " + serverCnxnClassCtr.getName() + ". Using NIOServerCnxn"); } catch (IllegalAccessException e1) { LOG.debug("IllegalAccessException for " + serverCnxnClassCtr.getName() + ". Using NIOServerCnxn"); } catch (InvocationTargetException e1) { LOG.debug("InvocationTargetException for " + serverCnxnClassCtr.getName() + ". Using NIOServerCnxn"); } catch (Throwable t) { LOG.debug("Unknown Exception while dealing with: . Using NIOServerCnxn", serverCnxnClassCtr.getName()); } } if (cnxn == null) { cnxn = new NIOServerCnxn(zkServer, sock, sk, this, selectorThread); } return cnxn; }

Target:
protected NIOServerCnxn createConnection(SocketChannel sock, SelectionKey sk, SelectorThread selectorThread) throws IOException { try { return serverCnxnClassCtr.newInstance(zkServer, sock, sk, this, selectorThread); } catch (Throwable t) { throw new IOException("Can not instantiate class for " + serverCnxnClassCtr.getName(), t); } }
Source:
private Mac getHMAC() throws NoSuchAlgorithmException, CloneNotSupportedException, InvalidKeyException { lock.readLock().lock(); try { if (lastSecretKey != null && !isKeyExpired()) { if (hmac != null) { return (Mac) hmac.clone(); } else { Mac hmac = Mac.getInstance("HmacSHA256"); hmac.init(lastSecretKey); return hmac; } } } finally { lock.readLock().unlock(); } lock.writeLock().lock(); try { if (hmac == null) { hmac = Mac.getInstance("HmacSHA256"); hmac.init(generateSecretKey()); } else if (isKeyExpired()) { hmac.init(generateSecretKey()); } return (Mac) hmac.clone(); } catch (CloneNotSupportedException ex) { Mac hmac = this.hmac; this.hmac = null; return hmac; } finally { lock.writeLock().unlock(); } }

Target:
private Mac getHMAC() throws GeneralSecurityException { lock.readLock().lock(); try { if (lastSecretKey != null && !isKeyExpired()) { return createHMAC(); } } finally { lock.readLock().unlock(); } lock.writeLock().lock(); try { if (lastSecretKey == null) { generateSecretKey(); hmac = Mac.getInstance("HmacSHA256"); hmac.init(lastSecretKey); return (Mac) hmac.clone(); } else if (isKeyExpired()) { generateSecretKey(); } return createHMAC(); } catch (CloneNotSupportedException ex) { Mac hmac = this.hmac; this.hmac = null; return hmac; } finally { lock.writeLock().unlock(); } }
Source:
public void run() { final IndirectClient client = getClient(); final MockWebContext context = MockWebContext.create(); final String url = client.getRedirectAction(context).getLocation(); logger.warn("Redirect to: \n{}", url); logger.warn("Use credentials: / {}", getLogin(), getPassword()); if (canCancel()) { logger.warn("You can CANCEL the authentication."); } logger.warn("Returned url (copy/paste the fragment starting before the question mark of the query string):"); final Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.name()); final String returnedUrl = scanner.nextLine().trim(); populateContextWithUrl(context, returnedUrl); final CommonProfile profile = (CommonProfile) client.getCredentials(context).map(credentials -> client.getUserProfile((Credentials) credentials, context) ).orElse(null); logger.debug("userProfile: {}", profile); if (profile != null || !canCancel()) { verifyProfile(profile); logger.warn("## Java serialization"); final JavaSerializationHelper javaSerializationHelper = new JavaSerializationHelper(); byte[] bytes = javaSerializationHelper.serializeToBytes(profile); final CommonProfile profile2 = (CommonProfile) javaSerializationHelper.unserializeFromBytes(bytes); verifyProfile(profile2); } logger.warn("################"); logger.warn("Test successful!"); }

Target:
public void run() { final IndirectClient client = getClient(); final MockWebContext context = MockWebContext.create(); final String url = client.getRedirectAction(context).getLocation(); logger.warn("Redirect to: \n{}", url); logger.warn("Use credentials: / {}", getLogin(), getPassword()); if (canCancel()) { logger.warn("You can CANCEL the authentication."); } logger.warn("Returned url (copy/paste the fragment starting before the question mark of the query string):"); final Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.name()); final String returnedUrl = scanner.nextLine().trim(); populateContextWithUrl(context, returnedUrl); client.getCredentials(context).map(credentials -> client.getUserProfile((Credentials) credentials, context) ).ifPresent( p -> { CommonProfile profile = (CommonProfile) p; logger.debug("userProfile: {}", profile); if (!canCancel()) { verifyProfile(profile); logger.warn("## Java serialization"); final JavaSerializationHelper javaSerializationHelper = new JavaSerializationHelper(); byte[] bytes = javaSerializationHelper.serializeToBytes(profile); final CommonProfile profile2 = (CommonProfile) javaSerializationHelper.unserializeFromBytes(bytes); verifyProfile(profile2); } } ); logger.warn("################"); logger.warn("Test successful!"); }
Source:
private ListenableFuture<QueryResult<Content>> executeSingleQuery(final Query<Content> query) { final Id contentId = query.getOnlyId(); return Futures.transform(resolve(query, contentId), (ResolvedEquivalents<Content> input) -> { List<Content> equivs = input.get(contentId).asList(); if (equivs.isEmpty()) { throw new UncheckedQueryExecutionException(new NotFoundException(contentId)); } if (equivs.size() == 1) { Content resource = equivs.get(0); return QueryResult.singleResult(resource, query.getContext()); } else { return QueryResult.listResult(equivs, query.getContext(), equivs.size()); } } ); }

Target:
private ListenableFuture<QueryResult<Content>> executeSingleQuery(final Query<Content> query) { final Id contentId = query.getOnlyId(); return Futures.transform(resolve(query, contentId), (ResolvedEquivalents<Content> input) -> { List<Content> equivs = input.get(contentId).asList(); if (equivs.isEmpty()) { throw new UncheckedQueryExecutionException(new NotFoundException(contentId)); } Content resource = equivs.get(0); return QueryResult.singleResult(resource, query.getContext()); } ); }
Source:
Timer.Sample timerStart(String consumerName, String lifecycle) { if (consumerName == null || consumerName.length() == 0) return null; if (lifecycle == null || lifecycle.length() == 0) return null; Map<String, Timer.Sample> queueTimers = timers.get(consumerName); if (queueTimers == null) { queueTimers = new HashMap<>(); timers.put(consumerName, queueTimers); } String threadLifecycle = lifecycle + Thread.currentThread().getId(); Timer.Sample sampler = queueTimers.get(threadLifecycle); if (sampler == null) { sampler = Timer.start(registry); queueTimers.put(threadLifecycle, sampler); } return sampler; }

Target:
Timer.Sample timerStart(String consumerName, String lifecycle) { if (consumerName == null || consumerName.length() == 0) return null; if (lifecycle == null || lifecycle.length() == 0) return null; String threadLifecycle = lifecycle + Thread.currentThread().getId(); String compositeKey = consumerName + threadLifecycle; return timers.computeIfAbsent(compositeKey, k -> Timer.start(registry)); }
Source:
private static SiriusContext fromUnknownEObject(EObject obj) { Session session = SessionManager.INSTANCE.getSession(obj); Resource res = EcoreUtil.getRootContainer(obj).eResource(); EObject semanticElement = null; if (session != null && res != null && session.getSemanticResources().contains(res)) { semanticElement = obj; } return new SiriusContext(obj, session, null, null, semanticElement); }

Target:
private static SiriusContext fromUnknownEObject(EObject obj) { Session session = Session.of(obj).orElse(null); Resource res = EcoreUtil.getRootContainer(obj).eResource(); EObject semanticElement = null; if (session != null && res != null && session.getSemanticResources().contains(res)) { semanticElement = obj; } return new SiriusContext(obj, session, null, null, semanticElement); }
Source:
public void getPayment_ReturnsPaymentWithCaptureUrl() { publicAuthMock.mapBearerTokenToAccountId(API_KEY, GATEWAY_ACCOUNT_ID); connectorMock.respondWithChargeFoundAndCaptureUrl(250, GATEWAY_ACCOUNT_ID, CHARGE_ID, CAPTURED, RETURN_URL, DESCRIPTION, REFERENCE, EMAIL, PAYMENT_PROVIDER, CREATED_DATE, SupportedLanguage.ENGLISH, true, REFUND_SUMMARY, SETTLEMENT_SUMMARY, CARD_DETAILS, 0L, 250L); getPaymentResponse(API_KEY, CHARGE_ID) .statusCode(200) .contentType(JSON) .body("_links.capture.href", is(paymentLocationFor(CHARGE_ID) + "/capture")) .body("_links.capture.method", is("POST")); }

Target:
public void getPayment_ReturnsPaymentWithCaptureUrl() { publicAuthMock.mapBearerTokenToAccountId(API_KEY, GATEWAY_ACCOUNT_ID); connectorMock.respondWithChargeFound(AMOUNT, GATEWAY_ACCOUNT_ID, CHARGE_ID, AWAITING_CAPTURE_REQUEST, RETURN_URL, DESCRIPTION, REFERENCE, EMAIL, PAYMENT_PROVIDER, CREATED_DATE, SupportedLanguage.ENGLISH, true, CHARGE_TOKEN_ID, REFUND_SUMMARY, SETTLEMENT_SUMMARY, CARD_DETAILS, 0L, 0L); getPaymentResponse(API_KEY, CHARGE_ID) .statusCode(200) .contentType(JSON) .body("_links.capture.href", is(paymentLocationFor(CHARGE_ID) + "/capture")) .body("_links.capture.method", is("POST")); }
Source:
private void storeWindowIfNeeded(Application application, Accumulator<Object> children, List<WeakReference<Activity>> activities){ List<View>windows = WindowFetcher.getWindowViews(application); if (windows == null){ return; } for (View view : windows) { if (belongToActivity(view, activities)) { continue; } children.store(view); } }

Target:
private void storeWindowIfNeeded(Application application, Accumulator<Object> children, List<WeakReference<Activity>> activities) { List<View> rootViews = WindowRootViewCompat.get(application).getRootViews(); for (View view : rootViews) { if (!isDecorViewOfActivity(view, activities)) { children.store(view); } } }
Source:
public SweepDelay(long configPause) { this.initialPause = Math.min(Math.max(MIN_PAUSE_MILLIS, configPause), MAX_PAUSE_MILLIS); this.currentPause = new AtomicLong(initialPause); }

Target:
SweepDelay(long configPause) { this.maxPauseMillis = Math.max(DEFAULT_MAX_PAUSE_MILLIS, configPause); this.initialPause = Math.max(MIN_PAUSE_MILLIS, configPause); this.currentPause = new AtomicLong(initialPause); }
Source:
public void readEmptyServerObject() throws Exception { final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); final JsonNode rootNode = mapper.readTree(Files.readAllBytes(java.nio.file.Paths.get(getClass().getResource("/oas2.yaml").toURI()))); final OpenAPIDeserializer deserializer = new OpenAPIDeserializer(); final SwaggerParseResult result = deserializer.deserialize(rootNode); Assert.assertNotNull(result); final OpenAPI openAPI = result.getOpenAPI(); Assert.assertNotNull(openAPI); assertEquals(openAPI.getServers().get(0).getUrl(),"/"); }

Target:
public void readEmptyServerObject() throws Exception { final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); final JsonNode rootNode = mapper.readTree(Files.readAllBytes(java.nio.file.Paths.get(getClass().getResource("/oas2.yaml.template").toURI()))); final OpenAPIDeserializer deserializer = new OpenAPIDeserializer(); final SwaggerParseResult result = deserializer.deserialize(rootNode); Assert.assertNotNull(result); final OpenAPI openAPI = result.getOpenAPI(); Assert.assertNotNull(openAPI); assertEquals(openAPI.getServers().get(0).getUrl(),"/"); }
Source:
public void startUp(IngestJobContext context) throws IngestModuleException { this.context = context; try { fileManager = Case.getOpenCase().getServices().getFileManager(); } catch (NoCurrentCaseException ex) { logger.log(Level.SEVERE, "Exception while getting open case.", ex); } }

Target:
public void startUp(IngestJobContext context) throws IngestModuleException { this.context = context; try { fileManager = Case.getOpenCase().getServices().getFileManager(); } catch (NoCurrentCaseException ex) { logger.log(Level.SEVERE, "Exception while getting open case.", ex); throw new IngestModuleException(Bundle.ThunderbirdMboxFileIngestModule_noOpenCase_errMsg(), ex); } }
Source:
public void testCategoryAttributeList() { MetacardImpl metacard = new MetacardImpl(); metacard.setAttribute(Core.TITLE, "The Title"); List<HtmlExportCategory> categoryList = new ArrayList<>(); categoryList.add(new HtmlCategoryModel("Core", coreList)); HtmlMetacardModel metacardModel = new HtmlMetacardModel(metacard, categoryList); HtmlExportCategory category = metacardModel.getCategories().get(0); assertTrue(category.getAttributeList().contains(Core.TITLE)); }

Target:
public void testCategoryAttributeList() { MetacardImpl metacard = new MetacardImpl(); metacard.setAttribute(Core.TITLE, METACARD_TITLE); List<HtmlExportCategory> categoryList = new ArrayList<>(); categoryList.add(new HtmlCategoryModel("Core", coreList)); HtmlMetacardModel metacardModel = new HtmlMetacardModel(metacard, categoryList); HtmlExportCategory category = metacardModel.getCategories().get(0); assertThat(category.getAttributes(), hasItem(Core.TITLE)); }
Source:
public void scheduleJobs() { SchedulerUtil sched = getSchedulUtil(); int refreshRate = Config.<Integer> getValue(ConfigValues.VdsRefreshRate) * 1000; registeredJobs.add(sched.scheduleAFixedDelayJob( this, "onTimer", new Class[0], new Object[0], refreshRate, refreshRate, TimeUnit.MILLISECONDS)); double availableUpdatesRefreshRate = Config.<Double> getValue(ConfigValues.HostPackagesUpdateTimeInHours); final int HOURS_TO_MINUTES = 60; long rateInMinutes = Math.round(availableUpdatesRefreshRate * HOURS_TO_MINUTES); registeredJobs.add(sched.scheduleAFixedDelayJob( this, "availableUpdates", new Class[0], new Object[0], RandomUtils.nextInt(HOURS_TO_MINUTES) + 1, rateInMinutes, TimeUnit.MINUTES)); vmsRefresher = getVmStatsRefresherFactory().create(this); vmsRefresher.startMonitoring(); hostRefresher = new RefreshHostOnHostConnectionChangeEvent(this); hostRefresher.startMonitoring(); }

Target:
public void scheduleJobs() { SchedulerUtil sched = getSchedulUtil(); int refreshRate = Config.<Integer> getValue(ConfigValues.VdsRefreshRate) * 1000; registeredJobs.add(sched.scheduleAFixedDelayJob( this, "onTimer", new Class[0], new Object[0], refreshRate, refreshRate, TimeUnit.MILLISECONDS)); double availableUpdatesRefreshRate = Config.<Double> getValue(ConfigValues.HostPackagesUpdateTimeInHours); final int HOURS_TO_MINUTES = 60; long rateInMinutes = Math.round(availableUpdatesRefreshRate * HOURS_TO_MINUTES); registeredJobs.add(sched.scheduleAFixedDelayJob( this, "availableUpdates", new Class[0], new Object[0], RandomUtils.nextInt(HOURS_TO_MINUTES) + 1, rateInMinutes, TimeUnit.MINUTES)); vmsRefresher = getVmStatsRefresherFactory().create(this); vmsRefresher.startMonitoring(); hostRefresher = new RefreshHostOnHostConnectionChangeEvent(this, resourceManager); hostRefresher.startMonitoring(); }
Source:
public CdRom get() { if (QueryHelper.hasMatrixParam(getUriInfo(), CURRENT_CONSTRAINT_PARAMETER)) { VM vm = collection.lookupEntity(guid); if (vm == null) { return notFound(); } if (vm.getCurrentCd() != null) { vm.setIsoPath(vm.getCurrentCd()); } return addLinks(populate(map(vm), vm)); } else { return super.get(); } }

Target:
public CdRom get() { final boolean getCurrent = QueryHelper.hasMatrixParam(getUriInfo(), CURRENT_CONSTRAINT_PARAMETER) && !"false".equalsIgnoreCase(QueryHelper.getMatrixConstraint(getUriInfo(), CURRENT_CONSTRAINT_PARAMETER)); if (getCurrent) { VM vm = collection.lookupEntity(guid); if (vm == null) { return notFound(); } if (vm.getCurrentCd() != null) { vm.setIsoPath(vm.getCurrentCd()); } return addLinks(populate(map(vm), vm)); } else { return super.get(); } }
Source:
public String toString() { if (m_tableName == null) { return m_name + "(" + m_index + ")"; } else { return getName(); } }

Target:
public String toString() { if (getAlias() != null && !getAlias().equals(getColumnName())) { return getAlias() + "(" + getIndex() + ")"; } else { return getName(); } }
Source:
public void pathologicalInputOrderingTest() { final GraphUtils.Graph<Integer> graph = new GraphUtils.Graph<>(); final int a = 0, b = 1, c = 2, d = 3, e = 4, f = 5, h = 6, g = 7; graph.addNode(a); graph.addNode(b); graph.addNode(c); graph.addNode(d); graph.addNode(f); graph.addNode(h); graph.addNode(e); graph.addNode(g); graph.addEdge(a, h); graph.addEdge(b, f); graph.addEdge(c, h); graph.addEdge(d, f); graph.addEdge(e, h); graph.addEdge(e, f); graph.addEdge(g, a); final Map<Integer, Integer> clusters = graph.cluster(); assertEquals(clusters.size(), 8); final Integer repCluster = clusters.get(a); IntStream.range(0,7).forEach(i -> assertEquals(clusters.get(i), repCluster)); }

Target:
public void pathologicalInputOrderingTest() { final GraphUtils.Graph<Integer> graph = new GraphUtils.Graph<>(); final int a = 0, b = 1, c = 2, d = 3, e = 4, f = 5, h = 6, g = 7; graph.addNode(a); graph.addNode(b); graph.addNode(c); graph.addNode(d); graph.addNode(f); graph.addNode(h); graph.addNode(e); graph.addNode(g); graph.addEdge(a, h); graph.addEdge(b, f); graph.addEdge(c, h); graph.addEdge(d, f); graph.addEdge(e, h); graph.addEdge(e, f); graph.addEdge(g, a); final Map<Integer, Integer> clusters = graph.cluster(); assertEquals(clusters.size(), 8); final Integer repCluster = clusters.get(a); graph.getNodes().forEach(i -> assertEquals(clusters.get(i), repCluster)); }
Source:
protected void releaseDocument(IDocument document, IProgressMonitor pm) throws CoreException { boolean isModified= isDocumentModified(); super.releaseDocument(document, pm); try { fCUnit.discardWorkingCopy(); } finally { if (isModified && !isDocumentAcquired()) { if (fCUnit.isWorkingCopy()) fCUnit.reconcile( ICompilationUnit.NO_AST, false , null , null ); else fCUnit.makeConsistent(pm); } } }

Target:
protected void releaseDocument(IDocument document, IProgressMonitor pm) throws CoreException { boolean isModified= isDocumentModified(); SubMonitor subMonitor= SubMonitor.convert(pm, 2); super.releaseDocument(document, subMonitor.newChild(1)); try { fCUnit.discardWorkingCopy(); } finally { if (isModified && !isDocumentAcquired()) { if (fCUnit.isWorkingCopy()) fCUnit.reconcile( ICompilationUnit.NO_AST, false , null , subMonitor.newChild(1)); else fCUnit.makeConsistent(subMonitor.newChild(1)); } } subMonitor.setWorkRemaining(0); }
Source:
public void initialize(OperatorContext op) throws Exception { super.initialize(op); trace.log(TraceLevel.INFO, "Using authentication type: " + authenticationType); if(authenticationFile != null) { authenticationFile = authenticationFile.trim(); } URI baseConfigURI = op.getPE().getApplicationDirectory().toURI(); auth = AuthHelper.getAuthenticator(authenticationType, PathConversionHelper.convertToAbsPath(baseConfigURI, authenticationFile), authenticationProperties); rc = new RetryController(maxRetries, retryDelay); hasOutputPort = op.getStreamingOutputs().size() == 1; final StreamSchema inputSchema = getInput(0).getStreamSchema(); if((!headerContentType.equals(MIME_FORM) && !headerContentType.equals(MIME_JSON))) { if(inputSchema.getAttributeCount() != 1) throw new Exception("Only a single attribute is permitted in the input stream for content type \"" + headerContentType + "\""); } if (headerContentType.equals(MIME_FORM)) processType = ProcessType.TUPLE_FORM; else if (headerContentType.equals(MIME_JSON)) { processType = ProcessType.TUPLE_JSON; if (inputSchema.getAttributeCount() == 1) { Attribute attr = inputSchema.getAttribute(0); if (isStandardJsonAttribute(attr)) { processType = ProcessType.PURE_JSON; } } else { for (Attribute attr : inputSchema) { if (isStandardJsonAttribute(attr)) { processType = ProcessType.MIX_JSON; break; } } } } if (postAttributes.size() > 0) { if ((headerContentType.equals(MIME_FORM) || headerContentType.equals(MIME_JSON))) { } else { throw new Exception(" PostAttributes specified with headerContentType value other than: " + MIME_FORM + "," + MIME_JSON + "; found '" + headerContentType + "'."); } } trace.log(TraceLevel.INFO, "URL: " + url); }

Target:
public void initialize(OperatorContext op) throws Exception { super.initialize(op); trace.log(TraceLevel.INFO, "Using authentication type: " + authenticationType); if(authenticationFile != null) { authenticationFile = authenticationFile.trim(); } URI baseConfigURI = op.getPE().getApplicationDirectory().toURI(); auth = AuthHelper.getAuthenticator(authenticationType, PathConversionHelper.convertToAbsPath(baseConfigURI, authenticationFile), authenticationProperties); rc = new RetryController(maxRetries, retryDelay); hasOutputPort = op.getStreamingOutputs().size() == 1; final StreamSchema inputSchema = getInput(0).getStreamSchema(); if((!headerContentType.equals(MIME_FORM) && !headerContentType.equals(MIME_JSON))) { if(inputSchema.getAttributeCount() != 1) throw new Exception("Only a single attribute is permitted in the input stream for content type \"" + headerContentType + "\""); } if (headerContentType.equals(MIME_FORM)) processType = ProcessType.TUPLE_FORM; else if (headerContentType.equals(MIME_JSON)) { processType = ProcessType.TUPLE_JSON; if (inputSchema.getAttributeCount() == 1) { Attribute attr = inputSchema.getAttribute(0); if (isStandardJsonAttribute(attr)) { processType = ProcessType.PURE_JSON; } } else { for (Attribute attr : inputSchema) { if (isStandardJsonAttribute(attr)) { processType = ProcessType.MIX_JSON; break; } } } } trace.log(TraceLevel.INFO, "URL: " + url); }