auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected CascadingTypeParameter getCascadingMetaData() { Map<TypeVariable<?>, CascadingTypeParameter> typeParametersCascadingMetaData = new HashMap<>(); for ( ContainerElementConstraintMappingContextImpl typeArgumentContext : containerElementContexts.values() ) { CascadingTypeParameter cascadingTypeParameter = typeArgumentContext.getCascadingTypeParameter(); if ( cascadingTypeParameter != null ) { typeParametersCascadingMetaData.put( cascadingTypeParameter.getTypeParameter(), cascadingTypeParameter ); } } boolean isArray = TypeHelper.isArray( configuredType ); CascadingTypeParameter cascadingMetaData = isArray ? CascadingTypeParameter.arrayElement( configuredType, isCascading, typeParametersCascadingMetaData, groupConversions ) : CascadingTypeParameter.annotatedObject( configuredType, isCascading, typeParametersCascadingMetaData, groupConversions ); return cascadingMetaData; }

Target:
protected CascadingTypeParameter getCascadingMetaData() { Map<TypeVariable<?>, CascadingTypeParameter> typeParametersCascadingMetaData = containerElementContexts.values().stream() .filter( c -> c.getCascadingTypeParameter() != null ) .collect( Collectors.toMap( c -> c.getCascadingTypeParameter().getTypeParameter(), c -> c.getCascadingTypeParameter() ) ); for ( ContainerElementConstraintMappingContextImpl typeArgumentContext : containerElementContexts.values() ) { CascadingTypeParameter cascadingTypeParameter = typeArgumentContext.getCascadingTypeParameter(); if ( cascadingTypeParameter != null ) { typeParametersCascadingMetaData.put( cascadingTypeParameter.getTypeParameter(), cascadingTypeParameter ); } } boolean isArray = TypeHelper.isArray( configuredType ); CascadingTypeParameter cascadingMetaData = isArray ? CascadingTypeParameter.arrayElement( configuredType, isCascading, typeParametersCascadingMetaData, groupConversions ) : CascadingTypeParameter.annotatedObject( configuredType, isCascading, typeParametersCascadingMetaData, groupConversions ); return cascadingMetaData; }
Source:
public void putAndPersistAdditionalInformation(String key, String value) { String valueToUpdate = this.additionalInformation.get(key); if (valueToUpdate == null || (valueToUpdate != null && !valueToUpdate.equals(value))) { this.additionalInformation.put(key, value); this.descriptor.getAdditionalInformation().put(key, value); this.monitoring.nodeSourceEvent(new RMNodeSourceEvent(RMEventType.NODESOURCE_UPDATED, this.administrator.getName(), this.name, this.getDescription(), this.additionalInformation, this.administrator.getName(), this.getStatus().toString())); persistAdditionalInformation(); } }

Target:
public void putAndPersistAdditionalInformation(String key, String value) { String valueToUpdate = this.additionalInformation.get(key); if (valueToUpdate == null || (valueToUpdate != null && !valueToUpdate.equals(value))) { this.additionalInformation.put(key, value); this.descriptor.getAdditionalInformation().put(key, value); persistAdditionalInformation(); this.monitoring.nodeSourceEvent(new RMNodeSourceEvent(RMEventType.NODESOURCE_UPDATED, this.administrator.getName(), this.name, this.getDescription(), this.additionalInformation, this.administrator.getName(), this.getStatus().toString())); } }
Source:
public String getStringValue() { return null; }

Target:
public String getStringValue() { throw createUnsupportedOperationException(); }
Source:
public void visitNode(AstNode node) { if (isUsingDjangoModel) { AstNode attributeRef = node.getFirstChild(PythonGrammar.ATTRIBUTE_REF); if (attributeRef != null) { String functionName = attributeRef.getLastChild(PythonGrammar.NAME).getTokenValue(); if (functionName.equals("raw") || functionName.equals("extra")) { addIssue(node, MESSAGE); } } } if (isUsingDjangoDBConnection || isUsingDjangoDBConnections) { AstNode attributeRef = node.getFirstChild(PythonGrammar.ATTRIBUTE_REF); if (attributeRef != null && attributeRef.getLastChild(PythonGrammar.NAME).getTokenValue().equals("execute")) { addIssue(node, MESSAGE); } } super.visitNode(node); }

Target:
public void visitNode(AstNode node) { AstNode attributeRef = node.getFirstChild(PythonGrammar.ATTRIBUTE_REF); if (attributeRef != null) { String functionName = attributeRef.getLastChild(PythonGrammar.NAME).getTokenValue(); if (isSQLQueryFromDjangoModel(functionName) || isSQLQueryFromDjangoDBConnection(functionName)) { addIssue(node, MESSAGE); } } super.visitNode(node); }
Source:
private RpcOptions determineRpcOptionsForBackupReplication(RpcManager rpc, boolean isSync, Collection<Address> recipients) { RpcOptions options; if (isSync) { if (recipients == null) { options = rpc.getRpcOptionsBuilder(ResponseMode.SYNCHRONOUS_IGNORE_LEAVERS).build(); } else { options = rpc.getDefaultRpcOptions(true); } } else { options = rpc.getDefaultRpcOptions(false); } return options; }

Target:
private RpcOptions determineRpcOptionsForBackupReplication(RpcManager rpc, boolean isSync, Collection<Address> recipients) { if (isSync) { return recipients == null ? rpc.getRpcOptionsBuilder(ResponseMode.SYNCHRONOUS_IGNORE_LEAVERS).build() : defaultSyncOptions; } else { return defaultAsyncOptions; } }
Source:
public List<? extends Module> getJacksonModules() { return ImmutableList.<Module>of( new SimpleModule("DruidLookupModule") { @Override public void setupModule(SetupContext context) { context.registerSubtypes(MapLookupExtractorFactory.class); } } ); }

Target:
public List<? extends Module> getJacksonModules() { return ImmutableList.<Module>of( new SimpleModule("DruidLookupModule").registerSubtypes(MapLookupExtractorFactory.class) ); }
Source:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { for (String device : connectorThreads.keySet()) { logger.debug("Close previous message listener for device '" + device + "'"); final AnelConnectorThread connectorThread = connectorThreads.get(device); connectorThread.setInterrupted(); } for (String device : connectorThreads.keySet()) { final AnelConnectorThread connectorThread = connectorThreads.get(device); try { connectorThread.join(); } catch (InterruptedException e) { logger.info("Previous message listener closing interrupted for device '" + device + "'", e); } } connectorThreads.clear(); refreshInterval = 0; try { refreshInterval = AnelConfigReader.readConfig(config, connectorThreads, bindingFacade); logger.debug("Anel configuration read with refresh interval " + refreshInterval + "ms and " + connectorThreads.size() + " devices."); } catch (ConfigurationException e) { logger.error("Could not read configuration for Anel binding: " + e.getMessage()); return; } catch (Exception e) { logger.error("Could not read configuration for Anel binding", e); return; } setProperlyConfigured(true); for (String device : connectorThreads.keySet()) { final AnelConnectorThread connectorThread = connectorThreads.get(device); logger.debug("Starting message listener for device: " + connectorThread); connectorThread.start(); } new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(30000); } catch (InterruptedException e) { } for (AnelConnectorThread connectorThread : connectorThreads.values()) { connectorThread.requestRefresh(); } } }).start(); }

Target:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { disconnectAll(); connectorThreads.clear(); refreshInterval = 0; try { refreshInterval = AnelConfigReader.readConfig(config, connectorThreads, bindingFacade); logger.debug("Anel configuration read with refresh interval " + refreshInterval + "ms and " + connectorThreads.size() + " devices."); } catch (ConfigurationException e) { logger.error("Could not read configuration for Anel binding: " + e.getMessage()); return; } catch (Exception e) { logger.error("Could not read configuration for Anel binding", e); return; } setProperlyConfigured(true); for (String device : connectorThreads.keySet()) { final AnelConnectorThread connectorThread = connectorThreads.get(device); logger.debug("Starting message listener for device: " + connectorThread); connectorThread.start(); } new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(THREAD_INITIALIZATION_DELAY); } catch (InterruptedException e) { } refreshAll(); } }).start(); }
Source:
public List<UserDto> getAllUsersSortedByLastName() { try { final Criteria criteria = this.getSession().createCriteria(WorkbenchUser.class); criteria.createAlias("person", "person", CriteriaSpecification.LEFT_JOIN); criteria.createAlias("person.crops", "crops", CriteriaSpecification.LEFT_JOIN); criteria.addOrder(Order.asc("person.lastName")); criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); final List<WorkbenchUser> workbenchUsers = criteria.list(); final List<UserDto> users = new ArrayList<>(); if (workbenchUsers != null) { for (final WorkbenchUser workbenchUser : workbenchUsers) { final UserDto user = new UserDto(); if (workbenchUser.getRoles() != null && !workbenchUser.getRoles().isEmpty()) { user.setUserRoles(UserRoleMapper.map(workbenchUser.getRoles())); } user.setUserId(workbenchUser.getUserid()); if (workbenchUser.getPerson() != null) { user.setEmail(workbenchUser.getPerson().getEmail()); user.setFirstName(workbenchUser.getPerson().getFirstName()); user.setLastName(workbenchUser.getPerson().getLastName()); if (workbenchUser.getPerson().getCrops() != null) { final Set<CropDto> crops = new HashSet<>(); for (final CropType cropType : workbenchUser.getPerson().getCrops()) { final CropDto crop = new CropDto(); crop.setCropName(cropType.getCropName()); crops.add(crop); } user.setCrops(crops); } } user.setStatus(workbenchUser.getStatus()); user.setUsername(workbenchUser.getName()); users.add(user); } } return users; } catch (final HibernateException e) { final String message = "Error with getAllUserDtosSorted() query from User: " + e.getMessage(); WorkbenchUserDAO.LOG.error(message, e); throw new MiddlewareQueryException(message, e); } }

Target:
public List<UserDto> getAllUsersSortedByLastName() { try { final Criteria criteria = this.getSession().createCriteria(WorkbenchUser.class); criteria.createAlias("person", "person", CriteriaSpecification.LEFT_JOIN); criteria.createAlias("person.crops", "crops", CriteriaSpecification.LEFT_JOIN); criteria.addOrder(Order.asc("person.lastName")); criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); final List<WorkbenchUser> workbenchUsers = criteria.list(); final List<UserDto> users = new ArrayList<>(); if (workbenchUsers != null) { for (final WorkbenchUser workbenchUser : workbenchUsers) { users.add(new UserDto(workbenchUser)); } } return users; } catch (final HibernateException e) { final String message = "Error with getAllUserDtosSorted() query from User: " + e.getMessage(); WorkbenchUserDAO.LOG.error(message, e); throw new MiddlewareQueryException(message, e); } }
Source:
public Set<String> getWriteScopes() { return writeScopes; }

Target:
public Set<String> getWriteScopes() { return Collections.unmodifiableSet(writeScopes); }
Source:
protected void persist(final StepContribution contribution, final Chunk<O> chunk) throws Exception { RetryCallback<Object> retryCallback = new RetryCallback<Object>() { @Override @SuppressWarnings("unchecked") public Object doWithRetry(RetryContext context) throws Exception { chunkMonitor.setChunkSize(chunk.size()); try { doPersist(contribution, chunk); } catch (Exception e) { if (shouldSkip(skipPolicy, e, contribution.getStepSkipCount())) { for (O item : chunk.getItems()) { getListener().onSkipInWrite(item, e); } } else { getListener().onRetryWriteException((List<Object>) chunk.getItems(), e); if (rollbackClassifier.classify(e)) { throw e; } } throw new ForceRollbackForWriteSkipException( "Force rollback on skippable exception so that skipped item can be located.", e); } contribution.incrementWriteCount(chunk.size()); return null; } }; RecoveryCallback<Object> recoveryCallback = new RecoveryCallback<Object>() { @Override public O recover(RetryContext context) throws Exception { Throwable e = context.getLastThrowable(); if (shouldSkip(skipPolicy, e, contribution.getStepSkipCount())) { contribution.incrementWriteSkipCount(); logger.debug("Skipping after failed write", e); return null; } else { if (rollbackClassifier.classify(e)) { throw new RetryException("Non-skippable exception in recoverer while write", e); } return null; } } }; batchRetryTemplate.execute(retryCallback, recoveryCallback); }

Target:
protected void persist(final StepContribution contribution, final Chunk<O> chunk) throws Exception { RetryCallback<Object> retryCallback = new RetryCallback<Object>() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Object doWithRetry(RetryContext context) throws Exception { chunkMonitor.setChunkSize(chunk.size()); try { doPersist(contribution, chunk); } catch (Exception e) { if (shouldSkip(skipPolicy, e, contribution.getStepSkipCount())) { ((MulticasterBatchListener) getListener()).onSkipInWrite(chunk.getItems(), e); } else { getListener().onRetryWriteException((List<Object>) chunk.getItems(), e); if (rollbackClassifier.classify(e)) { throw e; } } throw new ForceRollbackForWriteSkipException( "Force rollback on skippable exception so that skipped item can be located.", e); } contribution.incrementWriteCount(chunk.size()); return null; } }; RecoveryCallback<Object> recoveryCallback = new RecoveryCallback<Object>() { @Override public O recover(RetryContext context) throws Exception { Throwable e = context.getLastThrowable(); if (shouldSkip(skipPolicy, e, contribution.getStepSkipCount())) { contribution.incrementWriteSkipCount(); logger.debug("Skipping after failed write", e); return null; } else { if (rollbackClassifier.classify(e)) { throw new RetryException("Non-skippable exception in recoverer while write", e); } return null; } } }; batchRetryTemplate.execute(retryCallback, recoveryCallback); }
Source:
public boolean isCompiletimeEvaluable() { return true; }

Target:
public boolean isCompiletimeEvaluable() { return value.isCompiletimeEvaluable(); }
Source:
public Image apply(@Nullable VirtualMachine from) { if (from == null || from.getConfig() == null) { OperatingSystem os = OperatingSystem.builder().description("null").family(OsFamily.UNRECOGNIZED) .version("null").is64Bit(true).arch("null").build(); return new ImageBuilder() .id("null") .name("null") .description("null") .operatingSystem(os).status(toPortableImageStatus.get(from.getRuntime().getPowerState())) .build(); } String guestFamily = from.getConfig().getGuestId(); String annotation = from.getConfig().getAnnotation(); OsFamily family = parseOsFamilyOrUnrecognized(annotation); String version = parseVersionOrReturnEmptyString(family, annotation, osVersionMap); OperatingSystem os = OperatingSystem.builder().description(annotation).family(family) .version(version).is64Bit(true).arch("x86_64").build(); return new ImageBuilder() .id(from.getName()) .name(from.getName()) .description(from.getName()) .operatingSystem(os).status(toPortableImageStatus.get(from.getRuntime().getPowerState())) .build(); }

Target:
public Image apply(@Nullable VirtualMachine from) { if (from == null || from.getConfig() == null) { OperatingSystem os = OperatingSystem.builder().description("null").family(OsFamily.UNRECOGNIZED) .version("null").is64Bit(true).arch("null").build(); return new ImageBuilder() .id("null") .name("null") .description("null") .operatingSystem(os).status(toPortableImageStatus.get(from.getRuntime().getPowerState())) .build(); } String guestFamily = from.getConfig().getGuestId(); String annotation = from.getConfig().getAnnotation(); OsFamily family = annotation == null ? OsFamily.UNRECOGNIZED : parseOsFamilyOrUnrecognized(annotation); String description = annotation == null ? guestFamily : annotation; String version = parseVersionOrReturnEmptyString(family, annotation, osVersionMap); OperatingSystem os = OperatingSystem.builder().description(description).family(family) .version(version).is64Bit(true).arch("x86_64").build(); return new ImageBuilder() .id(from.getName()) .name(from.getName()) .description(from.getName()) .operatingSystem(os).status(toPortableImageStatus.get(from.getRuntime().getPowerState())) .build(); }
Source:
public Double getPriority() { return getValueAsDouble("priority", Double.MAX_VALUE); }

Target:
public Integer getPriority() { return getValueAsInteger("priority", Integer.MAX_VALUE); }
Source:
private QueryRequest getQueryRequest() throws IOException { QueryRequest queryRequest = null; if (request.method() == HttpMethod.GET) { String queryString = getParameterValue(QUERY_STRING); String strOffset = getParameterValue(OFFSET); String queryMode = getParameterValue(QUERY_MODE); Integer offset = strOffset != null ? Integer.valueOf(strOffset) : null; String strMaxResults = getParameterValue(MAX_RESULTS); Integer maxResults = strMaxResults != null ? Integer.valueOf(strMaxResults) : null; IndexedQueryMode qm = queryMode == null ? IndexedQueryMode.FETCH : IndexedQueryMode.valueOf(queryMode); queryRequest = new QueryRequest(queryString, offset, maxResults, qm); } else if (request.method() == HttpMethod.POST || request.method() == HttpMethod.PUT) { queryRequest = getQueryFromJSON(); } return queryRequest; }

Target:
private QueryRequest getQueryRequest() throws IOException { QueryRequest queryRequest = null; if (request.method() == HttpMethod.GET) { queryRequest = getQueryFromString(); } else if (request.method() == HttpMethod.POST || request.method() == HttpMethod.PUT) { queryRequest = getQueryFromJSON(); } return queryRequest; }
Source:
public final Object doResolveAfter(final VirtualFrame frame, final SResolver resolver, final long timeout) { Timer t = new Timer(); t.schedule(new TimerTask() { @Override public void run() { resolvePromise(frame, resolver, true, false); } }, timeout); return true; }

Target:
public final Object doResolveAfter(final VirtualFrame frame, final SResolver resolver, final long timeout) { if (timerThread == null) { timerThread = new Timer(); } timerThread.schedule(new TimerTask() { @Override public void run() { ResolvePromiseNode.resolve(wrapper, resolver.getPromise(), true, resolver.getPromise().getOwner(), false); } }, timeout); return true; }
Source:
public String publish(ArtifactId templateArtId, ArtifactId headArtId) { ArtifactReadable artifact = getArtifactHead(headArtId); String template = setUpTemplateWithOptions(templateArtId); if (!artifact.equals(ArtifactReadable.SENTINEL)) { if (!template.equals("") && elementType.equals(ARTIFACT)) { StringBuilder wordMlOutput = applyContentToTemplate(artifact, template); return wordMlOutput.toString(); } else { return null; } } else { return null; } }

Target:
public String publish(ArtifactId templateArtId, ArtifactId headArtId) { ArtifactReadable artifact = getArtifactHead(headArtId); String template = setUpTemplateWithOptions(templateArtId); if (artifact.isValid()) { if (Strings.isValid(template) && elementType.equals(ARTIFACT)) { StringBuilder wordMlOutput = applyContentToTemplate(artifact, template); return wordMlOutput.toString(); } else { return null; } } else { return null; } }
Source:
SymbolMapper getCorrelatedSymbolMapper() { return new SymbolMapper(correlatedSymbolsMapping.asMap().entrySet().stream() .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, symbols -> Iterables.getLast(symbols.getValue())))); }

Target:
SymbolMapper getCorrelatedSymbolMapper() { return new SymbolMapper(correlatedSymbolsMapping.asMap().entrySet().stream() .collect(toImmutableMap(Map.Entry::getKey, symbols -> Iterables.getLast(symbols.getValue())))); }
Source:
Location getLocation() { return new TypeInInputLibraryLocation(inputJackLibrary.getLocation(), Jack.getUserFriendlyFormatter().getName(enclosingPackage, simpleName)); }

Target:
Location getLocation() { return location; }
Source:
private void writeTimeGrainHoursHeaders() { for (TimeGrain timeGrain : solution.getTimeGrainList()) { LocalTime startTime = LocalTime.ofSecondOfDay(timeGrain.getStartingMinuteOfDay() * 60); LocalTime endTime = LocalTime.ofSecondOfDay( (timeGrain.getStartingMinuteOfDay() + timeGrain.GRAIN_LENGTH_IN_MINUTES) * 60); nextHeaderCell(TIME_FORMATTER.format(startTime)); } }

Target:
private void writeTimeGrainHoursHeaders() { for (TimeGrain timeGrain : solution.getTimeGrainList()) { LocalTime startTime = LocalTime.ofSecondOfDay(timeGrain.getStartingMinuteOfDay() * 60); nextHeaderCell(TIME_FORMATTER.format(startTime)); } }
Source:
public void testGridSetLoading() throws Exception { GWC gwc = GWC.get(); int waited = 0; while(waited <= 30000 && GWC.get().getGridSetBroker().get(INSPIRE_GRID_SET_NAME) == null) { Thread.sleep(100); waited += 100; } assertThat(gwc.getGridSetBroker().get(INSPIRE_GRID_SET_NAME), notNullValue()); assertThat(gwc.isInternalGridSet(INSPIRE_GRID_SET_NAME), is(true)); }

Target:
public void testGridSetLoading() throws Exception { GWC gwc = GWC.get(); assertThat(gwc.getGridSetBroker().get(INSPIRE_GRID_SET_NAME), notNullValue()); assertThat(gwc.isInternalGridSet(INSPIRE_GRID_SET_NAME), is(true)); }
Source:
public Function<String, String> from1_1to1_2() { return rawXml -> rawXml.replaceAll("</simulationDescriptor>", "<dmoSession></dmoSession>\n<type>RULE</type>\n</simulationDescriptor>").replaceAll("<ScenarioSimulationModel version=\"1.1\">", "<ScenarioSimulationModel version=\"1.2\">"); }

Target:
public Function<String, String> from1_1to1_2() { return rawXml -> { if ((rawXml.contains("<dmoSession>") || (rawXml.contains("<dmnFilePath>")) && (rawXml.contains("<type>")))) { return rawXml.replaceAll("<ScenarioSimulationModel version=\"1.1\">", "<ScenarioSimulationModel version=\"1.2\">"); } else { return rawXml.replaceAll("</simulationDescriptor>", "<dmoSession></dmoSession>\n<type>RULE</type>\n</simulationDescriptor>").replaceAll("<ScenarioSimulationModel version=\"1.1\">", "<ScenarioSimulationModel version=\"1.2\">"); } }; }
Source:
static boolean looselyMatches(URI notifyUri, String repository) { boolean result = false; try { URI repositoryUri = new URI(repository); result = Objects.equal(getScheme(notifyUri), getScheme(repositoryUri)) && Objects.equal(notifyUri.getHost(), repositoryUri.getHost()) && getPort(notifyUri) == getPort(repositoryUri) && Objects.equal(notifyUri.getPath(), repositoryUri.getPath()) && Objects.equal(notifyUri.getQuery(), repositoryUri.getQuery()); } catch ( URISyntaxException ex ) { LOGGER.log(Level.SEVERE, "could not parse repository uri " + repository, ex); } return result; }

Target:
static boolean looselyMatches(URI notifyUri, String repository) { boolean result = false; try { URI repositoryUri = new URI(repository); result = getScheme(notifyUri).equals(getScheme(repositoryUri)) && Objects.equal(notifyUri.getHost(), repositoryUri.getHost()) && getPort(notifyUri) == getPort(repositoryUri) && Objects.equal(notifyUri.getPath(), repositoryUri.getPath()) && Objects.equal(notifyUri.getQuery(), repositoryUri.getQuery()); } catch ( URISyntaxException ex ) { LOGGER.log(Level.SEVERE, "could not parse repository uri " + repository, ex); } return result; }
Source:
protected void onPostExecute(List<SetupConfiguration> setupConfigurations){ if(setupConfigurations == null){ Toast.makeText(getContext(), "Setup configurations could not be loaded", Toast.LENGTH_SHORT).show(); return; } allSetupConfigurations = setupConfigurations; SetupConfigurationAdapter.this.clear(); addAll(setupConfigurations); notifyDataSetChanged(); if (backgroundListQueryTaskListener != null) { backgroundListQueryTaskListener.onQueryTaskFinish(); } }

Target:
protected void onPostExecute(List<SetupConfiguration> setupConfigurations){ if(setupConfigurations == null){ Toast.makeText(getContext(), R.string.error_setup_configuration_download, Toast.LENGTH_SHORT).show(); return; } allSetupConfigurations = setupConfigurations; SetupConfigurationAdapter.this.clear(); addAll(setupConfigurations); notifyDataSetChanged(); if (backgroundListQueryTaskListener != null) { backgroundListQueryTaskListener.onQueryTaskFinish(); } }
Source:
public Chain get(long key) { EhcacheEntityResponse response; try { response = entity.invoke(messageFactory.getOperation(key), false); } catch (Exception e) { throw new ServerStoreProxyException(e); } if (response != null && response.getType() == EhcacheEntityResponse.Type.GET_RESPONSE) { return ((EhcacheEntityResponse.GetResponse)response).getChain(); } else { throw new ServerStoreProxyException("Response for get operation was invalid : " + response != null ? response.getType().toString() : "null message"); } }

Target:
public Chain get(long key) { EhcacheEntityResponse response; try { response = entity.invoke(messageFactory.getOperation(key), false); } catch (Exception e) { throw new ServerStoreProxyException(e); } if (response != null && response.getType() == EhcacheEntityResponse.Type.GET_RESPONSE) { return ((EhcacheEntityResponse.GetResponse)response).getChain(); } else { throw new ServerStoreProxyException("Response for get operation was invalid : " + (response != null ? response.getType().toString() : "null message")); } }
Source:
public void testUpdateNoNetworkWithPortMirroringNetwork() throws Exception { setUriInfo(setUpBasicUriExpectations()); control.replay(); NIC nic = getNic(false); nic.setNetwork(new Network()); nic = resource.update(nic); assertNotNull(nic); }

Target:
public void testUpdateNoNetworkWithPortMirroringNetwork() throws Exception { try { setUriInfo(setUpBasicUriExpectations()); control.replay(); NIC nic = getNic(false); nic.setNetwork(new Network()); nic = resource.update(nic); fail("expected WebApplicationException"); } catch (WebApplicationException wae) { assertEquals(400, wae.getResponse().getStatus()); assertEquals("Cannot set port mirroring if there is no network on the NIC", ((Fault) wae.getResponse().getEntity()).getReason()); } }
Source:
public void invoke(String... parameters) { CmdLineParser parser = new CmdLineParser(this); try { try { parser.parseArgument(parameters); if (inputFiles.isEmpty()) { throw new CmdLineException(parser, "asciidoctor: FAILED: input file missing"); } } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); return; } Options options = parse(); ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile)); for (String inputFile : inputFiles) { String output = renderInput(options, inputFile); zip.putNextEntry(new ZipEntry(mapInFileToOutFile(inputFile))); zip.write(output.getBytes()); zip.closeEntry(); } zip.close(); } catch (java.io.IOException e) { System.err.println(e.getMessage()); } }

Target:
private void invoke(String... parameters) { CmdLineParser parser = new CmdLineParser(this); try { try { parser.parseArgument(parameters); if (inputFiles.isEmpty()) { throw new CmdLineException(parser, "asciidoctor: FAILED: input file missing"); } } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); System.exit(1); return; } ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile)); byte[] buf = new byte[BUFSIZ]; for (String inputFile : inputFiles) { Options options = createOptions(inputFile); renderInput(options, inputFile); FileInputStream f = new FileInputStream(new File(mapInFileToOutFileWithDir(inputFile))); int len; zip.putNextEntry(new ZipEntry(mapInFileToOutFile(inputFile))); while ((len = f.read(buf)) > 0) { zip.write(buf, 0, len); } f.close(); zip.closeEntry(); } zip.close(); } catch (java.io.IOException e) { System.err.println(e.getMessage()); System.exit(1); } }
Source:
public void initialize() { GatewayConfig configuration = getConfigAs(GatewayConfig.class); if (isConfigurationValid(configuration)) { scheduler.schedule(new Runnable() { @Override public void run() { try { setupGateway(configuration); } catch (final Throwable t) { logger.error("An unexpected error occurred: {}", t.getMessage(), t); } } }, 0, TimeUnit.SECONDS); } }

Target:
public void initialize() { GatewayConfig configuration = getConfigAs(GatewayConfig.class); if (configuration.host == null || configuration.host.isEmpty()) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Host must be specified in the configuration!"); return; } if (configuration.code == null || configuration.code.isEmpty()) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Security code must be provided in the configuration!"); return; } this.gatewayURI = "coaps://" + configuration.host + ":" + configuration.port + "/" + DEVICES; this.gatewayInfoURI = "coaps://" + configuration.host + ":" + configuration.port + "/" + GATEWAY + "/" + GATEWAY_DETAILS; try { URI uri = new URI(gatewayURI); deviceClient = new TradfriCoapClient(uri); } catch (URISyntaxException e) { logger.debug("Illegal gateway URI `{}`: {}", gatewayURI, e.getMessage()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage()); return; } DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder(new InetSocketAddress(0)); builder.setPskStore(new StaticPskStore("", configuration.code.getBytes())); dtlsConnector = new DTLSConnector(builder.build()); endPoint = new CoapEndpoint(dtlsConnector, NetworkConfig.getStandard()); deviceClient.setEndpoint(endPoint); updateStatus(ThingStatus.UNKNOWN); scanJob = scheduler.scheduleWithFixedDelay(() -> { startScan(); }, 0, 1, TimeUnit.MINUTES); }
Source:
public void dropSegment(DataSegment segment, LoadPeonCallback callback) { synchronized (lock) { if (stopped) { log.warn( "Server[%s] failed to drop segment[%s] because load queue peon is stopped.", serverId, segment.getIdentifier() ); callback.execute(); return; } SegmentHolder holder = segmentsToDrop.get(segment); if (holder == null) { log.info("Server[%s] to drop segment[%s] queued.", serverId, segment.getIdentifier()); segmentsToDrop.put(segment, new DropSegmentHolder(segment, callback)); processingExecutor.execute(this::doSegmentManagement); } else { holder.addCallback(callback); } } }

Target:
public void dropSegment(DataSegment segment, LoadPeonCallback callback) { synchronized (lock) { if (stopped) { log.warn( "Server[%s] cannot drop segment[%s] because load queue peon is stopped.", serverId, segment.getIdentifier() ); callback.execute(); return; } SegmentHolder holder = segmentsToDrop.get(segment); if (holder == null) { log.info("Server[%s] to drop segment[%s] queued.", serverId, segment.getIdentifier()); segmentsToDrop.put(segment, new DropSegmentHolder(segment, callback)); processingExecutor.execute(this::doSegmentManagement); } else { holder.addCallback(callback); } } }
Source:
int getToWeight(int landmarkIndex, int node) { int res = landmarkWeightDA.getInt((long) node * LM_ROW_LENGTH + landmarkIndex * 4); int from = res & FROM_WEIGHT_INF; int delta = res >> FROM_WEIGHT_BITS; if (delta == DELTA_INF) return DELTA_MAX; res = from + delta; assert res >= 0 : "Negative forward weight " + res + ", landmark index:" + landmarkIndex + ", node:" + node; return res; }

Target:
int getToWeight(int landmarkIndex, int node) { int res = landmarkWeightDA.getInt((long) node * LM_ROW_LENGTH + landmarkIndex * 4); int delta = res >> FROM_WEIGHT_BITS; if (delta == DELTA_INF) return Integer.MAX_VALUE; int from = res & FROM_WEIGHT_INF; if (from == FROM_WEIGHT_INF) { from = DELTA_INF + 1; } res = from + delta; assert res >= 0 : "Negative forward weight " + res + ", landmark index:" + landmarkIndex + ", node:" + node; return res; }
Source:
private void recordEventWithIdAndSource(final byte eventMarker, final int eventSize, final long id, final SourceSection section, final Activity current) { ensureSufficientSpace(eventSize, current); final int start = position; put(eventMarker); putLong(id); if (VmSettings.TRUFFLE_DEBUGGER_ENABLED || VmSettings.KOMPOS_TRACING) { writeSourceSection(section); } assert position == start + eventSize; }

Target:
private void recordEventWithIdAndSource(final byte eventMarker, final int eventSize, final long id, final SourceSection section, final Activity current) { ensureSufficientSpace(eventSize, current); final int start = position; put(eventMarker); putLong(id); if (VmSettings.KOMPOS_TRACING) { writeSourceSection(section); } assert position == start + eventSize; }
Source:
public SegmentHandoffNotifier createSegmentHandoffNotifier(String dataSource) { return new SegmentHandoffNotifier() { @Override public boolean registerSegmentHandoffCallback( SegmentDescriptor descriptor, Executor exec, Runnable handOffRunnable ) { log.info("Not waiting for segment to be handed off, executing handOffRunnable"); exec.execute(handOffRunnable); return true; } @Override public void start() @Override public void close() }; }

Target:
public SegmentHandoffNotifier createSegmentHandoffNotifier(String dataSource) { return NOTIFIER; }
Source:
public void onStdOut(String message) { System.err.println( "onStdOut: " + message ); message = message.trim(); if ( message.isEmpty() == false ) { messages.add( PodExec.CHANNEL_STDOUT+message ); } }

Target:
public void onStdOut(String message) { LOG.debug( "onStdOut: " + message ); message = message.trim(); if ( message.isEmpty() == false ) { messages.add( PodExec.CHANNEL_STDOUT+message ); } }
Source:
public static int hammingDistance(final String s1, final String s2) { if (s1.length() != s2.length()) { throw new IllegalArgumentException("Attempted to determine Hamming distance of strings with differing lengths."); } int measuredDistance = 0; for (int i = 0;i < s1.length();i++) { if (s1.charAt(i) != s2.charAt(i)) { measuredDistance++; } } return measuredDistance; }

Target:
public static int hammingDistance(final String s1, final String s2) { if (s1.length() != s2.length()) { throw new IllegalArgumentException("Attempted to determine Hamming distance of strings with differing lengths. " + "The first string has length " + s1.length() + " and the second string has length " + s2.length() + "."); } int measuredDistance = 0; for (int i = 0;i < s1.length();i++) { if (s1.charAt(i) != s2.charAt(i)) { measuredDistance++; } } return measuredDistance; }
Source:
public void match(final MethodNode methodNode, final IFilterOutput output) { cursor = methodNode.instructions.getFirst(); final Set<AbstractInsnNode> ignore = new HashSet<AbstractInsnNode>(); final int maskVar = Type.getMethodType(methodNode.desc) .getArgumentTypes().length - 2; while (true) { if (cursor.getOpcode() != Opcodes.ILOAD) { break; } if (((VarInsnNode) cursor).var != maskVar) { break; } next(); nextIs(Opcodes.IAND); nextIs(Opcodes.IFEQ); if (cursor == null) { return; } ignore.add(cursor); cursor = instructionAfterLabel(((JumpInsnNode) cursor).label); } for (AbstractInsnNode i : ignore) { output.ignore(i, i); } }

Target:
public void match(final MethodNode methodNode, final IFilterOutput output) { cursor = methodNode.instructions.getFirst(); final Set<AbstractInsnNode> ignore = new HashSet<AbstractInsnNode>(); final int maskVar = Type.getMethodType(methodNode.desc) .getArgumentTypes().length - 2; while (true) { if (cursor.getOpcode() != Opcodes.ILOAD) { break; } if (((VarInsnNode) cursor).var != maskVar) { break; } next(); nextIs(Opcodes.IAND); nextIs(Opcodes.IFEQ); if (cursor == null) { return; } ignore.add(cursor); cursor = ((JumpInsnNode) cursor).label; skipNonOpcodes(); } for (AbstractInsnNode i : ignore) { output.ignore(i, i); } }
Source:
public boolean equals(Object o) { if (o instanceof PartitionKey) { PartitionKey another = (PartitionKey) o; boolean eq = ((columnName != null && another.columnName != null && columnName.equals(another.columnName)) || (columnName == null && another.columnName == null)); eq = eq && ((partitionValue != null && another.partitionValue != null && partitionValue.equals(another.partitionValue)) || (partitionValue == null && another.partitionValue == null)); return eq; } return false; }

Target:
public boolean equals(Object o) { if (o instanceof PartitionKey) { PartitionKey another = (PartitionKey) o; return TUtil.checkEquals(columnName, another.columnName) && TUtil.checkEquals(partitionValue, another.partitionValue); } return false; }
Source:
public void afterSuite() throws IOException { System.out.println("afterSuite " + getClass().getName()); for (ObjectName mbean : _server.queryNames(null, null)) { try { _server.unregisterMBean(mbean); } catch (Exception e) { } } _baseDataAccessorMap.values().forEach(BaseDataAccessor::close); _clusterSetupMap.values().forEach(ClusterSetup::close); _helixZkClientMap.values().forEach(HelixZkClient::close); _zkServerMap.values().forEach(TestHelper::stopZkServer); System.out.println("last line"); }

Target:
public void afterSuite() throws IOException { for (ObjectName mbean : _server.queryNames(null, null)) { try { _server.unregisterMBean(mbean); } catch (Exception e) { } } _baseDataAccessorMap.values().forEach(BaseDataAccessor::close); _clusterSetupMap.values().forEach(ClusterSetup::close); _helixZkClientMap.values().forEach(HelixZkClient::close); _zkServerMap.values().forEach(TestHelper::stopZkServer); }
Source:
public void stripeRefund() { String externalChargeId = defaultTestCharge.getExternalChargeId(); long amount = 10L; stripeMockClient.mockCancelCharge(); ImmutableMap<String, Long> refundData = ImmutableMap.of("amount", amount, "refund_amount_available", defaultTestCharge.getAmount()); String refundPayload = new Gson().toJson(refundData); ValidatableResponse response = given().port(testContext.getPort()) .body(refundPayload) .accept(ContentType.JSON) .contentType(ContentType.JSON) .post("/v1/api/accounts/{accountId}/charges/{chargeId}/refunds" .replace("{accountId}", accountId) .replace("{chargeId}", externalChargeId)) .then() .statusCode(ACCEPTED_202); List<Map<String, Object>> refundsFoundByChargeId = databaseTestHelper.getRefundsByChargeId(defaultTestCharge.getChargeId()); assertThat(refundsFoundByChargeId.size(), is(1)); Long chargeId = databaseTestHelper.getChargeIdByExternalId(externalChargeId); assertEquals(databaseTestHelper.getChargeStatus(chargeId), CAPTURED.getValue()); String refundId = response.extract().path("refund_id"); verify(postRequestedFor(urlEqualTo("/v1/refunds")) .withHeader("Idempotency-Key", equalTo(refundId)) .withRequestBody(containing("charge=" + defaultTestCharge.getTransactionId())) .withRequestBody(containing("amount=" + amount))); }

Target:
public void stripeRefund() { String externalChargeId = defaultTestCharge.getExternalChargeId(); long amount = 10L; stripeMockClient.mockCancelCharge(); ImmutableMap<String, Long> refundData = ImmutableMap.of("amount", amount, "refund_amount_available", defaultTestCharge.getAmount()); String refundPayload = new Gson().toJson(refundData); ValidatableResponse response = given().port(testContext.getPort()) .body(refundPayload) .accept(ContentType.JSON) .contentType(ContentType.JSON) .post("/v1/api/accounts/{accountId}/charges/{chargeId}/refunds" .replace("{accountId}", accountId) .replace("{chargeId}", externalChargeId)) .then() .statusCode(ACCEPTED_202); List<Map<String, Object>> refundsFoundByChargeId = databaseTestHelper.getRefundsByChargeId(defaultTestCharge.getChargeId()); assertThat(refundsFoundByChargeId.size(), is(1)); Long chargeId = databaseTestHelper.getChargeIdByExternalId(externalChargeId); assertEquals(databaseTestHelper.getChargeStatus(chargeId), CAPTURED.getValue()); String refundId = response.extract().path("refund_id"); verify(postRequestedFor(urlEqualTo("/v1/refunds")) .withHeader("Idempotency-Key", equalTo(refundId)) .withRequestBody(containing("charge=" + defaultTestCharge.getTransactionId())) .withRequestBody(containing("amount=" + amount)) .withRequestBody(containing("reverse_transfer=true")) .withRequestBody(containing("refund_application_fee=true"))); }
Source:
public void createTopic(final EventType eventType) throws TopicCreationException, DuplicatedEventTypeNameException { createTopic(eventType.getTopic(), calculateKafkaPartitionCount(eventType.getDefaultStatistic()), nakadiSettings.getDefaultTopicReplicaFactor(), eventType.getOptions().getRetentionTime(), nakadiSettings.getDefaultTopicRotationMs()); }

Target:
public void createTopic(final EventType eventType) throws TopicCreationException, DuplicatedEventTypeNameException { if (eventType.getOptions().getRetentionTime() == null) { throw new IllegalArgumentException("Retention time can not be null"); } createTopic(eventType.getTopic(), calculateKafkaPartitionCount(eventType.getDefaultStatistic()), nakadiSettings.getDefaultTopicReplicaFactor(), eventType.getOptions().getRetentionTime(), nakadiSettings.getDefaultTopicRotationMs()); }
Source:
public List<String> listAll(String path) { List<String> objects = new ArrayList<String>(); List<String> pathParts = Splitter.on('/').splitToList(ensureTrailingSlashRemoved(path)); int pathCount = pathParts.size(); for (String object : getAllObjects(ensureTrailingSlashPresent(path))) { List<String> objectParts = Splitter.on('/').splitToList(ensureTrailingSlashRemoved(object)); if (objectParts.size() == pathCount + 1) { objects.add(object); } } return objects; }

Target:
public List<String> listAll(String path) { return Stream.concat(listFolders(path).stream(), listFiles(path).stream()) .collect(Collectors.toList()); }
Source:
public void setDevMode(String mode) { final boolean booleanMode = BooleanUtils.toBoolean(mode); if (!this.devModeValueSet) { this.devMode = booleanMode; this.devModeValueSet = true; if (this.devMode) { LOG.warn("Setting development mode affects the safety of your application!", this.devMode); } } else { LOG.debug("Error setting development mode value [{}], already previously set to [{}]", mode, this.devMode); } }

Target:
protected void setDevMode(String mode) { this.devMode = BooleanUtils.toBoolean(mode); if (this.devMode) { LOG.warn("Setting development mode affects the safety of your application!", this.devMode); } }
Source:
private Client delegate() { long currentCount = counter.get(); if (currentCount >= exceptionCountBeforeRefresh && counter.compareAndSet(currentCount, 0)) { log.info("Creating a new Feign client, as exceptions have been thrown in a row by old client", SafeArg.of("count", currentCount)); try { currentClient = refreshingSupplier.get(); } catch (RuntimeException e) { log.warn("An error occurred whilst trying to re-create an OkHttpClient, because exceptions have been thrown in a row by old client." + " Continuing operation with the old client...", SafeArg.of("count", currentCount), e); } } return currentClient; }

Target:
private Client delegate() { long currentCount = counter.get(); if (currentCount >= exceptionCountBeforeRefresh && counter.compareAndSet(currentCount, 0)) { log.info("Creating a new Feign client, as exceptions have been thrown in a row by old client", SafeArg.of("count", currentCount)); try { currentClient = refreshingSupplier.get(); } catch (RuntimeException e) { log.warn("An error occurred whilst trying to re-create an OkHttpClient." + " Continuing operation with the old client...", SafeArg.of("count", currentCount), e); } } return currentClient; }
Source:
private FirewallRule findById(List<FirewallRule> collection, String id) { FirewallRule result = null; for (FirewallRule rule : collection) { if (rule.id().equals(id)) { result = rule; } } return result; }

Target:
private FirewallRule findById(List<FirewallRule> collection, String id) { for (FirewallRule rule : collection) { if (rule.id().equals(id)) { return rule; } } return null; }
Source:
public void truncateAllRounds() { lock.writeLock().lock(); try { File dir = new File(path); boolean success = getLogEntries(dir).stream().map(File::delete).reduce(true, (x, y) -> x && y); if (!success) { log.warn("failed to delete all log files."); } } finally { lock.writeLock().unlock(); } }

Target:
public void truncateAllRounds() { lock.writeLock().lock(); try { File dir = new File(path); getLogEntries(dir).forEach(PaxosStateLogImpl::deleteLogFile); } finally { lock.writeLock().unlock(); } }
Source:
public Image getImage(Object element) { RepositoryTreeNode node = (RepositoryTreeNode) element; if (node.getType() == RepositoryTreeNodeType.TAG) { try { ObjectId id = node.getRepository().resolve( ((Ref) node.getObject()).getName()); new RevWalk(node.getRepository()).parseTag(id); return decorateImage(node.getType().getIcon(), element); } catch (AmbiguousObjectException e) { return decorateImage(node.getType().getIcon(), element); } catch (IOException e) { return decorateImage(lightweightTagImage, element); } } else return decorateImage(node.getType().getIcon(), element); }

Target:
public Image getImage(Object element) { RepositoryTreeNode node = (RepositoryTreeNode) element; if (node.getType() == RepositoryTreeNodeType.TAG) { RevObject any; try { ObjectId id = node.getRepository().resolve( ((Ref) node.getObject()).getName()); any = new RevWalk(node.getRepository()).parseAny(id); } catch (MissingObjectException e) { Activator.logError(e.getMessage(), e); return null; } catch (IOException e) { Activator.logError(e.getMessage(), e); return null; } if (any instanceof RevCommit) return decorateImage(lightweightTagImage, element); else return decorateImage(node.getType().getIcon(), element); } else return decorateImage(node.getType().getIcon(), element); }
Source:
public SecureStoreData(String pluginName, String className, File jarFile, String storeName) { super(storeName, "", jarFile); this.className = className; this.storeName = storeName; }

Target:
public SecureStoreData(String pluginName, String className, File jarFile, String storeName) { super(pluginName, "", jarFile); this.className = className; this.storeName = String.format("%s/%s", pluginName, storeName); }
Source:
private void deliverMessages() { try { log.trace("{} Delivering batch of messages to task", this, messageBatch.size()); long start = time.milliseconds(); task.put(new ArrayList<>(messageBatch)); recordBatch(messageBatch.size()); sinkTaskMetricsGroup.recordPut(time.milliseconds() - start); currentOffsets.putAll(origOffsets); messageBatch.clear(); if (pausedForRedelivery) { if (!shouldPause()) resumeAll(); pausedForRedelivery = false; } } catch (RetriableException e) { log.error("{} RetriableException from SinkTask:", this, e); pausedForRedelivery = true; pauseAll(); } catch (Throwable t) { log.error("{} Task threw an uncaught and unrecoverable exception. Task is being killed and will not " + "recover until manually restarted. {}", this, t.getMessage()); throw new ConnectException("Exiting WorkerSinkTask due to unrecoverable exception.", t); } }

Target:
private void deliverMessages() { try { log.trace("{} Delivering batch of messages to task", this, messageBatch.size()); long start = time.milliseconds(); task.put(new ArrayList<>(messageBatch)); recordBatch(messageBatch.size()); sinkTaskMetricsGroup.recordPut(time.milliseconds() - start); currentOffsets.putAll(origOffsets); messageBatch.clear(); if (pausedForRedelivery) { if (!shouldPause()) resumeAll(); pausedForRedelivery = false; } } catch (RetriableException e) { log.error("{} RetriableException from SinkTask:", this, e); pausedForRedelivery = true; pauseAll(); } catch (Throwable t) { log.error("{} Task threw an uncaught and unrecoverable exception. Task is being killed and will not " + "recover until manually restarted. Error: {}", this, t.getMessage(), t); throw new ConnectException("Exiting WorkerSinkTask due to unrecoverable exception.", t); } }
Source:
private static String getDensityString(DisplayMetrics displayMetrics) { switch (displayMetrics.densityDpi) { case DisplayMetrics.DENSITY_LOW: return "ldpi"; case DisplayMetrics.DENSITY_MEDIUM: return "mdpi"; case DisplayMetrics.DENSITY_HIGH: return "hdpi"; case DisplayMetrics.DENSITY_XHIGH: return "xhdpi"; case DisplayMetrics.DENSITY_XXHIGH: return "xxhdpi"; case DisplayMetrics.DENSITY_XXXHIGH: return "xxxhdpi"; case DisplayMetrics.DENSITY_TV: return "tvdpi"; default: return "unknown"; } }

Target:
private static String getDensityString(DisplayMetrics displayMetrics) { switch (displayMetrics.densityDpi) { case DisplayMetrics.DENSITY_LOW: return "ldpi"; case DisplayMetrics.DENSITY_MEDIUM: return "mdpi"; case DisplayMetrics.DENSITY_HIGH: return "hdpi"; case DisplayMetrics.DENSITY_XHIGH: return "xhdpi"; case DisplayMetrics.DENSITY_XXHIGH: return "xxhdpi"; case DisplayMetrics.DENSITY_XXXHIGH: return "xxxhdpi"; case DisplayMetrics.DENSITY_TV: return "tvdpi"; default: return String.valueOf(displayMetrics.densityDpi); } }