auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<Path> search(RepositorySearchRequest request) { List<Path> result = new LinkedList<Path>(); Storage storage = configurationManager.getConfiguration().getStorage(request.getStorageId()); Repository repository = storage.getRepository(request.getRepositoryId()); LayoutProvider layoutProvider = layoutProviderRegistry.getProvider(repository.getLayout()); List<ArtifactEntry> artifactEntryList = artifactEntryService.findByCoordinates(request.getStorageId(), request.getRepositoryId(), request.getCoordinates(), request.getSkip(), request.getLimit(), request.getOrderBy(), false); for (ArtifactEntry artifactEntry : artifactEntryList) { RepositoryPath repositoryPath; try { repositoryPath = layoutProvider.resolve(repository, artifactEntry.getArtifactCoordinates()); } catch (IOException e) { logger.error(String.format("Failed to resolve Remote Artifact [%s]", artifactEntry.getArtifactPath()), e); continue; } result.add(repositoryPath); } return result; }

Target:
public List<Path> search(RepositorySearchRequest request) { List<Path> result = new LinkedList<Path>(); Storage storage = configurationManager.getConfiguration().getStorage(request.getStorageId()); Repository repository = storage.getRepository(request.getRepositoryId()); LayoutProvider layoutProvider = layoutProviderRegistry.getProvider(repository.getLayout()); List<ArtifactEntry> artifactEntryList = artifactEntryService.findByCoordinates(request.getStorageId(), request.getRepositoryId(), request.getCoordinates(), request.getSkip(), request.getLimit(), request.getOrderBy(), false); for (ArtifactEntry artifactEntry : artifactEntryList) { RepositoryPath repositoryPath; try { repositoryPath = layoutProvider.resolve(repository, artifactEntry.getArtifactCoordinates()); } catch (IOException e) { logger.error(String.format("Failed to resolve Artifact [%s]", artifactEntry.getArtifactPath()), e); continue; } result.add(repositoryPath); } return result; }
Source:
public void handleSuccess() { super.handleSuccess(); if (isCompleteTrace(trace)) { disposeProvider(false); } else { fNbRead += getNbRead(); synchronized (fRequestSyncObj) { if (!getRange().equals(fTimeRange)) { startRequest(); } } } }

Target:
public void handleSuccess() { super.handleSuccess(); if (isCompleteTrace(trace)) { disposeProvider(false); } else { fNbRead += getNbRead(); synchronized (fRequestSyncObj) { final TmfTimeRange timeRange = fTimeRange; if (timeRange != null) { if (getRange().getEndTime().getValue() > timeRange.getEndTime().getValue()) { startRequest(); } } } } }
Source:
private boolean isMaterialFromTypes(Map material, List<String> pollerPluginIds) { if (((String) material.get("type")).equalsIgnoreCase("scm")) { for (String pollerPluginId : pollerPluginIds) { if(((String) material.get("plugin-id")).equalsIgnoreCase(pollerPluginId)) { return true; } } } return false; }

Target:
private boolean isMaterialFromTypes(Map material, List<String> pollerPluginIds) { if (((String) material.get("type")).equalsIgnoreCase("scm")) { return pollerPluginIds.contains((String) material.get("plugin-id")); } return false; }
Source:
public AdSkinHelper(String pathToLeftPart, String pathToRightPart, WebDriver driver) { this.pathToLeftPart = pathToLeftPart; this.pathToRightPart = pathToRightPart; this.driver = driver; this.adsComparison = new AdsComparison(); this.imageEditor = new ImageEditor(); this.shooter = new Shooter(); this.imageComparison = new ImageComparison(); WebElement wikiaArticle = driver.findElement(By.id("WikiaPageBackground")); WebElement globalNavigation = driver.findElement(By.id("globalNavigation")); this.viewPortWidth = globalNavigation.getSize().getWidth(); this.startSkinY = globalNavigation.getSize().getHeight(); this.articleLeftSideX = wikiaArticle.getLocation().x; this.articleRightSideX = wikiaArticle.getLocation().x + wikiaArticle.getSize().getWidth(); }

Target:
public AdSkinHelper(String pathToLeftPart, String pathToRightPart, WebDriver driver) { this.pathToLeftPart = pathToLeftPart; this.pathToRightPart = pathToRightPart; this.driver = driver; }
Source:
protected Endpoint createEndpoint(String urispec, String remaining, Map<String, Object> params) throws Exception { WekaConfiguration config = new WekaConfiguration(this); setProperties(config, params); Command command = Command.valueOf(remaining); config.setCommand(command); return new WekaEndpoint(urispec, this, config); }

Target:
protected Endpoint createEndpoint(String urispec, String remaining, Map<String, Object> params) throws Exception { WekaConfiguration config = new WekaConfiguration(); WekaEndpoint endpoint = new WekaEndpoint(urispec, this, config); setProperties(endpoint, params); Command command = Command.valueOf(remaining); config.setCommand(command); return endpoint; }
Source:
public void testAccessControl_instructorAccessProfileFromHisCourse_shouldPass() { InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); StudentAttributes student1InCourse1 = typicalBundle.students.get("student1InCourse1"); loginAsInstructor(instructor1OfCourse1.googleId); String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, instructor1OfCourse1.courseId, Const.ParamsNames.STUDENT_EMAIL, student1InCourse1.getEmail(), }; verifyCanAccess(submissionParams); }

Target:
public void testAccessControl_instructorAccessProfileFromHisCourse_shouldPass() { InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); StudentAttributes student1InCourse1 = typicalBundle.students.get("student1InCourse1"); String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, instructor1OfCourse1.courseId, Const.ParamsNames.STUDENT_EMAIL, student1InCourse1.getEmail(), }; verifyAccessibleForInstructorsOfTheSameCourse(submissionParams); }
Source:
public void teardownTest() throws InterruptedException { firewallPolicyApi().delete(currentFirewallPolicy.id()); Thread.sleep(15000); assertNodeAvailable(currentServer); deleteServer(currentServer.id()); }

Target:
public void teardownTest() throws InterruptedException { assertNodeAvailable(currentServer); firewallPolicyApi().delete(currentFirewallPolicy.id()); assertNodeAvailable(currentServer); deleteServer(currentServer.id()); }
Source:
protected String getTableNameFromQuery(String jsonStr) { JSONObject j = new JSONObject(jsonStr); String s = (String) j.get("query"); String str = ""; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '{' || s.charAt(i) == '}') { continue; } else { str = str + s.charAt(i); } } String[] queryTerms = str.trim().split("\\s+"); return queryTerms[0]; }

Target:
protected String getTableNameFromQuery(String jsonStr) { StringBuilder str = new StringBuilder(); try { JSONObject j = new JSONObject(jsonStr); String s = (String) j.get("query"); Integer countBrackets = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '{' || s.charAt(i) == '}') { countBrackets++; if (countBrackets == 2) { break; } } else { str.append(s.charAt(i)); } } } catch (JSONException e) { log.error("Exception: {}", e); } return str.toString().trim().split("\\s+")[0]; }
Source:
public void messageTrackedAndRemovedWhenClientLeaves() throws Exception { assertThat(activeMessageHandler.getTrackedClients().count()).isZero(); storeProxy.getAndAppend(42L, createPayload(42L)); Map<Long, EhcacheEntityResponse> responses = activeMessageHandler.getRecordedMessages().filter(r->r.getClientSourceId().toLong() == activeMessageHandler.getTrackedClients().findFirst().get().toLong()) .collect(Collectors.toMap(r->r.getTransactionId(), r->r.getResponse())); assertThat(responses).hasSize(1); assertThat(activeEntity.getConnectedClients()).hasSize(1); service.stop(); activeEntity.notifyDestroyed(activeMessageHandler.getTrackedClients().iterator().next()); waitForPredicate(e -> activeEntity.getConnectedClients().size() > 0, 2000); assertThat(activeMessageHandler.getTrackedClients().count()).isZero(); }

Target:
public void messageTrackedAndRemovedWhenClientLeaves() throws Exception { assertThat(activeMessageHandler.getTrackedClients().count()).isZero(); storeProxy.getAndAppend(42L, createPayload(42L)); assertThat(activeMessageHandler.getRecordedMessages().collect(Collectors.toList())).hasSize(1); assertThat(activeEntity.getConnectedClients()).hasSize(1); service.stop(); activeEntity.notifyDestroyed(activeMessageHandler.getTrackedClients().iterator().next()); waitForPredicate(e -> activeEntity.getConnectedClients().size() > 0, 2000); assertThat(activeMessageHandler.getTrackedClients().count()).isZero(); }
Source:
public void showImage() { this.displayImage = !this.displayImage; if (this.displayImage) { try { identifyImage(this.imageNumber); } catch (Exception e) { Helper.setFehlerMeldung("Error while generating image", e.getMessage()); logger.error(e.getMessage(), e); } } }

Target:
public void showImage() { this.displayImage = !this.displayImage; if (this.displayImage) { try { identifyImage(this.imageNumber); } catch (RuntimeException e) { Helper.setErrorMessage("Error while generating image", logger, e); } } }
Source:
private void initializeDefaultsFromPropertiesFile() throws Exception { Properties props = new Properties(); try (FileReader fr = new FileReader(config.trim())) { props.load(fr); } catch (Exception e) { } String prop = props.getProperty("group.id", ""); if (prop.isEmpty()) { groupid = "voltdb-" + (useSuppliedProcedure ? procedure : table); } else { groupid = prop; } prop = props.getProperty("socket.timeout.ms", null); if (prop != null) { timeout = Integer.parseInt(prop); } prop = props.getProperty("socket.receive.buffer.bytes", null); if (prop != null) { buffersize = Integer.parseInt(prop); } }

Target:
private void initializeDefaultsFromPropertiesFile() throws Exception { if (config.trim().isEmpty()) { return; } Properties props = new Properties(); try (FileReader fr = new FileReader(config.trim())) { props.load(fr); } String prop = props.getProperty("group.id", ""); if (prop.isEmpty()) { groupid = "voltdb-" + (useSuppliedProcedure ? procedure : table); } else { groupid = prop; } prop = props.getProperty("socket.timeout.ms", null); if (prop != null) { timeout = Integer.parseInt(prop); } prop = props.getProperty("socket.receive.buffer.bytes", null); if (prop != null) { buffersize = Integer.parseInt(prop); } prop = props.getProperty("zookeeper.session.timeout.millis", null); if (prop != null) { zookeeperSessionTimeoutMillis = Integer.parseInt(prop); } }
Source:
public static void main(String[] args) throws Exception { VerifiableProperties properties = ToolUtils.getVerifiableProperties(args); DiskReformatterConfig config = new DiskReformatterConfig(properties); StoreConfig storeConfig = new StoreConfig(properties); try (ClusterMap clusterMap = new StaticClusterAgentsFactory(new ClusterMapConfig(properties), config.hardwareLayoutFilePath, config.partitionLayoutFilePath).getClusterMap()) { StoreKeyFactory storeKeyFactory = Utils.getObj(storeConfig.storeKeyFactory, clusterMap); DataNodeId dataNodeId = clusterMap.getDataNodeId(config.datanodeHostname, config.datanodePort); if (dataNodeId == null) { throw new IllegalArgumentException( "Did not find node in clustermap with hostname:port - " + config.datanodeHostname + ":" + config.datanodePort); } DiskReformatter reformatter = new DiskReformatter(dataNodeId, config.fetchSizeInBytes, storeConfig, storeKeyFactory, clusterMap, SystemTime.getInstance()); reformatter.reformat(config.diskMountPath, new File(config.scratchPath)); } }

Target:
public static void main(String[] args) throws Exception { VerifiableProperties properties = ToolUtils.getVerifiableProperties(args); DiskReformatterConfig config = new DiskReformatterConfig(properties); StoreConfig storeConfig = new StoreConfig(properties); ClusterMapConfig clusterMapConfig = new ClusterMapConfig(properties); ClusterAgentsFactory clusterAgentsFactory = Utils.getObj(clusterMapConfig.clusterMapClusterAgentsFactory, clusterMapConfig, config.hardwareLayoutFilePath, config.partitionLayoutFilePath); try (ClusterMap clusterMap = clusterAgentsFactory.getClusterMap()) { StoreKeyFactory storeKeyFactory = Utils.getObj(storeConfig.storeKeyFactory, clusterMap); DataNodeId dataNodeId = clusterMap.getDataNodeId(config.datanodeHostname, config.datanodePort); if (dataNodeId == null) { throw new IllegalArgumentException( "Did not find node in clustermap with hostname:port - " + config.datanodeHostname + ":" + config.datanodePort); } DiskReformatter reformatter = new DiskReformatter(dataNodeId, Collections.EMPTY_LIST, config.fetchSizeInBytes, storeConfig, storeKeyFactory, clusterMap, SystemTime.getInstance()); AtomicInteger exitStatus = new AtomicInteger(0); CountDownLatch latch = new CountDownLatch(config.diskMountPaths.length); for (int i = 0; i < config.diskMountPaths.length; i++) { int finalI = i; Runnable runnable = () -> { try { reformatter.reformat(config.diskMountPaths[finalI], new File(config.scratchPaths[finalI])); latch.countDown(); } catch (Exception e) { throw new IllegalStateException(e); } }; Thread thread = Utils.newThread(config.diskMountPaths[finalI] + "-reformatter", runnable, true); thread.setUncaughtExceptionHandler((t, e) -> { exitStatus.set(1); logger.error("Reformatting failed", config.diskMountPaths[finalI], e); latch.countDown(); }); thread.start(); } latch.await(); System.exit(exitStatus.get()); } }
Source:
public String getOpenTagPattern() { return String.format("<[ ]*%s[ ]*>", this.xmlName); }

Target:
public String getOpenTagPattern() { return String.format(OPEN_TAG_PATTERN, this.xmlName); }
Source:
public void run(DiagnosticsLogWriter writer) { probeRenderer.writer = writer; probeRenderer.timeMillis = System.currentTimeMillis(); probeRenderContext.renderAt(ProbeLevel.DEBUG, probeRenderer); probeRenderer.writer = null; }

Target:
public void run(DiagnosticsLogWriter writer) { collector.writer = writer; collector.timeMillis = System.currentTimeMillis(); context.collectAll(collector); collector.writer = null; }
Source:
private void persistModel(long modelId, String modelName, MLModel model) throws MLModelBuilderException { try { MLStorage storage = databaseService.getModelStorage(modelId); if (storage == null) { throw new MLModelBuilderException("Invalid model ID: " + modelId); } String storageType = storage.getType(); String storageLocation = storage.getLocation(); if (model.getAlgorithmClass().equalsIgnoreCase(MLConstants.DEEPLEARNING)) { MLDeeplearningModel mlDeeplearningModel = (MLDeeplearningModel) model.getModel(); mlDeeplearningModel.setStorageLocation(storageLocation); model.setModel(mlDeeplearningModel); } MLIOFactory ioFactory = new MLIOFactory(mlProperties); MLOutputAdapter outputAdapter = ioFactory.getOutputAdapter(storageType + MLConstants.OUT_SUFFIX); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(model); oos.flush(); oos.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); String outPath = storageLocation + File.separator + modelName; outputAdapter.write(outPath, is); databaseService.updateModelStorage(modelId, storageType, outPath); log.info(String.format("Successfully persisted the model [id] %s", modelId)); } catch (Exception e) { throw new MLModelBuilderException("Failed to persist the model [id] " + modelId + ". " + e.getMessage(), e); } }

Target:
private void persistModel(long modelId, String modelName, MLModel model) throws MLModelBuilderException { try { MLStorage storage = databaseService.getModelStorage(modelId); if (storage == null) { throw new MLModelBuilderException("Invalid model ID: " + modelId); } String storageType = storage.getType(); String storageLocation = storage.getLocation(); if (MLConstants.DEEPLEARNING.equalsIgnoreCase(model.getAlgorithmClass())) { MLDeeplearningModel mlDeeplearningModel = (MLDeeplearningModel) model.getModel(); mlDeeplearningModel.setStorageLocation(storageLocation); model.setModel(mlDeeplearningModel); } MLIOFactory ioFactory = new MLIOFactory(mlProperties); MLOutputAdapter outputAdapter = ioFactory.getOutputAdapter(storageType + MLConstants.OUT_SUFFIX); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(model); oos.flush(); oos.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); String outPath = storageLocation + File.separator + modelName; outputAdapter.write(outPath, is); databaseService.updateModelStorage(modelId, storageType, outPath); log.info(String.format("Successfully persisted the model [id] %s", modelId)); } catch (Exception e) { throw new MLModelBuilderException("Failed to persist the model [id] " + modelId + ". " + e.getMessage(), e); } }
Source:
public void process(VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid) throws AffinityConflictException { VirtualMachine vm = vmProfile.getVirtualMachine(); List<AffinityGroupVMMapVO> vmGroupMappings = _affinityGroupVMMapDao.findByVmIdType(vm.getId(), getType()); for (AffinityGroupVMMapVO vmGroupMapping : vmGroupMappings) { if (vmGroupMapping != null) { AffinityGroupVO group = _affinityGroupDao.findById(vmGroupMapping.getAffinityGroupId()); if (s_logger.isDebugEnabled()) { s_logger.debug("Processing affinity group " + group.getName() + " for VM Id: " + vm.getId()); } List<Long> groupVMIds = _affinityGroupVMMapDao.listVmIdsByAffinityGroup(group.getId()); groupVMIds.remove(vm.getId()); Set<Long> hostIds = new HashSet<>(); for (Long groupVMId : groupVMIds) { VMInstanceVO groupVM = _vmInstanceDao.findById(groupVMId); hostIds.add(groupVM.getHostId()); } List<Long> preferredHostIds = new ArrayList<>(); preferredHostIds.addAll(hostIds); plan.setPreferredHosts(preferredHostIds); } } }

Target:
public void process(VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid) throws AffinityConflictException { VirtualMachine vm = vmProfile.getVirtualMachine(); List<AffinityGroupVMMapVO> vmGroupMappings = _affinityGroupVMMapDao.findByVmIdType(vm.getId(), getType()); if (CollectionUtils.isNotEmpty(vmGroupMappings)) { for (AffinityGroupVMMapVO vmGroupMapping : vmGroupMappings) { processAffinityGroup(vmGroupMapping, plan, vm); } } }
Source:
public Span getSpan(String tenantId, String id) { GetResponse response = null; try { response = client.getClient() .prepareGet(client.getIndex(tenantId), SPAN_TYPE, id) .setRouting(id) .execute() .actionGet(); } catch (IndexMissingException ex) { log.errorf("Missing span index %s", tenantId); return null; } Span span = null; if (!response.isSourceEmpty()) { try { span = deserialize(response.getSourceAsString(), Span.class); if (span.serverSpan() && span.url() == null) { Span clientSpan = getSpan(tenantId, SpanUniqueIdGenerator.getClientId(span.getId())); List<BinaryAnnotation> binaryAnnotations = new ArrayList<>(clientSpan.getBinaryAnnotations()); binaryAnnotations.addAll(span.getBinaryAnnotations()); span = new Span(binaryAnnotations, span.getAnnotations()); } } catch (IOException ex) { log.errorFailedToParse(ex); } } log.tracef("Get span with id[%s] is: %s", id, span); return span; }

Target:
public Span getSpan(String tenantId, String id) { GetResponse response = null; try { response = client.getClient() .prepareGet(client.getIndex(tenantId), SPAN_TYPE, id) .setRouting(id) .execute() .actionGet(); } catch (IndexMissingException ex) { log.errorf("Missing span index %s", tenantId); return null; } Span span = null; if (!response.isSourceEmpty()) { try { span = deserialize(response.getSourceAsString(), Span.class); if (span.serverSpan() && span.url() == null) { Span clientSpan = getSpan(tenantId, SpanUniqueIdGenerator.getClientId(span.getId())); if (clientSpan != null && clientSpan.url() != null) { BinaryAnnotation httpURLAnnotation = new BinaryAnnotation(); httpURLAnnotation.setKey(Constants.ZIPKIN_BIN_ANNOTATION_HTTP_URL); httpURLAnnotation.setValue(clientSpan.url().toString()); List<BinaryAnnotation> binaryAnnotationsWithURL = new ArrayList<>(span.getBinaryAnnotations()); binaryAnnotationsWithURL.add(httpURLAnnotation); span = new Span(span, binaryAnnotationsWithURL, span.getAnnotations()); } } } catch (IOException ex) { log.errorFailedToParse(ex); } } log.tracef("Get span with id[%s] is: %s", id, span); return span; }
Source:
public static LocalCacheManager create(AlluxioConfiguration conf) throws IOException { MetaStore metaStore = MetaStore.create(); CacheEvictor evictor = CacheEvictor.create(conf); PageStore pageStore = PageStore.create(conf); try { Collection<PageInfo> pageInfos = pageStore.getPages(); LOG.info("Loading existing pages", pageInfos.size()); for (PageInfo pageInfo : pageInfos) { PageId pageId = pageInfo.getPageId(); metaStore.addPage(pageId, pageInfo); evictor.updateOnPut(pageId); } return new LocalCacheManager(conf, metaStore, pageStore, evictor); } catch (Exception e) { try { pageStore.close(); } catch (Exception ex) { e.addSuppressed(ex); } throw new IOException("failed to create local cache manager", e); } }

Target:
public static LocalCacheManager create(AlluxioConfiguration conf) throws IOException { MetaStore metaStore = MetaStore.create(); CacheEvictor evictor = CacheEvictor.create(conf); PageStore pageStore = PageStore.create(conf); try { Collection<PageInfo> pageInfos = pageStore.getPages(); LOG.info("Creating LocalCacheManager with existing pages", pageInfos.size()); for (PageInfo pageInfo : pageInfos) { PageId pageId = pageInfo.getPageId(); metaStore.addPage(pageId, pageInfo); evictor.updateOnPut(pageId); } return new LocalCacheManager(conf, metaStore, pageStore, evictor); } catch (Exception e) { try { pageStore.close(); } catch (Exception ex) { e.addSuppressed(ex); } throw new IOException("failed to create local cache manager", e); } }
Source:
private static void createOrDropTrigger(Connection conn, String schema, String table, boolean create) throws SQLException { try (Statement stat = conn.createStatement()) { String trigger = StringUtils.quoteIdentifier(schema) + "." + StringUtils.quoteIdentifier(TRIGGER_PREFIX + table); stat.execute("DROP TRIGGER IF EXISTS " + trigger); if (create) { ResultSet rs = stat.executeQuery("SELECT value FROM information_schema.settings WHERE name = 'MV_STORE'"); boolean multiThread = FullTextTrigger.isMultiThread(conn); StringBuilder buff = new StringBuilder("CREATE TRIGGER IF NOT EXISTS "); buff.append(trigger). append(" AFTER INSERT, UPDATE, DELETE"); if(!multiThread) { buff.append(", ROLLBACK"); } buff.append(" ON "). append(StringUtils.quoteIdentifier(schema)). append('.'). append(StringUtils.quoteIdentifier(table)). append(" FOR EACH ROW CALL \""). append(FullText.FullTextTrigger.class.getName()). append('\"'); stat.execute(buff.toString()); } } }

Target:
private static void createOrDropTrigger(Connection conn, String schema, String table, boolean create) throws SQLException { try (Statement stat = conn.createStatement()) { String trigger = StringUtils.quoteIdentifier(schema) + "." + StringUtils.quoteIdentifier(TRIGGER_PREFIX + table); stat.execute("DROP TRIGGER IF EXISTS " + trigger); if (create) { boolean multiThread = FullTextTrigger.isMultiThread(conn); StringBuilder buff = new StringBuilder( "CREATE TRIGGER IF NOT EXISTS "); buff.append(trigger). append(" AFTER INSERT, UPDATE, DELETE"); if(!multiThread) { buff.append(", ROLLBACK"); } buff.append(" ON "). append(StringUtils.quoteIdentifier(schema)). append('.'). append(StringUtils.quoteIdentifier(table)). append(" FOR EACH ROW CALL \""). append(FullText.FullTextTrigger.class.getName()). append('\"'); stat.execute(buff.toString()); } } }
Source:
public void getNormilizedStringWithoutDashInTheEnd() { String input = RandomStringUtils.random(61, true, true) + "-"; String output = KubernetesStringUtils.getNormalizedString(input); assertTrue(!output.endsWith("-"), "Normilized string can not end with '-'"); }

Target:
public void getNormilizedStringWithoutDashInTheEnd() { String input = RandomStringUtils.random(61, true, true) + "-"; String output = KubernetesStringUtils.getNormalizedString(input); assertTrue(!output.endsWith("-"), "Normalized string can not end with '-'"); }
Source:
public static void validateZipOutputFile(String sourceFilename, final File outFile, final File outDir) throws IOException { final File canonicalOutFile = outFile.getCanonicalFile(); final String canonicalOutDir = outDir.getCanonicalPath(); if (!canonicalOutFile.toPath().startsWith(canonicalOutDir)) { throw new ISE( "Unzipped output path[%s] of sourceFile[%s] does not start with outDir[%s].", canonicalOutFile, sourceFilename, outDir ); } }

Target:
public static void validateZipOutputFile( String sourceFilename, final File outFile, final File outDir ) throws IOException { final File canonicalOutFile = outFile.getCanonicalFile(); final String canonicalOutDir = outDir.getCanonicalPath(); if (!canonicalOutFile.toPath().startsWith(canonicalOutDir)) { throw new ISE( "Unzipped output path[%s] of sourceFile[%s] does not start with outDir[%s].", canonicalOutFile, sourceFilename, canonicalOutDir ); } }
Source:
public static void main(String[] args) { String projectId = "your-project"; String member = "your-member"; String role = "roles/logging.logWriter"; CloudResourceManager crmService = null; try { crmService = initializeService(); } catch (IOException | GeneralSecurityException e) { System.out.println("Unable to initialize service: \n" + e.toString()); } addBinding(crmService, projectId, member, role); Policy policy = getPolicy(crmService, projectId); Binding binding = null; List<Binding> bindings = policy.getBindings(); for (Binding b : bindings) { if (b.getRole().equals(role)) { binding = b; break; } } System.out.println("Role: " + binding.getRole()); System.out.print("Members: "); for (String m : binding.getMembers()) { System.out.print("[" + m + "] "); } System.out.println(); removeMember(crmService, projectId, member, role); }

Target:
public static void main(String[] args) { String projectId = "your-project"; String member = "your-member"; String role = "roles/logging.logWriter"; CloudResourceManager crmService = null; try { crmService = initializeService(); } catch (IOException | GeneralSecurityException e) { System.out.println("Unable to initialize service: \n" + e.getMessage() + e.getStackTrace()); } addBinding(crmService, projectId, member, role); Policy policy = getPolicy(crmService, projectId); Binding binding = null; List<Binding> bindings = policy.getBindings(); for (Binding b : bindings) { if (b.getRole().equals(role)) { binding = b; break; } } System.out.println("Role: " + binding.getRole()); System.out.print("Members: "); for (String m : binding.getMembers()) { System.out.print("[" + m + "] "); } System.out.println(); removeMember(crmService, projectId, member, role); }
Source:
public boolean isEnableTestModeButtonVisible() { boolean isButtonVisible = false; try { wait.forElementVisible(enableTestModeButton, 5, 1); isButtonVisible = true; } catch (TimeoutException exception) { isButtonVisible = false; } return isModuleVisible() && isButtonVisible; }

Target:
public boolean isEnableTestModeButtonVisible() { boolean isButtonVisible = false; try { wait.forElementVisible(enableTestModeButton, 5, 1); isButtonVisible = true; } catch (TimeoutException e) { isButtonVisible = false; } return isModuleVisible() && isButtonVisible; }
Source:
private static Seq<Long> tenDigitPandigitalsWithProperty() { final CharSeq ALL_DIGITS = CharSeq.of("0123456789"); final List<Integer> DIVISORS = List.of(2, 3, 5, 7, 11, 13, 17); return ALL_DIGITS .combinations(2) .flatMap(CharSeq::permutations) .flatMap(firstTwoDigits -> DIVISORS .foldLeft(List.of(firstTwoDigits), (accumulator, divisor) -> accumulator .flatMap(digitsSoFar -> ALL_DIGITS .removeAll(digitsSoFar) .map(nextDigit -> digitsSoFar.append(nextDigit)) ) .filter(digitsToTest -> Integer.valueOf(digitsToTest.takeRight(3).mkString()) % divisor == 0) ) ) .map(tailDigitsWithProperty -> tailDigitsWithProperty .prepend(ALL_DIGITS .removeAll(tailDigitsWithProperty) .head() ) ) .map(CharSeq::mkString) .map(Long::valueOf); }

Target:
private static Seq<Long> tenDigitPandigitalsWithProperty() { final CharSeq ALL_DIGITS = CharSeq.of("0123456789"); final List<Integer> DIVISORS = List.of(2, 3, 5, 7, 11, 13, 17); return ALL_DIGITS .combinations(2) .flatMap(CharSeq::permutations) .flatMap(firstTwoDigits -> DIVISORS .foldLeft(List.of(firstTwoDigits), (accumulator, divisor) -> accumulator .flatMap(digitsSoFar -> ALL_DIGITS .removeAll(digitsSoFar) .map(nextDigit -> digitsSoFar.append(nextDigit)) ) .filter(digitsToTest -> digitsToTest.takeRight(3).parseInt() % divisor == 0) ) ) .map(tailDigitsWithProperty -> tailDigitsWithProperty .prepend(ALL_DIGITS .removeAll(tailDigitsWithProperty) .head() ) ) .map(CharSeq::parseLong); }
Source:
public void execute(DelegateExecution execution) throws Exception { final Pool pool = (Pool) execution.getVariable(CoreProcessVariables.POOL); @SuppressWarnings("unchecked") List<Machine> machines = (List<Machine>) execution.getVariable(CoreProcessVariables.MACHINES); checkNotNull(machines, "expecting to find the list of machines as process variable"); processEngine.getIdentityService().setAuthenticatedUserId("kermit"); List<String> processIds = Lists.newArrayList(); for (Machine machine : machines) { final String businessKey = String.format("%s-%s-%s", execution.getProcessBusinessKey(), type, machine.getExternalId()); ProcessInstance instance = processEngine.getRuntimeService().startProcessInstanceByKey( processKey, businessKey, ImmutableMap.<String, Object>of(CoreProcessVariables.POOL, pool, "machine", machine)); LOG.info("Started background '" + type + "' process ({}) for machine {}", new Object[]{businessKey, instance.getId(), machine.getExternalId()}); processIds.add(instance.getId()); } LOG.info("Saving process IDs as {}", processIds, resultVariable); execution.setVariable(resultVariable, processIds); }

Target:
public void execute(DelegateExecution execution) throws Exception { final Pool pool = (Pool) execution.getVariable(CoreProcessVariables.POOL); @SuppressWarnings("unchecked") List<Machine> machines = (List<Machine>) execution.getVariable(CoreProcessVariables.MACHINES); checkNotNull(machines, "expecting to find the list of machines as process variable"); processEngine.getIdentityService().setAuthenticatedUserId(CoreConstants.ACTIVITI_EXPLORER_DEFAULT_USER); List<String> processIds = Lists.newArrayList(); for (Machine machine : machines) { final String businessKey = String.format("%s-%s-%s", execution.getProcessBusinessKey(), type, machine.getExternalId()); ProcessInstance instance = processEngine.getRuntimeService().startProcessInstanceByKey( processKey, businessKey, ImmutableMap.<String, Object>of(CoreProcessVariables.POOL, pool, "machine", machine)); LOG.info("Started background '" + type + "' process ({}) for machine {}", new Object[]{businessKey, instance.getId(), machine.getExternalId()}); processIds.add(instance.getId()); } LOG.info("Saving process IDs as {}", processIds, resultVariable); execution.setVariable(resultVariable, processIds); }
Source:
public static void testPatchLineOfCredit() throws MambuApiException{ String methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println("\nIn " + methodName); LinesOfCreditService linesOfCreditService = MambuAPIFactory.getLineOfCreditService(); final String clientId = DemoUtil.getDemoClient().getId(); List<LineOfCredit> clientLoCs = linesOfCreditService.getClientLinesOfCredit(clientId, 0, 5); System.out.println(clientLoCs.size() + " lines of credit for Client " + clientId); if(clientLoCs.isEmpty() && clientLoCs.get(0) == null){ System.out.println("WARNING: " + methodName + " could not be tested because there are no LoCs to be patched"); }else{ LineOfCredit lineOfCredit = clientLoCs.get(0); Calendar patchDate = Calendar.getInstance(); lineOfCredit.setId("LOC" + System.currentTimeMillis()); patchDate.add(Calendar.DAY_OF_MONTH, 1); lineOfCredit.setStartDate(patchDate.getTime()); patchDate.add(Calendar.YEAR, 2); lineOfCredit.setExpiryDate(patchDate.getTime()); lineOfCredit.setAmount(lineOfCredit.getAmount().add(new Money("5000"))); lineOfCredit.setNotes("Note updated through APIs today " + new Date()); boolean booleanResult = linesOfCreditService.patchLinesOfCredit(lineOfCredit.getEncodedKey(), lineOfCredit); System.out.println("PATCH LoC result is = " + booleanResult); lineOfCredit = linesOfCreditService.getLineOfCredit(lineOfCredit.getEncodedKey()); logLineOfCreditDetails(lineOfCredit); } }

Target:
public static void testPatchLineOfCredit() throws MambuApiException{ String methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println("\nIn " + methodName); LinesOfCreditService linesOfCreditService = MambuAPIFactory.getLineOfCreditService(); final String clientId = DemoUtil.getDemoClient().getId(); List<LineOfCredit> clientLoCs = linesOfCreditService.getClientLinesOfCredit(clientId, 0, 5); System.out.println(clientLoCs.size() + " lines of credit for Client " + clientId); if(clientLoCs.isEmpty() || clientLoCs.get(0) == null){ System.out.println("WARNING: " + methodName + " could not be tested because there are no LoCs to be patched"); }else{ LineOfCredit lineOfCredit = clientLoCs.get(0); Calendar patchDate = Calendar.getInstance(); lineOfCredit.setId("LOC" + System.currentTimeMillis()); patchDate.add(Calendar.DAY_OF_MONTH, 1); lineOfCredit.setStartDate(patchDate.getTime()); patchDate.add(Calendar.YEAR, 2); lineOfCredit.setExpiryDate(patchDate.getTime()); lineOfCredit.setAmount(lineOfCredit.getAmount().add(new Money("5000"))); lineOfCredit.setNotes("Note updated through APIs today " + new Date()); boolean patchResult = linesOfCreditService.patchLinesOfCredit(lineOfCredit); System.out.println("PATCH LoC result is = " + patchResult); lineOfCredit = linesOfCreditService.getLineOfCredit(lineOfCredit.getEncodedKey()); logLineOfCreditDetails(lineOfCredit); } }
Source:
public HashSet<String> getDomainHosts() throws Exception{ HashSet<String> hosts = new HashSet<String>(); readRootNode(); if (rootNode.isDefined()) if (rootNode.get("host").isDefined()){ List<ModelNode> listNodes = rootNode.get("host").asList(); for (ModelNode listNode : listNodes) { hosts.add(listNode.keys().toString()); } } return hosts; }

Target:
public Set<String> getDomainHosts() throws Exception{ Set<String> hosts = new HashSet<String>(); readRootNode(); if (rootNode.isDefined()) if (rootNode.hasDefined("host")) hosts.addAll(rootNode.get("host").keys()); return hosts; }
Source:
public void checkConstraintRule( ConstraintRule rule, DynamicRecord record, RecordAccess records, CheckerEngine<DynamicRecord,ConsistencyReport.SchemaConsistencyReport> engine ) { checkSchema( rule, record, records, engine ); if ( rule.getConstraintDescriptor().type().enforcesUniqueness() ) { DynamicRecord previousObligation = indexObligations.put( rule.getOwnedIndex(), record.clone() ); if ( previousObligation != null ) { engine.report().duplicateObligation( previousObligation ); } } }

Target:
public void checkConstraintRule( ConstraintRule rule, DynamicRecord record, RecordAccess records, CheckerEngine<DynamicRecord,ConsistencyReport.SchemaConsistencyReport> engine ) { checkSchema( rule, record, records, engine ); if ( rule.getConstraintDescriptor().enforcesUniqueness() ) { DynamicRecord previousObligation = indexObligations.put( rule.getOwnedIndex(), record.clone() ); if ( previousObligation != null ) { engine.report().duplicateObligation( previousObligation ); } } }
Source:
public CloseableIterator<R> iterator() { if (stream == null) { return removableIterator(Closeables.iterator(getOrCreateStream())); } else { return Closeables.iterator(getOrCreateStream()); } }

Target:
public CloseableIterator<R> iterator() { if (stream == null) { return removableIterator(Closeables.iterator(createStream())); } else { return Closeables.iterator(stream); } }
Source:
public OperatingSystemToOperatingSystem(final OperatingSystemToOsFamily operatingSystemToOsFamily) { this.operatingSystemToOsFamily = operatingSystemToOsFamily; }

Target:
OperatingSystemToOperatingSystem(final OperatingSystemToOsFamily operatingSystemToOsFamily) { this.operatingSystemToOsFamily = operatingSystemToOsFamily; }
Source:
public void setupTest() throws Exception { this.mockQuery = Mockito.mock(Query.class); this.mockResult = Mockito.mock(Result.class); this.mockDgSocket = Mockito.mock(DatagramSocket.class); this.mockLog = Mockito.mock(Logger.class); this.mockServer = Mockito.mock(Server.class); PowerMockito.whenNew(DatagramSocket.class).withAnyArguments().thenReturn(this.mockDgSocket); testValues = ImmutableMap.<String, Object>of("x-att1-x", "120021"); Mockito.when(this.mockResult.getValues()).thenReturn(testValues); Mockito.when(this.mockResult.getAttributeName()).thenReturn("X-ATT-X"); Mockito.when(this.mockResult.getClassName()).thenReturn("X-DOMAIN.PKG.CLASS-X"); Mockito.when(this.mockResult.getTypeName()).thenReturn("Type=x-type-x"); Mockito.when(this.mockServer.getLabel()).thenReturn("myhostname"); Map<String, Object> settings = newHashMap(); settings.put("host", "localhost"); settings.put("port", 8923); this.writer = TCollectorUDPWriter.builder() .setDebugEnabled(false) .setHost("localhost") .setPort(1234) .build(); Whitebox.setInternalState(TCollectorUDPWriter.class, Logger.class, this.mockLog); }

Target:
public void setupTest() throws Exception { this.mockQuery = Mockito.mock(Query.class); this.mockResult = Mockito.mock(Result.class); this.mockDgSocket = Mockito.mock(DatagramSocket.class); this.mockLog = Mockito.mock(Logger.class); PowerMockito.whenNew(DatagramSocket.class).withAnyArguments().thenReturn(this.mockDgSocket); testValues = ImmutableMap.<String, Object>of("x-att1-x", "120021"); Mockito.when(this.mockResult.getValues()).thenReturn(testValues); Mockito.when(this.mockResult.getAttributeName()).thenReturn("X-ATT-X"); Mockito.when(this.mockResult.getClassName()).thenReturn("X-DOMAIN.PKG.CLASS-X"); Mockito.when(this.mockResult.getTypeName()).thenReturn("Type=x-type-x"); Map<String, Object> settings = newHashMap(); settings.put("host", "localhost"); settings.put("port", 8923); this.writer = TCollectorUDPWriter.builder() .setDebugEnabled(false) .setHost("localhost") .setPort(1234) .build(); Whitebox.setInternalState(TCollectorUDPWriter.class, Logger.class, this.mockLog); }
Source:
public List<SimplePage> getSitePages(String siteId) { DetachedCriteria d = DetachedCriteria.forClass(SimplePage.class).add(Restrictions.eq("siteId", siteId)) .add(Restrictions.disjunction() .add(Restrictions.isNull("owner")) .add(Restrictions.conjunction().add(Restrictions.isNotNull("owner")).add(Restrictions.eq("owned", true))) ); List<SimplePage> l = (List<SimplePage>) getHibernateTemplate().findByCriteria(d); if (l != null && l.size() > 0) { return l; } else { return null; } }

Target:
public List<SimplePage> getSitePages(String siteId) { DetachedCriteria d = DetachedCriteria.forClass(SimplePage.class).add(Restrictions.eq("siteId", siteId)) .add(Restrictions.disjunction() .add(Restrictions.isNull("owner")) .add(Restrictions.eq("owned", true)) ); List<SimplePage> l = (List<SimplePage>) getHibernateTemplate().findByCriteria(d); if (l != null && l.size() > 0) { return l; } else { return null; } }
Source:
private void decrementLatchAndHandle(int count) { if (latch.addAndGet(-count) > 0) { return; } Map<Integer, Object> result = createHashMap(partitionResults.length()); for (int partitionId = 0; partitionId < partitionResults.length(); partitionId++) { Object partitionResult = partitionResults.get(partitionId); if (partitionResult instanceof Throwable) { future.setResult(partitionResult); if (callback != null) { callback.onFailure((Throwable) partitionResult); } return; } if (partitionResult != null) { result.put(partitionId, partitionResult == NULL_RESULT ? null : partitionResult); } } future.setResult(result); if (callback != null) { callback.onResponse(result); } }

Target:
private void decrementLatchAndHandle(int count) { if (latch.addAndGet(-count) > 0) { return; } Map<Integer, Object> result = createHashMap(partitionResults.length()); for (int partitionId = 0; partitionId < partitionResults.length(); partitionId++) { Object partitionResult = partitionResults.get(partitionId); if (partitionResult instanceof Throwable) { future.setResult(partitionResult); return; } if (partitionResult != null) { result.put(partitionId, partitionResult == NULL_RESULT ? null : partitionResult); } } future.setResult(result); }
Source:
public void test() { DepositTestUtils.makeTestDir(depositsDirectory, job.getDepositUUID(), new File("src/test/resources/biomedDspaceMETS.zip")); long start = System.currentTimeMillis(); job.run(); log.info("Run dspace mets: {}", (System.currentTimeMillis() - start)); Model model = job.getWritableModel(); assertFalse("Model was empty", model.isEmpty()); Bag depositBag = model.getBag(job.getDepositPID().getURI()); assertNotNull("Deposit object not found", depositBag); Resource primaryResource = (Resource) depositBag.iterator().next(); assertNotNull("Main object from the deposit not found", primaryResource); NodeIterator childIt = model.getBag(primaryResource).iterator(); int childCount = 0; while (childIt.hasNext()) { childCount++; Resource child = (Resource) childIt.next(); verifyStagingLocationExists(child, job.getDepositDirectory(), "Child content"); } assertEquals("Incorrect aggregate child count", 5, childCount); }

Target:
public void test() { DepositTestUtils.makeTestDir(depositsDirectory, job.getDepositUUID(), new File("src/test/resources/biomedDspaceMETS.zip")); long start = System.currentTimeMillis(); job.run(); log.info("Run dspace mets: {}", (System.currentTimeMillis() - start)); Model model = job.getWritableModel(); assertFalse("Model was empty", model.isEmpty()); Bag depositBag = model.getBag(job.getDepositPID().getURI()); assertNotNull("Deposit object not found", depositBag); Resource primaryResource = (Resource) depositBag.iterator().next(); assertNotNull("Main object from the deposit not found", primaryResource); assertTrue("Main object is not a work", primaryResource.hasProperty(RDF.type, Cdr.Work)); NodeIterator childIt = model.getBag(primaryResource).iterator(); int childCount = 0; while (childIt.hasNext()) { childCount++; Resource child = (Resource) childIt.next(); verifyStagingLocationExists(child, job.getDepositDirectory(), "Child content"); } assertEquals("Incorrect aggregate child count", 5, childCount); }
Source:
public ActivityLogEntry(String servlet, String act, AccountAttributes acc, String params, String link, String unregisteredUserCourse, String unregisteredUserEmail) { time = System.currentTimeMillis(); servletName = servlet; action = act; toShow = true; message = params; url = link; if (acc == null){ role = "Unknown"; name = "Unknown"; email = "Unknown"; UserType userType = GateKeeper.inst().getCurrentUser(); googleId = userType != null ? userType.id : "Unknown"; } else { role = acc.isInstructor ? "Instructor" : "Student"; name = acc.name; googleId = acc.googleId; email = acc.email; } if (googleId.contentEquals("Unknown") && unregisteredUserCourse != null && unregisteredUserEmail != null) { id = unregisteredUserEmail + "%" + unregisteredUserCourse + "%" + formatTimeForId(new Date(time)); } else { id = googleId + formatTimeForId(new Date(time)); } role = changeRoleToAutoIfAutomatedActions(servletName, role); }

Target:
public ActivityLogEntry(String servlet, String act, AccountAttributes acc, String params, String link, String unregisteredUserCourse, String unregisteredUserEmail) { time = System.currentTimeMillis(); servletName = servlet; action = act; toShow = true; message = params; url = link; if (acc == null){ role = "Unknown"; name = "Unknown"; email = "Unknown"; UserType userType = GateKeeper.inst().getCurrentUser(); googleId = userType != null ? userType.id : "Unknown"; } else { role = acc.isInstructor ? "Instructor" : "Student"; name = acc.name; googleId = acc.googleId; email = acc.email; } boolean isUnregisteredStudent = googleId.contentEquals("Unknown") && unregisteredUserCourse != null && unregisteredUserEmail != null; if (isUnregisteredStudent) { id = unregisteredUserEmail + "%" + unregisteredUserCourse + "%" + formatTimeForId(new Date(time)); } else { id = googleId + "%" + formatTimeForId(new Date(time)); } role = changeRoleToAutoIfAutomatedActions(servletName, role); }
Source:
protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Context ctx = getApplicationContext(); final PackageManager packageManager = ctx.getPackageManager(); hasLocationFeature = packageManager.hasSystemFeature(PackageManager.FEATURE_LOCATION) || packageManager.hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS) || packageManager.hasSystemFeature(PackageManager.FEATURE_LOCATION_NETWORK); this.locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); this.marker_icon = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.marker); final Boolean dark = PreferenceManager.getDefaultSharedPreferences(ctx) .getString("theme", "light").equals("dark"); final int mTheme = dark ? R.style.ConversationsTheme_Dark : R.style.ConversationsTheme; setTheme(mTheme); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && savedInstanceState == null) { requestPermissions(REQUEST_CODE_CREATE); } final IConfigurationProvider config = Configuration.getInstance(); config.load(ctx, getPreferences()); config.setUserAgentValue(BuildConfig.APPLICATION_ID + "_" + BuildConfig.VERSION_CODE); final File f = new File(ctx.getCacheDir() + "/tiles"); try { f.mkdirs(); } catch (final SecurityException ignored) { } if (f.exists() && f.isDirectory() && f.canRead() && f.canWrite()) { Log.d(Config.LOGTAG, "Using tile cache at: " + f.getAbsolutePath()); config.setOsmdroidTileCache(f.getAbsoluteFile()); } }

Target:
protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Context ctx = getApplicationContext(); setTheme(ThemeHelper.find(this)); final PackageManager packageManager = ctx.getPackageManager(); hasLocationFeature = packageManager.hasSystemFeature(PackageManager.FEATURE_LOCATION) || packageManager.hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS) || packageManager.hasSystemFeature(PackageManager.FEATURE_LOCATION_NETWORK); this.locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); this.marker_icon = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.marker); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && savedInstanceState == null) { requestPermissions(REQUEST_CODE_CREATE); } final IConfigurationProvider config = Configuration.getInstance(); config.load(ctx, getPreferences()); config.setUserAgentValue(BuildConfig.APPLICATION_ID + "_" + BuildConfig.VERSION_CODE); final File f = new File(ctx.getCacheDir() + "/tiles"); try { f.mkdirs(); } catch (final SecurityException ignored) { } if (f.exists() && f.isDirectory() && f.canRead() && f.canWrite()) { Log.d(Config.LOGTAG, "Using tile cache at: " + f.getAbsolutePath()); config.setOsmdroidTileCache(f.getAbsoluteFile()); } }