auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void writeData() { if (commitExecutor.isShutdown()) { if (!commitExecutor.isTerminated()) { try { if (!commitExecutor .awaitTermination(OGlobalConfiguration.WAL_SHUTDOWN_TIMEOUT.getValueAsInteger(), TimeUnit.MILLISECONDS)) throw new OStorageException("Unable to write data, WAL commit executor appears hung"); } catch (InterruptedException e) { Thread.interrupted(); throw OException.wrapException(new OStorageException("Thread was interrupted during waiting for WAL commit executor"), e); } } new WriteTask().run(); } else { try { commitExecutor.submit(new WriteTask()).get(); } catch (InterruptedException e) { Thread.interrupted(); throw OException.wrapException(new OStorageException("Thread was interrupted during flush"), e); } catch (ExecutionException e) { throw OException.wrapException(new OStorageException("Error during WAL segment '" + getPath() + "' flush"), e); } } }

Target:
private void writeData() { if (commitExecutor.isShutdown()) if (flushNewData) throw new OStorageException("Unable to write data, WAL thread is shutdown"); else return; try { commitExecutor.submit(new WriteTask()).get(); } catch (InterruptedException e) { Thread.interrupted(); throw OException.wrapException(new OStorageException("Thread was interrupted during data write"), e); } catch (ExecutionException e) { throw OException.wrapException(new OStorageException("Error during WAL segment '" + getPath() + "' data write"), e); } }
Source:
public PropertyRegexTester(IPersonAttributesGroupTestDefinition definition) { super(definition); final String propertyName = definition.getTestValue(); String regexExpression = PropertiesManager.getProperty (propertyName, ""); if (StringUtils.isBlank(regexExpression)) { logger.error("Unable to find property name in portal.properties or has empty value." + " PAGS PropertyRegexTester will always return false for attribute {}", propertyName, definition.getAttributeName()); } setPattern(regexExpression); }

Target:
public PropertyRegexTester(IPersonAttributesGroupTestDefinition definition) { super(definition); setPattern(definition.getAttributeName(), definition.getTestValue()); }
Source:
public boolean isSuccessStatusCode() { return 200 <= this.statusCode && this.statusCode <= 299; }

Target:
public boolean isSuccessStatusCode() { return this.statusCode >= 200 && this.statusCode <= 299; }
Source:
public void factoryWithDirectUrlWithSpecificBranch() throws Exception { String repositoryName = testRepo.getName(); try { testFactoryWithSpecificBranch.authenticateAndOpen(); } catch (NoSuchElementException ex) { fail("<LINK_0>"); } projectExplorer.waitProjectExplorer(); notificationsPopupPanel.waitProgressPopupPanelClose(); events.clickEventLogBtn(); events.waitExpectedMessage( "Project " + repositoryName + " imported", UPDATING_PROJECT_TIMEOUT_SEC); events.waitExpectedMessage( "Successfully configured and cloned source code of " + repositoryName, UPDATING_PROJECT_TIMEOUT_SEC); events.waitExpectedMessage( "Project: " + repositoryName + " | cloned from: " + repositoryName + " | remote branch: refs/remotes/origin/" + SECOND_BRANCH_NAME + " | local branch: " + SECOND_BRANCH_NAME, UPDATING_PROJECT_TIMEOUT_SEC); projectExplorer.waitAndSelectItem(repositoryName); pullRequestPanel.waitOpenPanel(); projectExplorer.expandPathInProjectExplorer(repositoryName + "/my-lib"); projectExplorer.waitItem(repositoryName + "/my-lib/pom.xml"); String wsId = workspaceServiceClient .getByName(seleniumWebDriver.getWorkspaceNameFromBrowserUrl(), testUser.getName()) .getId(); List<String> visibleItems = projectExplorer.getNamesOfAllOpenItems(); assertTrue( visibleItems.containsAll( ImmutableList.of(repositoryName, "my-lib", "my-webapp", "src", "pom.xml"))); String projectType = testProjectServiceClient.getFirstProject(wsId).getType(); assertTrue(projectType.equals("blank")); }

Target:
public void factoryWithDirectUrlWithSpecificBranch() throws Exception { String repositoryName = testAuxiliaryRepo.getName(); try { testFactoryWithSpecificBranch.authenticateAndOpen(); } catch (NoSuchElementException ex) { fail("<LINK_0>"); } projectExplorer.waitProjectExplorer(); notificationsPopupPanel.waitProgressPopupPanelClose(); events.clickEventLogBtn(); events.waitExpectedMessage( "Project " + repositoryName + " imported", UPDATING_PROJECT_TIMEOUT_SEC); events.waitExpectedMessage( "Successfully configured and cloned source code of " + repositoryName, UPDATING_PROJECT_TIMEOUT_SEC); events.waitExpectedMessage( String.format( "Project: %s | cloned from: %s | remote branch: refs/remotes/origin/%s | local branch: %s", repositoryName, repositoryName, SECOND_BRANCH_NAME, SECOND_BRANCH_NAME), UPDATING_PROJECT_TIMEOUT_SEC); projectExplorer.waitAndSelectItem(repositoryName); pullRequestPanel.waitOpenPanel(); projectExplorer.expandPathInProjectExplorer(repositoryName + "/my-lib"); projectExplorer.waitItem(repositoryName + "/my-lib/pom.xml"); String wsId = workspaceServiceClient .getByName(seleniumWebDriver.getWorkspaceNameFromBrowserUrl(), testUser.getName()) .getId(); List<String> visibleItems = projectExplorer.getNamesOfAllOpenItems(); assertTrue( visibleItems.containsAll( ImmutableList.of(repositoryName, "my-lib", "my-webapp", "src", "pom.xml"))); String projectType = testProjectServiceClient.getFirstProject(wsId).getType(); assertTrue(projectType.equals("blank")); }
Source:
public void setWidth(int width) { this.width= width; }

Target:
protected final void setWidth(int width) { this.width= width; }
Source:
public Context(String type, String name) { Preconditions.checkNotNull(type, "type"); Preconditions.checkNotNull(name, "name"); this.type = type; this.name = name; }

Target:
public Context(String type, String name) { checkNotNull(type, "type"); checkNotNull(name, "name"); this.type = type; this.name = name; }
Source:
private void failAfterMinimum(final int next) throws SpuriousIOException { if (count.get() + next > minimumBytes) { throw new SpuriousIOException("Random error"); } }

Target:
private void failAfterMinimum(final int next) throws SpuriousIOException { if (count.get() + next > minimumBytes) { throw new SpuriousIOException("Read failure after byte " + minimumBytes); } }
Source:
public void testReadLz4() throws Exception { byte[] data = toByteArray(getResource("apache-lz4.orc")); OrcReader orcReader = new OrcReader(new InMemoryOrcDataSource(data), ORC, SIZE, SIZE, SIZE); assertEquals(orcReader.getCompressionKind(), LZ4); Map<Integer, Type> includedColumns = ImmutableMap.<Integer, Type>builder() .put(0, BIGINT) .put(1, INTEGER) .put(2, BIGINT) .build(); OrcRecordReader reader = orcReader.createRecordReader( includedColumns, OrcPredicate.TRUE, DateTimeZone.UTC, newSimpleAggregatedMemoryContext()); int rows = 0; while (true) { int batchSize = reader.nextBatch(); if (batchSize <= 0) { break; } rows += batchSize; Block xBlock = reader.readBlock(BIGINT, 0); Block yBlock = reader.readBlock(INTEGER, 1); Block zBlock = reader.readBlock(BIGINT, 2); for (int position = 0; position < batchSize; position++) { BIGINT.getLong(xBlock, position); INTEGER.getLong(yBlock, position); BIGINT.getLong(zBlock, position); } } assertEquals(rows, reader.getFileRowCount()); }

Target:
public void testReadLz4() throws Exception { byte[] data = toByteArray(getResource("apache-lz4.orc")); OrcReader orcReader = new OrcReader(new InMemoryOrcDataSource(data), ORC, SIZE, SIZE, SIZE); assertEquals(orcReader.getCompressionKind(), LZ4); assertEquals(orcReader.getFooter().getNumberOfRows(), 10_000); Map<Integer, Type> includedColumns = ImmutableMap.<Integer, Type>builder() .put(0, BIGINT) .put(1, INTEGER) .put(2, BIGINT) .build(); OrcRecordReader reader = orcReader.createRecordReader( includedColumns, OrcPredicate.TRUE, DateTimeZone.UTC, newSimpleAggregatedMemoryContext()); int rows = 0; while (true) { int batchSize = reader.nextBatch(); if (batchSize <= 0) { break; } rows += batchSize; Block xBlock = reader.readBlock(BIGINT, 0); Block yBlock = reader.readBlock(INTEGER, 1); Block zBlock = reader.readBlock(BIGINT, 2); for (int position = 0; position < batchSize; position++) { BIGINT.getLong(xBlock, position); INTEGER.getLong(yBlock, position); BIGINT.getLong(zBlock, position); } } assertEquals(rows, reader.getFileRowCount()); }
Source:
public Map<String, String> getFields() { Map<String, String> map = fFields; if (map == null) { byte[] array = Arrays.copyOfRange(fPayload.array(), 0, fPayload.limit()); Builder<String, String> builder = ImmutableMap.<@NonNull String, @NonNull String> builder() .put("Binary", ConversionHelper.bytesToHex(array, true)); try { String s = new String(array, "UTF-8"); builder.put("Character", s); } catch (UnsupportedEncodingException e) { } fFields = builder.build(); return fFields; } return map; }

Target:
public Map<String, String> getFields() { Map<String, String> map = fFields; if (map == null) { byte[] array = Arrays.copyOfRange(fPayload.array(), fPayload.arrayOffset(), fPayload.arrayOffset() + fPayload.limit()); Builder<String, String> builder = ImmutableMap.<@NonNull String, @NonNull String> builder() .put("Binary", ConversionHelper.bytesToHex(array, true)); try { String s = new String(array, "UTF-8"); builder.put("Character", s); } catch (UnsupportedEncodingException e) { } fFields = builder.build(); return fFields; } return map; }
Source:
public void setSchedulerService(SchedulerService schedulerService) throws InitialisationException { this.schedulerService = schedulerService; initialise(); }

Target:
void setSchedulerService(SchedulerService schedulerService) { this.schedulerService = schedulerService; }
Source:
public void shouldScheduleEmailCheckJob() throws SchedulerException { ebodacScheduler.unscheduleEmailCheckJob(); verify(motechSchedulerService).safeUnscheduleAllJobs(EbodacConstants.EMAIL_CHECK_EVENT); Integer interval = 500; ebodacScheduler.scheduleEmailCheckJob(interval); MotechEvent event = new MotechEvent(EbodacConstants.EMAIL_CHECK_EVENT); Period period = Period.minutes(interval); DateTime startDate = DateTime.now().plusMinutes(1); RepeatingPeriodSchedulableJob job = new RepeatingPeriodSchedulableJob(event, startDate.toDate(), null, period, true); verify(motechSchedulerService).safeScheduleRepeatingPeriodJob(job); }

Target:
public void shouldScheduleEmailCheckJob() { Integer interval = 500; DateTimeUtils.setCurrentMillisFixed(10L); DateTime startDate = DateTime.now().plusMinutes(1); ebodacScheduler.scheduleEmailCheckJob(interval); MotechEvent event = new MotechEvent(EbodacConstants.EMAIL_CHECK_EVENT); Period period = Period.minutes(interval); RepeatingPeriodSchedulableJob job = new RepeatingPeriodSchedulableJob(event, startDate.toDate(), null, period, true); verify(motechSchedulerService).safeScheduleRepeatingPeriodJob(job); }
Source:
public void testXSetWMProtocols() { X11.Atom[] protocols = new X11.Atom[]{ X11.INSTANCE.XInternAtom(display, "WM_DELETE_WINDOW", false) }; int status = X11.INSTANCE.XSetWMProtocols(display, root, protocols, 1); assertEquals("Bad status for XSetWMProtocols", 1, status); }

Target:
public void testXSetWMProtocols() { X11.Atom[] atoms = new X11.Atom[]{ X11.INSTANCE.XInternAtom(display, "WM_DELETE_WINDOW", false), X11.INSTANCE.XInternAtom(display, "WM_TAKE_FOCUS", false) }; int status = X11.INSTANCE.XSetWMProtocols(display, root, atoms, atoms.length); Assert.assertNotEquals("Bad status for XSetWMProtocols", 0, status); }
Source:
public static void placeVolumeInVolumeAccessGroups(SolidFireConnection sfConnection, long sfVolumeId, List<HostVO> hosts, String clusterUuId) { if (!SolidFireUtil.hostsSupport_iScsi(hosts)) { String errMsg = "Not all hosts in the compute cluster support iSCSI."; LOGGER.warn(errMsg); throw new CloudRuntimeException(errMsg); } List<SolidFireUtil.SolidFireVag> sfVags = SolidFireUtil.getAllVags(sfConnection); Map<SolidFireUtil.SolidFireVag, List<String>> sfVagToIqnsMap = buildVagToIQNMap(hosts, sfVags); if (sfVagToIqnsMap.size() > MAX_NUM_VAGS_PER_VOLUME) { throw new CloudRuntimeException("A SolidFire volume can be in at most four volume access groups simultaneously."); } if (sfVagToIqnsMap.containsKey(null)) { sfVagToIqnsMap = updateNullKeyInsfVagToIqnsMap(sfVagToIqnsMap, sfVags, sfConnection, clusterUuId, sfVolumeId); } addVoulumestoVagIfNotPresent(sfVagToIqnsMap.keySet(), sfVolumeId, sfConnection); }

Target:
public static void placeVolumeInVolumeAccessGroups(SolidFireConnection sfConnection, long sfVolumeId, List<HostVO> hosts, String clusterUuId) { if (!SolidFireUtil.hostsSupport_iScsi(hosts)) { String errMsg = "Not all hosts in the compute cluster support iSCSI."; LOGGER.warn(errMsg); throw new CloudRuntimeException(errMsg); } List<SolidFireUtil.SolidFireVag> sfVags = SolidFireUtil.getAllVags(sfConnection); Map<SolidFireUtil.SolidFireVag, List<String>> sfVagToIqnsMap = buildVagToIQNMap(hosts, sfVags); if (sfVagToIqnsMap.size() > MAX_NUM_VAGS_PER_VOLUME) { throw new CloudRuntimeException("A SolidFire volume can be in at most four volume access groups simultaneously."); } if (sfVagToIqnsMap.containsKey(null)) { sfVagToIqnsMap = updateNullKeyInSfVagToIqnsMap(sfVagToIqnsMap, sfVags, sfConnection, clusterUuId, sfVolumeId); } addVolumestoVagIfNotPresent(sfVagToIqnsMap.keySet(), sfVolumeId, sfConnection); }
Source:
public static List<TargetGroup> newTargetGroups( final Collection<Unit> units, final Collection<Unit> enemyUnits) { final Set<UnitType> unitTypes = units.stream().map(unit -> unit.getType()).collect(Collectors.toSet()); final Set<UnitType> enemyUnitTypes = enemyUnits.stream().map(unit -> unit.getType()).collect(Collectors.toSet()); final List<TargetGroup> firingGroups = new ArrayList<TargetGroup>(); for (final UnitType unitType : unitTypes) { final Set<UnitType> targets = findTargets(unitType, unitTypes, enemyUnitTypes); boolean isAdded = false; for (final TargetGroup firingGroup : firingGroups) { if (firingGroup.getTargetUnitTypes().equals(targets)) { firingGroup.getFiringUnitTypes().add(unitType); isAdded = true; break; } } if (!isAdded) { firingGroups.add(new TargetGroup(unitType, targets)); } } return sortFiringGroups(firingGroups); }

Target:
public static List<TargetGroup> newTargetGroups( final Collection<Unit> units, final Collection<Unit> enemyUnits) { final Set<UnitType> unitTypes = units.stream().map(unit -> unit.getType()).collect(Collectors.toSet()); final Set<UnitType> enemyUnitTypes = enemyUnits.stream().map(unit -> unit.getType()).collect(Collectors.toSet()); final List<TargetGroup> targetGroups = new ArrayList<TargetGroup>(); for (final UnitType unitType : unitTypes) { final Set<UnitType> targets = findTargets(unitType, unitTypes, enemyUnitTypes); if (targets.isEmpty()) { continue; } final Optional<TargetGroup> targetGroup = findTargetsInTargetGroups(targets, targetGroups); if (targetGroup.isPresent()) { targetGroup.get().getFiringUnitTypes().add(unitType); } else { targetGroups.add(new TargetGroup(unitType, targets)); } } return sortTargetGroups(targetGroups); }
Source:
public Map<String, AnalysisProvider<TokenFilterFactory>> getTokenFilters() { Map<String, AnalysisProvider<TokenFilterFactory>> map = new HashMap<>(); map.put("serbian_stemmer", SerbianStemmerTokenFilterFactory::new); return Collections.unmodifiableMap(map); }

Target:
public Map<String, AnalysisProvider<TokenFilterFactory>> getTokenFilters() { return Collections.singletonMap("serbian_stemmer", SerbianStemmerTokenFilterFactory::new); }
Source:
public QuotaBalanceResponse createQuotaLastBalanceResponse(List<QuotaBalanceVO> quotaBalance, Date startDate) { if (quotaBalance == null || quotaBalance.size() == 0) { throw new InvalidParameterValueException("There are no balance entries on or before the requested date."); } if (startDate == null) { startDate = new Date(); } QuotaBalanceResponse resp = new QuotaBalanceResponse(); BigDecimal lastCredits = new BigDecimal(0); for (QuotaBalanceVO entry : quotaBalance) { if (s_logger.isDebugEnabled()) { s_logger.info("createQuotaLastBalanceResponse Date=" + entry.getUpdatedOn() + " balance=" + entry.getCreditBalance() + " credit=" + entry.getCreditsId()); } lastCredits = lastCredits.add(entry.getCreditBalance()); } resp.setStartQuota(lastCredits); resp.setStartDate(_quotaService.computeAdjustedTime(startDate)); resp.setCurrency(QuotaConfig.QuotaCurrencySymbol.value()); resp.setObjectName("balance"); return resp; }

Target:
public QuotaBalanceResponse createQuotaLastBalanceResponse(List<QuotaBalanceVO> quotaBalance, Date startDate) { if (quotaBalance == null) { throw new InvalidParameterValueException("There are no balance entries on or before the requested date."); } if (startDate == null) { startDate = new Date(); } QuotaBalanceResponse resp = new QuotaBalanceResponse(); BigDecimal lastCredits = new BigDecimal(0); for (QuotaBalanceVO entry : quotaBalance) { if (s_logger.isDebugEnabled()) { s_logger.debug("createQuotaLastBalanceResponse Date=" + entry.getUpdatedOn() + " balance=" + entry.getCreditBalance() + " credit=" + entry.getCreditsId()); } lastCredits = lastCredits.add(entry.getCreditBalance()); } resp.setStartQuota(lastCredits); resp.setStartDate(_quotaService.computeAdjustedTime(startDate)); resp.setCurrency(QuotaConfig.QuotaCurrencySymbol.value()); resp.setObjectName("balance"); return resp; }
Source:
private String getLocal(final Server server, final User user, final long radius) { final Location loc = user.getLocation(); final World world = loc.getWorld(); final StringBuilder output = new StringBuilder(); final long radiusSquared = radius * radius; boolean showHidden = user.canInteractVanished(); Queue<User> nearbyPlayers = new PriorityQueue<>((o1, o2) -> (int) (o1.getLocation().distanceSquared(loc) - o2.getLocation().distanceSquared(loc))); for (User player : ess.getOnlineUsers()) { if (!player.equals(user) && (!player.isHidden(user.getBase()) || showHidden || user.getBase().canSee(player.getBase()))) { final Location playerLoc = player.getLocation(); if (playerLoc.getWorld() != world) { continue; } final long delta = (long) playerLoc.distanceSquared(loc); if (delta < radiusSquared) { nearbyPlayers.offer(player); } } } while (!nearbyPlayers.isEmpty()) { if (output.length() > 0) { output.append(", "); } User nearbyPlayer = nearbyPlayers.poll(); output.append(nearbyPlayer.getDisplayName()).append("§f(§4").append((long) Math.sqrt(nearbyPlayer.getLocation().distanceSquared(loc))).append("m§f)"); } return output.length() > 1 ? output.toString() : tl("none"); }

Target:
private String getLocal(final Server server, final User user, final long radius) { final Location loc = user.getLocation(); final World world = loc.getWorld(); final StringBuilder output = new StringBuilder(); final long radiusSquared = radius * radius; boolean showHidden = user.canInteractVanished(); Queue<User> nearbyPlayers = new PriorityQueue<>((o1, o2) -> (int) (o1.getLocation().distanceSquared(loc) - o2.getLocation().distanceSquared(loc))); for (User player : ess.getOnlineUsers()) { if (!player.equals(user) && (!player.isHidden(user.getBase()) || showHidden || user.getBase().canSee(player.getBase()))) { final Location playerLoc = player.getLocation(); if (playerLoc.getWorld() != world) { continue; } final long delta = (long) playerLoc.distanceSquared(loc); if (delta < radiusSquared) { nearbyPlayers.offer(player); } } } while (!nearbyPlayers.isEmpty()) { if (output.length() > 0) { output.append(", "); } User nearbyPlayer = nearbyPlayers.poll(); output.append(nearbyPlayer.getDisplayName()).append("§f(§4").append((long) nearbyPlayer.getLocation().distance(loc)).append("m§f)"); } return output.length() > 1 ? output.toString() : tl("none"); }
Source:
public void itDoesntWritePassword() throws Exception { JsonNode node = getResponseAsJson(RequestType.GET, "/user/user1"); assertNull("", node.get("properties").get("password")); }

Target:
public void itDoesntWritePassword() throws Exception { JsonNode node = getResponseAsJson(RequestType.GET, "/user/user1"); assertNull(node.get("properties").get("password")); }
Source:
public Void visit(File f) { try { ContentUtils.writeToFile(f, dest, progress, worker, source); } catch (IOException ex) { logger.log(Level.WARNING, "Trouble extracting file to " + dest.getAbsolutePath(), ex); } return null; }

Target:
public Void visit(File f) { try { ContentUtils.writeToFile(f, dest, progress, worker, source); } catch (ReadContentInputStreamException ex) { logger.log(Level.WARNING, "Trouble extracting file to " + dest.getAbsolutePath(), ex); } catch (IOException ex) { logger.log(Level.SEVERE, "Trouble extracting file to " + dest.getAbsolutePath(), ex); } return null; }
Source:
public void getSourceFile(OutputStream output, IResourceRegistry registry, String urlToSource, boolean offline) { String templateName = offline ? "offlineSourceFileTemplate.html" : "sourceFileTemplate.html"; ResourceToken template = new ClassBasedResourceToken(templateName, getClass()); Writer writer = null; try { writer = new OutputStreamWriter(output); Client client = Client.create(); WebResource service = client.resource(urlToSource); PageFactory.realizePage(registry, template, writer, "fileContents", service.get(String.class)); } finally { Lib.close(writer); } }

Target:
public void getSourceFile(OutputStream output, IResourceRegistry registry, String urlToSource, boolean offline) { ResourceToken template = offline ? SOURCE_OFFLINE : SOURCE; Writer writer = null; try { writer = new OutputStreamWriter(output); Client client = Client.create(); WebResource service = client.resource(urlToSource); PageFactory.realizePage(registry, template, writer, "fileContents", service.get(String.class)); } finally { Lib.close(writer); } }
Source:
public int onStartCommand(Intent intent, int flags, int startId) { googleApiClient = new GoogleApiClient.Builder(this) .addApi(Nearby.MESSAGES_API) .addConnectionCallbacks(connectionCallbacks) .addOnConnectionFailedListener(onConnectionFailedListener) .build(); googleApiClient.connect(); return Service.START_NOT_STICKY; }

Target:
public int onStartCommand(Intent intent, int flags, int startId) { googleApiClient.connect(); return Service.START_NOT_STICKY; }
Source:
@Override public void attach(Linker linker) { for (Element enclosedElement : enclosingClass.getEnclosedElements()) { if (enclosedElement.getKind().isField()) { Inject injectAnnotation = enclosedElement.getAnnotation(Inject.class); if (injectAnnotation != null) { String key = GeneratorKeys.get(enclosedElement.asType()); System.out.println("enclosedElementKey = " + key); linker.requestBinding(key, enclosingClass.toString()); } } } }

Target:
@Override public void attach(Linker linker) { for (Element enclosedElement : enclosingClass.getEnclosedElements()) { if (enclosedElement.getKind().isField() && CodeGen.isStatic(enclosedElement)) { Inject injectAnnotation = enclosedElement.getAnnotation(Inject.class); if (injectAnnotation != null) { String key = GeneratorKeys.get(enclosedElement.asType()); linker.requestBinding(key, enclosingClass.toString()); } } } }
Source:
private boolean cannotAdd(T element) { return type != obj() && ((element == null) || (type.type() != asPrimitive(element.getClass()))); }

Target:
private boolean cannotAdd(T element) { return (type != obj()) && (type.type() != primitiveType(element)); }
Source:
protected void recvCommands() throws IOException { PushCertificateParser certParser = getPushCertificateParser(); FirstLine firstLine = null; try { for (;;) { String line; try { rawLine = pckIn.readString(); } catch (EOFException eof) { if (commands.isEmpty()) return; throw eof; } if (rawLine == PacketLineIn.END) { break; } if (line.length() >= 48 && line.startsWith("shallow ")) { clientShallowCommits.add(ObjectId.fromString(line.substring(8, 48))); continue; } if (firstLine == null) { firstLine = new FirstLine(line); enabledCapabilities = firstLine.getCapabilities(); line = firstLine.getLine(); if (line.equals(GitProtocolConstants.OPTION_PUSH_CERT)) { certParser.receiveHeader(pckIn, !isBiDirectionalPipe()); continue; } } if (line.equals(PushCertificateParser.BEGIN_SIGNATURE)) { certParser.receiveSignature(pckIn); continue; } ReceiveCommand cmd = parseCommand(line); if (cmd.getRefName().equals(Constants.HEAD)) { cmd.setResult(Result.REJECTED_CURRENT_BRANCH); } else { cmd.setRef(refs.get(cmd.getRefName())); } commands.add(cmd); if (certParser.enabled()) { certParser.addCommand(cmd); } } } catch (PackProtocolException e) { sendError(e.getMessage()); throw e; } }

Target:
protected void recvCommands() throws IOException { PushCertificateParser certParser = getPushCertificateParser(); FirstLine firstLine = null; try { for (;;) { String line; try { line = pckIn.readString(); } catch (EOFException eof) { if (commands.isEmpty()) return; throw eof; } if (line == PacketLineIn.END) { break; } if (line.length() >= 48 && line.startsWith("shallow ")) { clientShallowCommits.add(ObjectId.fromString(line.substring(8, 48))); continue; } if (firstLine == null) { firstLine = new FirstLine(line); enabledCapabilities = firstLine.getCapabilities(); line = firstLine.getLine(); if (line.equals(GitProtocolConstants.OPTION_PUSH_CERT)) { certParser.receiveHeader(pckIn, !isBiDirectionalPipe()); continue; } } if (line.equals(PushCertificateParser.BEGIN_SIGNATURE)) { certParser.receiveSignature(pckIn); continue; } ReceiveCommand cmd; try { cmd = parseCommand(line); } catch (PackProtocolException e) { sendError(e.getMessage()); throw e; } if (cmd.getRefName().equals(Constants.HEAD)) { cmd.setResult(Result.REJECTED_CURRENT_BRANCH); } else { cmd.setRef(refs.get(cmd.getRefName())); } commands.add(cmd); if (certParser.enabled()) { certParser.addCommand(cmd); } } } catch (PackProtocolException e) { sendError(e.getMessage()); throw e; } }
Source:
protected void tearDown() throws Exception { Job.getJobManager().cancel(BuildTestProject.class); IProject testProject = getTestProject(); if (testProject.exists()) { testProject.delete(true, null); } setWorkspaceAutoBuild(wasAutoBuildOn); logListener.clear(); Platform.removeLogListener(logListener); super.tearDown(); }

Target:
protected void tearDown() throws Exception { Job.getJobManager().cancel(BuildTestProject.class); Platform.removeLogListener(logListener); logListener.clear(); try { IProject testProject = getTestProject(); if (testProject.exists()) { testProject.delete(true, null); } } finally { setWorkspaceAutoBuild(wasAutoBuildOn); } super.tearDown(); }
Source:
public void removeServoEventListener(NameProvider service) { isEventsEnabled = false; removeListener("publishServoEvent", service.getName(), "onServoEvent"); }

Target:
public void removeServoEventListener(NameProvider service) { isEventsEnabled = false; unsubscribe(getName(), "publishServoEvent"); }
Source:
public static void configurePushURI(RemoteConfig remoteConfig, URIish pushURI) throws URISyntaxException { List<URIish> pushURIs = new ArrayList<URIish>( remoteConfig.getPushURIs()); for (URIish urIish : pushURIs) { remoteConfig.removePushURI(urIish); } remoteConfig.addPushURI(pushURI); }

Target:
public static void configurePushURI(RemoteConfig remoteConfig, URIish pushURI) { List<URIish> pushURIs = new ArrayList<URIish>( remoteConfig.getPushURIs()); for (URIish urIish : pushURIs) { remoteConfig.removePushURI(urIish); } remoteConfig.addPushURI(pushURI); }
Source:
public static String[] listBaudRates() { return new String[] {"115200", "57600", "38400", "31250", "28800", "19200", "14400", "9600", "4800", "2400", "1200", "300"}; }

Target:
public static String[] listBaudRates() { String outgoing[] = { "115200", "57600", "38400", "31250", "28800", "19200", "14400", "9600", "4800", "2400", "1200", "300" }; return outgoing; }
Source:
public void boardNew(boolean showDialog) { boolean userCancel = false; if (showDialog) { RandomMapDialog rmd = new RandomMapDialog(frame, this, null, mapSettings); userCancel = rmd.activateDialog(bv.getTilesetManager().getThemes()); } if (!userCancel) { board = BoardUtilities.generateRandom(mapSettings); game.setBoard(board); curfile = null; butSourceFile.setEnabled(false); frame.setTitle(Messages.getString("BoardEditor.title")); menuBar.setBoard(true); bvc.doLayout(); resetUndo(); choTheme.setSelectedItem(mapSettings.getTheme()); } }

Target:
public void boardNew(boolean showDialog) { boolean userCancel = false; if (showDialog) { RandomMapDialog rmd = new RandomMapDialog(frame, this, null, mapSettings); userCancel = rmd.activateDialog(bv.getTilesetManager().getThemes()); } if (!userCancel) { board = BoardUtilities.generateRandom(mapSettings); game.setBoard(board); curfile = null; choTheme.setSelectedItem(mapSettings.getTheme()); setupUiFreshBoard(); } }
Source:
private static Requirement createAvroTable(String schemaPath, String tableName, String topicName, ImmutableMap<String, Object> record) { try { Schema schema = new Schema.Parser().parse(new File(schemaPath)); byte[] avroData = convertRecordToAvro(schema, record); return immutableTable(new KafkaTableDefinition( tableName, topicName, new ListKafkaDataSource(ImmutableList.of( new KafkaMessage( contentsBuilder() .appendBytes(avroData) .build()))), 1, 1)); } catch (IOException e) { throw new RuntimeException(e); } }

Target:
private static Requirement createAvroTable(String schemaPath, String tableName, String topicName, ImmutableMap<String, Object> record) { try { Schema schema = new Schema.Parser().parse(new File(schemaPath)); byte[] avroData = convertRecordToAvro(schema, record); return immutableTable(new KafkaTableDefinition( tableName, topicName, new ListKafkaDataSource(ImmutableList.of( new KafkaMessage( contentsBuilder() .appendBytes(avroData) .build()))), 1, 1)); } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
static Severity getSeverity(String severityName) { switch (severityName) { case "BLOCKER": case "CRITICAL": case "MAJOR": return Severity.ERROR; case "MINOR": return Severity.WARNING; case "INFO": return Severity.INFO; } log.warn("Unknown severity: " + severityName); return Severity.WARNING; }

Target:
static Severity getSeverity(String severityName) { switch (severityName) { case "BLOCKER": case "CRITICAL": case "MAJOR": return Severity.ERROR; case "MINOR": return Severity.WARNING; case "INFO": return Severity.INFO; default: log.warn("Unknown severity: " + severityName); } return Severity.WARNING; }
Source:
public void testDivisibleByMiniBatchSize() { final Random generator = new Random(); final int numTotalInstances = MINI_BATCH_SIZE * 5; for (int i = 0; i < numTotalInstances; i++) { final int value = generator.nextInt(); values.put(i, value); } trainingDataProvider.prepareDataForEpoch(); assertTrue(numTotalInstances % MINI_BATCH_SIZE == 0); final int numTotalMiniBatches = (int) Math.ceil((double) numTotalInstances / MINI_BATCH_SIZE); final int numInstances = numTotalInstances / MINI_BATCH_SIZE; int numMiniBatchCount = 0; Map<Integer, Integer> trainingData = trainingDataProvider.getNextTrainingData(); while (!trainingData.isEmpty()) { numMiniBatchCount++; for (final Integer key : trainingData.keySet()) { assertEquals("The training data for a key should be same", values.get(key), trainingData.get(key)); } assertEquals("TrainingDataProvider did not give the expected number of instances", numInstances, trainingData.size()); trainingData = trainingDataProvider.getNextTrainingData(); } assertEquals("The total number of mini-batch is different from expectation", numTotalMiniBatches, numMiniBatchCount); }

Target:
public void testDivisibleByMiniBatchSize() { final int numTotalInstances = MINI_BATCH_SIZE * 5; createMockTrainingData(numTotalInstances); trainingDataProvider.prepareDataForEpoch(); testGetNextTrainingData(numTotalInstances); assertTrue("Data should be exhausted", trainingDataProvider.getNextTrainingData().isEmpty()); trainingDataProvider.prepareDataForEpoch(); testGetNextTrainingData(numTotalInstances); assertTrue("Data should be exhausted", trainingDataProvider.getNextTrainingData().isEmpty()); }
Source:
public void assertXmlApiWithXPathNavigationMatchesExpected() { try { FreeStyleProject project = createJobWithWorkspaceFile("checkstyleregextest.xml"); enableWarningsWithCheckstyle(project); String buildNumber = String.valueOf(project.getNextBuildNumber()); scheduleBuild(project); XmlPage page = j.createWebClient() .goToXml(project.getUrl() + buildNumber + "/checkstyleResult/api/xml?xpath=/*/overallResult"); Document test = page.getXmlDocument(); assertThat(test.getDocumentElement().getTagName()).isEqualTo("overallResult"); } catch (IOException | SAXException e) { e.printStackTrace(); } }

Target:
public void assertXmlApiWithXPathNavigationMatchesExpected() { FreeStyleProject project = createJobWithWorkspaceFile("checkstyleregextest.xml"); enableWarningsWithCheckstyle(project); String buildNumber = String.valueOf(buildProjectAndReturnBuildNo(project)); XmlPage page = getXmlPage(project, buildNumber, "/checkstyleResult/api/xml?xpath=/*/overallResult"); Document test = page.getXmlDocument(); assertThat(test.getDocumentElement().getTagName()).isEqualTo("overallResult"); assertThat(test.getDocumentElement().getFirstChild().getNodeValue()).isEqualTo("SUCCESS"); }
Source:
private BarcodeInventoryErrorDetail getErrorDetail(String netid, String assetTag, String condition, String buildingCode, String roomNumber) { BarcodeInventoryErrorDetail barcodeInventoryErrorDetail = new BarcodeInventoryErrorDetail(); barcodeInventoryErrorDetail.setUploadRowNumber(1L); barcodeInventoryErrorDetail.setCampusCode("IT"); barcodeInventoryErrorDetail.setAssetTagNumber(assetTag); barcodeInventoryErrorDetail.setUploadScanIndicator(true); barcodeInventoryErrorDetail.setUploadScanTimestamp(getDateTimeService().getCurrentTimestamp()); barcodeInventoryErrorDetail.setBuildingCode(buildingCode); barcodeInventoryErrorDetail.setBuildingRoomNumber(roomNumber); barcodeInventoryErrorDetail.setAssetConditionCode(condition); barcodeInventoryErrorDetail.setErrorCorrectionStatusCode(CamsConstants.BarCodeInventoryError.STATUS_CODE_ERROR); barcodeInventoryErrorDetail.setCorrectorUniversalIdentifier(netid); return barcodeInventoryErrorDetail; }

Target:
private BarcodeInventoryErrorDetail getErrorDetail(String netid, String assetTag, String condition, String buildingCode, String roomNumber) { BarcodeInventoryErrorDetail barcodeInventoryErrorDetail = new BarcodeInventoryErrorDetail(); barcodeInventoryErrorDetail.setUploadRowNumber(CuCamsConstants.CapAssetApi.UPLOAD_ROW_NUMBER); barcodeInventoryErrorDetail.setCampusCode(CuCamsConstants.CapAssetApi.CAMPUS_CODE_VALUE); barcodeInventoryErrorDetail.setAssetTagNumber(assetTag); barcodeInventoryErrorDetail.setUploadScanIndicator(true); barcodeInventoryErrorDetail.setUploadScanTimestamp(getDateTimeService().getCurrentTimestamp()); barcodeInventoryErrorDetail.setBuildingCode(buildingCode); barcodeInventoryErrorDetail.setBuildingRoomNumber(roomNumber); barcodeInventoryErrorDetail.setAssetConditionCode(condition); barcodeInventoryErrorDetail.setErrorCorrectionStatusCode(CamsConstants.BarCodeInventoryError.STATUS_CODE_ERROR); barcodeInventoryErrorDetail.setCorrectorUniversalIdentifier(netid); barcodeInventoryErrorDetail.setErrorDescription("Asset Tag Not Found"); return barcodeInventoryErrorDetail; }
Source:
protected SerialPort next(final SerialPort serialPort, final Observer<? super BluetoothValue> observer) { try { try (final InputStream inputStream = serialPort.getInputStream(); final Scanner scanner = new Scanner(inputStream) ) { if (scanner.hasNext()) { final String next = scanner.nextLine(); if (next != "") { observer.onNext(new BluetoothValue(scanner.nextLine())); } } } } catch (final IOException e) { observer.onError(e); } return serialPort; }

Target:
protected SerialPort next(final SerialPort serialPort, final Observer<? super BluetoothValue> observer) { try { final InputStream inputStream = serialPort.getInputStream(); try (final Scanner scanner = new Scanner(inputStream)) { if (scanner.hasNext()) { final String next = scanner.nextLine(); if (!next.isEmpty()) { observer.onNext(new BluetoothValue(next)); } } } } catch (final IOException e) { observer.onError(e); } return serialPort; }
Source:
public FormValidation doValidate(@QueryParameter String userName, @QueryParameter String url, @QueryParameter String password, @QueryParameter String groupVisibility, @QueryParameter String roleVisibility, @QueryParameter boolean useHTTPAuth, @QueryParameter String alternativeUrl, @QueryParameter Integer timeout) throws IOException { url = Util.fixEmpty(url); alternativeUrl = Util.fixEmpty(alternativeUrl); URL mainURL, alternativeURL = null; try{ if (url == null) { return FormValidation.error("No URL given"); } mainURL = new URL(url); } catch (MalformedURLException e){ return FormValidation.error(String.format("Malformed URL (%s)", url), e ); } try { if (alternativeUrl != null) { alternativeURL = new URL(alternativeUrl); } }catch (MalformedURLException e){ return FormValidation.error(String.format("Malformed alternative URL (%s)",alternativeUrl), e ); } JiraSite site = new JiraSite(mainURL, alternativeURL, userName, password, false, false, null, false, groupVisibility, roleVisibility, useHTTPAuth); site.setTimeout(timeout); try { JiraSession session = site.createSession(); if (session == null) { return FormValidation.error("Failed to login to JIRA"); } session.getMyPermissions(); return FormValidation.ok("Success"); } catch (RestClientException e) { LOGGER.log(Level.WARNING, "Failed to login to JIRA at " + url, e); } return FormValidation.error("Failed to login to JIRA"); }

Target:
public FormValidation doValidate(@QueryParameter String userName, @QueryParameter String url, @QueryParameter String password, @QueryParameter String groupVisibility, @QueryParameter String roleVisibility, @QueryParameter boolean useHTTPAuth, @QueryParameter String alternativeUrl, @QueryParameter Integer timeout) throws IOException { url = Util.fixEmpty(url); alternativeUrl = Util.fixEmpty(alternativeUrl); URL mainURL, alternativeURL = null; try{ if (url == null) { return FormValidation.error("No URL given"); } mainURL = new URL(url); } catch (MalformedURLException e){ return FormValidation.error(String.format("Malformed URL (%s)", url), e ); } try { if (alternativeUrl != null) { alternativeURL = new URL(alternativeUrl); } }catch (MalformedURLException e){ return FormValidation.error(String.format("Malformed alternative URL (%s)",alternativeUrl), e ); } JiraSite site = new JiraSite(mainURL, alternativeURL, userName, password, false, false, null, false, groupVisibility, roleVisibility, useHTTPAuth); site.setTimeout(timeout); try { JiraSession session = site.createSession(); session.getMyPermissions(); return FormValidation.ok("Success"); } catch (RestClientException e) { LOGGER.log(Level.WARNING, "Failed to login to JIRA at " + url, e); } return FormValidation.error("Failed to login to JIRA"); }
Source:
public void whenCreateEventTypeWithWrongPartitionKeyFieldsThen422() throws Exception { final EventType eventType = buildEventType(randomValidEventTypeName(), new JSONObject("{ \"price\": 1000 }"), Collections.singletonList("blabla")); Mockito.doReturn(eventType).when(eventTypeRepository).findByName(eventType.getName()); Mockito.doThrow(new TopicDeletionException("dummy message", null)).when(topicRepository).deleteTopic( eventType.getTopic()); postEventType(eventType).andExpect(status().isUnprocessableEntity()) .andExpect(content().contentType("application/problem+json")); }

Target:
public void whenCreateEventTypeWithWrongPartitionKeyFieldsThen422() throws Exception { final EventType eventType = buildEventType(randomValidEventTypeName(), new JSONObject("{ \"price\": 1000 }"), Collections.singletonList("blabla")); Mockito.doReturn(eventType).when(eventTypeRepository).findByName(eventType.getName()); postEventType(eventType).andExpect(status().isUnprocessableEntity()) .andExpect(content().contentType("application/problem+json")); }
Source:
private Iterable<S3ObjectSummary> getIterableObjectsFromPrefixes() { return () -> S3Utils.objectSummaryIterator(s3Client, getPrefixes(), segmentPusherConfig.getMaxListingLength()); }

Target:
private Iterable<S3ObjectSummary> getIterableObjectsFromPrefixes() { return () -> S3Utils.objectSummaryIterator(s3Client, getPrefixes(), inputDataConfig.getMaxListingLength()); }
Source:
public boolean hasProjects() { Set<String> proj = getProjects().keySet(); return (proj != null && !proj.isEmpty()); }

Target:
public boolean hasProjects() { return (getProjects().size() > 0); }
Source:
public Boolean getDevelopment() { return (Boolean) this.get("development"); }

Target:
public boolean getDevelopment() { return (Boolean) this.get("development"); }
Source:
public <K, V> CacheEventDispatcher<K, V> createCacheEventDispatcher(Store<K, V> store, ServiceConfiguration<?>... serviceConfigs) { String threadPoolAlias = defaultThreadPoolAlias; DefaultCacheEventDispatcherConfiguration config = findSingletonAmongst(DefaultCacheEventDispatcherConfiguration.class, serviceConfigs); if (config != null) { threadPoolAlias = config.getThreadPoolAlias(); } ExecutorService orderedExecutor = executionService.getOrderedExecutor(threadPoolAlias, new LinkedBlockingQueue<>()); ExecutorService unOrderedExecutor = executionService.getUnorderedExecutor(threadPoolAlias, new LinkedBlockingQueue<>()); return new CacheEventDispatcherImpl<>(unOrderedExecutor, orderedExecutor); }

Target:
public <K, V> CacheEventDispatcher<K, V> createCacheEventDispatcher(Store<K, V> store, ServiceConfiguration<?>... serviceConfigs) { String threadPoolAlias = defaultThreadPoolAlias; DefaultCacheEventDispatcherConfiguration config = findSingletonAmongst(DefaultCacheEventDispatcherConfiguration.class, (Object[]) serviceConfigs); if (config != null) { threadPoolAlias = config.getThreadPoolAlias(); } ExecutorService orderedExecutor = executionService.getOrderedExecutor(threadPoolAlias, new LinkedBlockingQueue<>()); ExecutorService unOrderedExecutor = executionService.getUnorderedExecutor(threadPoolAlias, new LinkedBlockingQueue<>()); return new CacheEventDispatcherImpl<>(unOrderedExecutor, orderedExecutor); }
Source:
public LicensedVideoSwapPageObject navigateToLvsPage() { backToLvsBtn.click(); PageObjectLogging.log("navigateToLvsPage", "verify that the lvs back button navigates to lvs page", true); return new LicensedVideoSwapPageObject(driver); }

Target:
public LicensedVideoSwapPageObject navigateToLvsPage() { waitForElementByElement(backToLvsBtn); backToLvsBtn.click(); PageObjectLogging.log("navigateToLvsPage", "lvs back button navigates to lvs page", true); return new LicensedVideoSwapPageObject(driver); }
Source:
private ItemGroup getItemGroup(Run<?, ?> build) { if (build instanceof AbstractBuild) { return ((AbstractBuild) build).getProject().getRootProject().getParent(); } else { return build.getParent().getParent(); } }

Target:
private ItemGroup getItemGroup(Run<?, ?> build) { return getRootProject(build.getParent()).getParent(); }
Source:
public void updateInitialRunFields() { if (vm.getCompatibilityVersion() != null) { AsyncDataProvider.isFloppySupported(new AsyncQuery<>(isFloppySupported -> { getIsSysprepPossible().setEntity(isFloppySupported && getIsWindowsOS()); getIsSysprepEnabled().setEntity(isFloppySupported && getInitializationType() == InitializationType.Sysprep); getIsCloudInitPossible().setEntity(!getIsWindowsOS()); getIsCloudInitEnabled().setEntity(getInitializationType() == InitializationType.CloudInit); getIsCloudInitEnabled().setIsAvailable(!getIsWindowsOS()); if (getIsSysprepPossible().getEntity() && getIsSysprepEnabled().getEntity()) { getVmInitModel().updateSysprepDomain(getVmInitModel().getSysprepDomain().getSelectedItem()); } }), vm.getOs(), vm.getCompatibilityVersion()); } }

Target:
public void updateInitialRunFields() { getIsSysprepPossible().setEntity(getIsWindowsOS()); getIsSysprepEnabled().setEntity(getInitializationType() == InitializationType.Sysprep); getIsCloudInitPossible().setEntity(!getIsWindowsOS()); getIsCloudInitEnabled().setEntity(getInitializationType() == InitializationType.CloudInit); getIsCloudInitEnabled().setIsAvailable(!getIsWindowsOS()); if (getIsSysprepPossible().getEntity() && getIsSysprepEnabled().getEntity()) { getVmInitModel().updateSysprepDomain(getVmInitModel().getSysprepDomain().getSelectedItem()); } }
Source:
public void testPiano() { solo.assertCurrentActivity("correct activity",SplashScreen.class); solo.waitForActivity("PianoActivity",3000); }

Target:
public void testPiano() { int MaximumTimeout = 300; solo.assertCurrentActivity("correct activity",SplashScreen.class); solo.waitForActivity("PianoActivity",MaximumTimeout); }
Source:
public HashSet<Project> getProjects() { return threadConfig.get().getProjects(); }

Target:
public Map<String,Project> getProjects() { return threadConfig.get().getProjects(); }
Source:
public ZooKeeperServiceRegistry(ZooKeeperConnection connection) { checkNotNull(connection); CuratorFramework curator = ((CuratorConnection) connection).getCurator(); checkNotNull(curator); checkArgument(curator.isStarted()); _zooKeeperConnection = connection; }

Target:
public ZooKeeperServiceRegistry(ZooKeeperConnection connection) { checkNotNull(connection); _zooKeeperConnection = connection; }
Source:
public void before() throws IOException { logMock = mock(Log.class); handler = new DefaultArtifactHandler(TYPE); List<ArtifactRepository> remoteArtifactRepositories = new ArrayList<>(); aetherRepositorySystemMock = mock(RepositorySystem.class); aetherRepositorySystemSessionMock = mock(RepositorySystemSession.class); installer = new ArtifactInstaller(logMock, remoteArtifactRepositories, aetherRepositorySystemMock, aetherRepositorySystemSessionMock); outputFolder = new TemporaryFolder(); outputFolder.create(); artifactFileFolder = new TemporaryFolder(); artifactFileFolder.create(); artifact = new DefaultArtifact(GROUP_ID, ARTIFACT_ID, VERSION, SCOPE, TYPE, CLASSIFIER, handler); }

Target:
public void before() throws IOException { logMock = mock(Log.class); handler = new DefaultArtifactHandler(TYPE); List<ArtifactRepository> remoteArtifactRepositories = new ArrayList<>(); aetherRepositorySystemMock = mock(RepositorySystem.class); aetherRepositorySystemSessionMock = mock(RepositorySystemSession.class); installer = new ArtifactInstaller(logMock, remoteArtifactRepositories, aetherRepositorySystemMock, aetherRepositorySystemSessionMock); outputFolder.create(); artifactFileFolder.create(); artifact = new DefaultArtifact(GROUP_ID, ARTIFACT_ID, VERSION, SCOPE, TYPE, CLASSIFIER, handler); }
Source:
public void testTransformSourceResponse() throws CatalogTransformerException, IOException { RtfQueryResponseAndMetacardTransformer transformer = createTransformer(); assertThat("Transformer cannot be null", transformer, notNullValue()); SourceResponse mockSourceResponse = mock(SourceResponse.class); List<Result> results = createMockResults(); when(mockSourceResponse.getResults()).thenReturn(results); when(mockSourceResponse.getResults()).thenReturn(results); BinaryContent content = transformer.transform(mockSourceResponse, new HashMap<>()); assertThat("Transformed content cannot be null", content, notNullValue()); assertThat( "Content mime type must be 'application/rtf'", content.getMimeType().toString(), equalTo("application/rtf")); assertThat("Content must not be empty", content.getByteArray().length, greaterThan(0)); }

Target:
public void testTransformSourceResponse() throws CatalogTransformerException, IOException, MimeTypeParseException { RtfQueryResponseAndMetacardTransformer transformer = createTransformer(); SourceResponse mockSourceResponse = mock(SourceResponse.class); List<Result> results = createMockResults(); when(mockSourceResponse.getResults()).thenReturn(results); BinaryContent content = transformer.transform(mockSourceResponse, Collections.emptyMap()); assertThat("Transformed content cannot be null", content, notNullValue()); assertThat( "Content mime type must be 'application/rtf'", content.getMimeType().toString(), equalTo("application/rtf")); String rtfResult = inputStreamToString(content.getInputStream()); assertThat("Content must not be empty", rtfResult, is(not(isEmptyOrNullString()))); String referenceRtf = getReferenceSourceResponseRtfFile(); assertThat("Produced RTF document must match reference", rtfResult, equalTo(referenceRtf)); }
Source:
public boolean supportsBitmapIndex(final BitmapIndexSelector selector) { return requiredBindings.isEmpty() || (requiredBindings.size() == 1 && selector.getBitmapIndex(Iterables.getOnlyElement(requiredBindings)) != null && !selector.hasMultipleValues(Iterables.getOnlyElement(requiredBindings))); }

Target:
public boolean supportsBitmapIndex(final BitmapIndexSelector selector) { if (requiredBindings.isEmpty()) { return true; } else if (requiredBindings.size() == 1) { final String column = Iterables.getOnlyElement(requiredBindings); return selector.getBitmapIndex(column) != null && !selector.hasMultipleValues(column); } else { return false; } }