auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void onClone() { ImportCloneModel cloneModel = (ImportCloneModel) getConfirmWindow(); if ((Boolean) cloneModel.getApplyToAll().getEntity()) { if (!(Boolean) cloneModel.getNoClone().getEntity()) { String suffix = (String) cloneModel.getSuffix().getEntity(); if (!validateSuffix(suffix, cloneModel.getSuffix())) { return; } for (VM vm : vmsInSetupMap.values()) { vm.setvm_name(vm.getvm_name() + suffix); cloneVmMap.put(vm.getId(), vm); } } vmsInSetupMap.clear(); } else { VM vm = (VM) cloneModel.getEntity(); if (!(Boolean) cloneModel.getNoClone().getEntity()) { String vmName = (String) cloneModel.getName().getEntity(); if (!validateVmName(vmName, vm.getos(), cloneModel.getName())) { return; } vm.setvm_name(vmName); cloneVmMap.put(vm.getId(), vm); } vmsInSetupMap.remove(vm.getId()); } setConfirmWindow(null); excuteImportClone(); }

Target:
private void onClone() { ImportCloneModel cloneModel = (ImportCloneModel) getConfirmWindow(); if ((Boolean) cloneModel.getApplyToAll().getEntity()) { if (!(Boolean) cloneModel.getNoClone().getEntity()) { String suffix = (String) cloneModel.getSuffix().getEntity(); if (!validateSuffix(suffix, cloneModel.getSuffix())) { return; } for (VM vm : vmsInSetupMap.values()) { vm.setvm_name(vm.getvm_name() + suffix); cloneVmMap.put(vm.getId(), vm); } } vmsInSetupMap.clear(); } else { VM vm = (VM) cloneModel.getEntity(); if (!(Boolean) cloneModel.getNoClone().getEntity()) { String vmName = (String) cloneModel.getName().getEntity(); if (!validateVmName(vmName, vm.getos(), cloneModel.getName())) { return; } vm.setvm_name(vmName); cloneVmMap.put(vm.getId(), vm); } vmsInSetupMap.remove(vm.getId()); } setConfirmWindow(null); executeImportClone(); }
Source:
protected void signalRMCoreIsInitialized() { rmCoreInitializedLock.lock(); try { rmCoreInitialized = true; logger.info("Resource Manager is initialized"); rmCoreInitializedCondition.signalAll(); } finally { rmCoreInitializedLock.unlock(); } }

Target:
protected void signalRMCoreIsInitialized() { logger.info("Resource Manager is initialized"); countDownLatch.countDown(); }
Source:
public void createNewTemplate(Template template) { if (isTitleValid(template)) { try { Converter converter = new Converter(template.getWorkflow().getTitle()); converter.convertWorkflowToTemplate(template); } catch (IOException | DAOException | WorkflowException e) { Helper.setErrorMessage(ERROR_SAVING, new Object[]{ObjectType.PROCESS.getTranslationSingular()}, logger, e); } List<Process> processesToAddToTemplate = templatesToCreate.get(template); try { ServiceManager.getTemplateService().save(template); } catch (DataException e) { Helper.setErrorMessage(ERROR_SAVING, new Object[]{ObjectType.TEMPLATE.getTranslationSingular()}, logger, e); } try { migrationService.addProcessesToTemplate(template, processesToAddToTemplate); } catch (DataException e) { Helper.setErrorMessage(ERROR_SAVING, new Object[]{ObjectType.PROCESS.getTranslationSingular()}, logger, e); } templatesToCreate.remove(template); } }

Target:
public void createNewTemplate(Template template) { if (migrationService.isTitleValid(template)) { try { Converter converter = new Converter(template.getWorkflow().getTitle()); converter.convertWorkflowToTemplate(template); } catch (IOException | DAOException | WorkflowException e) { Helper.setErrorMessage(ERROR_SAVING, new Object[]{ObjectType.PROCESS.getTranslationSingular()}, logger, e); } List<Process> processesToAddToTemplate = templatesToCreate.get(template); try { ServiceManager.getTemplateService().save(template); } catch (DataException e) { Helper.setErrorMessage(ERROR_SAVING, new Object[]{ObjectType.TEMPLATE.getTranslationSingular()}, logger, e); } try { migrationService.addProcessesToTemplate(template, processesToAddToTemplate); } catch (DataException e) { Helper.setErrorMessage(ERROR_SAVING, new Object[]{ObjectType.PROCESS.getTranslationSingular()}, logger, e); } templatesToCreate.remove(template); } }
Source:
DirectClassFile getClass(String path) throws FileNotFoundException { DirectClassFile classFile = null; for (ClassPathElement element : elements) { try { InputStream in = element.open(path); try { byte[] bytes = readStream(in, baos, readBuffer); baos.reset(); classFile = new DirectClassFile(bytes, path, false); classFile.setAttributeFactory(StdAttributeFactory.THE_ONE); break; } finally { in.close(); } } catch (IOException e) { } } if (classFile == null) { throw new FileNotFoundException(path); } return classFile; }

Target:
synchronized DirectClassFile getClass(String path) throws FileNotFoundException { DirectClassFile classFile = null; for (ClassPathElement element : elements) { try { InputStream in = element.open(path); try { byte[] bytes = readStream(in, baos, readBuffer); baos.reset(); classFile = new DirectClassFile(bytes, path, false); classFile.setAttributeFactory(StdAttributeFactory.THE_ONE); break; } finally { in.close(); } } catch (IOException e) { } } if (classFile == null) { throw new FileNotFoundException("File \"" + path + "\" not found"); } return classFile; }
Source:
private void createAndRegisterResources() { registerPaxosResource(); registerExceptionMappers(); Map<String, TimeLockServices> services = new ConcurrentHashMap<>(); Function<String, TimeLockServices> timelockServices = namespace -> services.computeIfAbsent( namespace, this::createInvalidatingTimeLockServices); resource = TimeLockResource.create( metricsManager, timelockServices, Suppliers.compose(TimeLockRuntimeConfiguration::maxNumberOfClients, runtime::get)); healthCheck = paxosResources.leadershipComponents().healthCheck(resource::getActiveClients); LockWatchTestingService.create( Suppliers.compose(TimeLockRuntimeConfiguration::lockWatchTestConfig, runtime::get), resource::getLockWatchingResource); registrar.accept(resource); Function<String, AsyncTimelockService> serviceCreator = namespace -> timelockServices.apply(namespace).getTimelockService(); if (undertowRegistrar.isPresent()) { undertowRegistrar.get().accept(ConjureTimelockResource.undertow(redirectRetryTargeter(), serviceCreator)); } else { registrar.accept(ConjureTimelockResource.jersey(redirectRetryTargeter(), serviceCreator)); } }

Target:
private void createAndRegisterResources() { registerPaxosResource(); registerExceptionMappers(); namespaces = new TimelockNamespaces( metricsManager, this::createInvalidatingTimeLockServices, Suppliers.compose(TimeLockRuntimeConfiguration::maxNumberOfClients, runtime::get)); TimeLockResource resource = TimeLockResource.create(namespaces); healthCheck = paxosResources.leadershipComponents().healthCheck(namespaces::getActiveClients); LockWatchTestingService.create( Suppliers.compose(TimeLockRuntimeConfiguration::lockWatchTestConfig, runtime::get), resource::getLockWatchingResource); registrar.accept(resource); Function<String, AsyncTimelockService> serviceCreator = namespace -> namespaces.get(namespace).getTimelockService(); if (undertowRegistrar.isPresent()) { undertowRegistrar.get().accept(ConjureTimelockResource.undertow(redirectRetryTargeter(), serviceCreator)); } else { registrar.accept(ConjureTimelockResource.jersey(redirectRetryTargeter(), serviceCreator)); } }
Source:
public ForkedServer start() { boolean isServerStarted; ProcessBuilder pb = new ProcessBuilder(); pb.command(commands); try { process = pb.start(); isServerStarted = runWithTimeout(this::checkServerLog, START_PATTERN); if (!isServerStarted) { throw new IllegalStateException("The server couldn't start"); } } catch (Exception e) { log.error(e); } log.info("SERVER STARTED!"); return this; }

Target:
public ForkedServer start() { boolean isServerStarted; ProcessBuilder pb = new ProcessBuilder(); pb.command(commands); try { process = pb.start(); isServerStarted = runWithTimeout(this::checkServerLog, START_PATTERN); if (!isServerStarted) { throw new IllegalStateException("The server couldn't start"); } } catch (Exception e) { log.error(e); } return this; }
Source:
public void onChanLoaderData(ChanThread result) { if (isWatching()) { chanLoader.setTimer(); } showPosts(); if (loadable.isThreadMode()) { boolean newPosts = false; int lastLoaded = loadable.lastLoaded; List<Post> posts = result.posts; List<PostImage> images = new ArrayList<>(); int more = 0; if (lastLoaded > 0) { for (int i = 0; i < posts.size(); i++) { Post post = posts.get(i); if(newPosts) { if(post.hasImage) { images.add(post.image); } } if (post.no == lastLoaded) { more = posts.size() - i - 1; newPosts = true; } } } loadable.setLastLoaded(posts.get(posts.size() - 1).no); if (more > 0) { threadPresenterCallback.showNewPostsNotification(true, more); if(images.size() > 0) { threadPresenterCallback.addImages(images, loadable); } } } if (loadable.markedNo >= 0) { Post markedPost = findPostById(loadable.markedNo); if (markedPost != null) { highlightPost(markedPost); scrollToPost(markedPost, false); } loadable.markedNo = -1; } addHistory(); }

Target:
public void onChanLoaderData(ChanThread result) { if (isWatching()) { chanLoader.setTimer(); } showPosts(); if (loadable.isThreadMode()) { boolean newPosts = false; int lastLoaded = loadable.lastLoaded; List<Post> posts = result.posts; List<PostImage> images = new ArrayList<>(); int more = 0; if (lastLoaded > 0) { for (int i = 0; i < posts.size(); i++) { Post post = posts.get(i); if(newPosts && post.hasImage) { images.add(post.image); } if (post.no == lastLoaded) { more = posts.size() - i - 1; newPosts = true; } } } loadable.setLastLoaded(posts.get(posts.size() - 1).no); if (more > 0) { threadPresenterCallback.showNewPostsNotification(true, more); if(images.size() > 0) { threadPresenterCallback.addImages(images, loadable); } } } if (loadable.markedNo >= 0) { Post markedPost = findPostById(loadable.markedNo); if (markedPost != null) { highlightPost(markedPost); scrollToPost(markedPost, false); } loadable.markedNo = -1; } addHistory(); }
Source:
public PrimitiveIterator.OfLong allRows() { return new PrimitiveIterator.OfLong() { private int actualRangeIndex = -1; private Range actualRange; private long next = findNext(); private long findNext() { if (actualRange == null || next + 1 > actualRange.to) { if (actualRangeIndex + 1 < ranges.size()) { actualRange = ranges.get(++actualRangeIndex); next = actualRange.from; } else { return -1; } } else { ++next; } return next; } @Override public boolean hasNext() { return next >= 0; } @Override public long nextLong() { long ret = next; if (ret < 0) { throw new NoSuchElementException(); } next = findNext(); return ret; } }; }

Target:
public PrimitiveIterator.OfLong allRows() { return new PrimitiveIterator.OfLong() { private int currentRangeIndex = -1; private Range currentRange; private long next = findNext(); private long findNext() { if (currentRange == null || next + 1 > currentRange.to) { if (currentRangeIndex + 1 < ranges.size()) { currentRange = ranges.get(++currentRangeIndex); next = currentRange.from; } else { return -1; } } else { ++next; } return next; } @Override public boolean hasNext() { return next >= 0; } @Override public long nextLong() { long ret = next; if (ret < 0) { throw new NoSuchElementException(); } next = findNext(); return ret; } }; }
Source:
public synchronized String registerProcessorAndGetId(final ProcessorData data) { final long startTime = System.currentTimeMillis(); final long retryTimeOutMs = 2 * sessionTimeoutMs; String processorId = data.getProcessorId(); if (ephemeralPath == null) { ephemeralPath = zkClient.createEphemeralSequential(keyBuilder.getProcessorsPath() + "/", data.toString()); LOG.info("Created ephemeral path: for processor: in zookeeper.", ephemeralPath, data); while (true) { ProcessorNode processorNode = new ProcessorNode(data, ephemeralPath); if (!isValidRegisteredProcessor(processorNode)) { long currentTime = System.currentTimeMillis(); if ((currentTime - startTime) < retryTimeOutMs) { LOG.info("Processor: is duplicate. Retrying registration again.", processorId); timeDelay(1000); } else { LOG.info("Processor: is duplicate. Deleting zookeeper node at path: {}.", processorId, ephemeralPath); zkClient.delete(ephemeralPath); metrics.deletions.inc(); throw new SamzaException(String.format("Processor: %s is duplicate in the group. Registration failed.", processorId)); } } else { break; } } } else { LOG.info("Ephemeral path: exists for processor: in zookeeper.", ephemeralPath, data); } return ephemeralPath; }

Target:
public synchronized String registerProcessorAndGetId(final ProcessorData data) { final long startTimeMs = System.currentTimeMillis(); final long retryTimeOutMs = 2 * sessionTimeoutMs; String processorId = data.getProcessorId(); if (ephemeralPath == null) { ephemeralPath = zkClient.createEphemeralSequential(keyBuilder.getProcessorsPath() + "/", data.toString()); LOG.info("Created ephemeral path: for processor: in zookeeper.", ephemeralPath, data); while (true) { ProcessorNode processorNode = new ProcessorNode(data, ephemeralPath); if (!isValidRegisteredProcessor(processorNode)) { long currentTimeMs = System.currentTimeMillis(); if ((currentTimeMs - startTimeMs) < retryTimeOutMs) { LOG.info("Processor: is duplicate. Retrying registration again.", processorId); timeDelay(5000); } else { LOG.info("Processor: is duplicate. Deleting zookeeper node at path: {}.", processorId, ephemeralPath); zkClient.delete(ephemeralPath); metrics.deletions.inc(); throw new SamzaException(String.format("Processor: %s is duplicate in the group. Registration failed.", processorId)); } } else { break; } } } else { LOG.info("Ephemeral path: exists for processor: in zookeeper.", ephemeralPath, data); } return ephemeralPath; }
Source:
public StreamingResponse apply(FileResource rsrc) throws ResourceNotFoundException, IOException { Project.NameKey project = rsrc.getRevision().getControl().getProject().getNameKey(); Repository repo = repoManager.openRepository(project); try { RevWalk rw = new RevWalk(repo); try { RevCommit commit = rw.parseCommit(ObjectId.fromString(rsrc.getRevision().getPatchSet() .getRevision().get())); TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(), rsrc.getPatchKey().get(), commit.getTree().getId()); if (tw == null) { throw new ResourceNotFoundException(); } try { final ObjectLoader loader = repo.open(tw.getObjectId(0)); return new StreamingResponse() { @Override public String getContentType() { return "text/plain;charset=UTF-8"; } @Override public void stream(OutputStream out) throws IOException { PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, Charsets.UTF_8)); try { loader.copyTo(BaseEncoding.base64().encodingStream(writer)); } finally { writer.flush(); } } }; } finally { tw.release(); } } finally { rw.release(); } } finally { repo.close(); } }

Target:
public StreamingResponse apply(FileResource rsrc) throws ResourceNotFoundException, IOException { Project.NameKey project = rsrc.getRevision().getControl().getProject().getNameKey(); Repository repo = repoManager.openRepository(project); try { RevWalk rw = new RevWalk(repo); try { RevCommit commit = rw.parseCommit(ObjectId.fromString(rsrc.getRevision().getPatchSet() .getRevision().get())); TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(), rsrc.getPatchKey().get(), commit.getTree().getId()); if (tw == null) { throw new ResourceNotFoundException(); } try { final ObjectLoader loader = repo.open(tw.getObjectId(0)); return new StreamingResponse() { @Override public String getContentType() { return "text/plain;charset=UTF-8"; } @Override public void stream(OutputStream out) throws IOException { OutputStream b64Out = BaseEncoding.base64().encodingStream( new OutputStreamWriter(out, Charsets.UTF_8)); loader.copyTo(b64Out); b64Out.close(); } }; } finally { tw.release(); } } finally { rw.release(); } } finally { repo.close(); } }
Source:
protected int rwInUnaryExpression(IASTNode node, IASTUnaryExpression expr, int indirection) { switch(expr.getOperator()) { case IASTUnaryExpression.op_bracketedPrimary: return rwAnyNode(expr, indirection); case IASTUnaryExpression.op_amper: return rwAnyNode(expr, indirection + 1); case IASTUnaryExpression.op_star: final IASTNode parent = expr.getParent(); if (parent instanceof IASTBinaryExpression && ((IASTBinaryExpression) parent).getOperator() == IASTBinaryExpression.op_assign) { return WRITE; } if (indirection > 0) { return rwAnyNode(expr, indirection - 1); } return READ; case IASTUnaryExpression.op_postFixDecr: case IASTUnaryExpression.op_postFixIncr: case IASTUnaryExpression.op_prefixDecr: case IASTUnaryExpression.op_prefixIncr: return READ | WRITE; case IASTUnaryExpression.op_minus: case IASTUnaryExpression.op_not: case IASTUnaryExpression.op_plus: case IASTUnaryExpression.op_tilde: return PDOMName.READ_ACCESS; case IASTUnaryExpression.op_sizeof: case IASTUnaryExpression.op_sizeofParameterPack: case IASTUnaryExpression.op_alignOf: return 0; } return READ; }

Target:
protected int rwInUnaryExpression(IASTNode node, IASTUnaryExpression expr, int indirection) { switch(expr.getOperator()) { case IASTUnaryExpression.op_bracketedPrimary: return rwAnyNode(expr, indirection); case IASTUnaryExpression.op_amper: return rwAnyNode(expr, indirection + 1); case IASTUnaryExpression.op_star: if (indirection > 0) { return rwAnyNode(expr, indirection - 1); } return READ; case IASTUnaryExpression.op_postFixDecr: case IASTUnaryExpression.op_postFixIncr: case IASTUnaryExpression.op_prefixDecr: case IASTUnaryExpression.op_prefixIncr: return READ | WRITE; case IASTUnaryExpression.op_minus: case IASTUnaryExpression.op_not: case IASTUnaryExpression.op_plus: case IASTUnaryExpression.op_tilde: return PDOMName.READ_ACCESS; case IASTUnaryExpression.op_sizeof: case IASTUnaryExpression.op_sizeofParameterPack: case IASTUnaryExpression.op_alignOf: return 0; } return READ; }
Source:
public Response intercept(Chain chain) throws IOException { Response response = chain.proceed(chain.request()); String hostName = chain.request().url().host(); HostMetrics metrics = hostMetrics.computeIfAbsent(hostName, host -> new HostMetrics(registry, name, host)); metrics.update(response.code()); return response; }

Target:
public Response intercept(Chain chain) throws IOException { Response response = chain.proceed(chain.request()); String hostname = chain.request().url().host(); hostMetrics.record(hostname, response.code()); return response; }
Source:
public int hashCode() { return getContent().hashCode(); }

Target:
public int hashCode() { return Objects.hashCode(getContent()); }
Source:
public BaseComponent[] getMessage() { if ( message == null ) { message = messageSupplier.get(); } return message; }

Target:
public synchronized BaseComponent[] getMessage() { if ( message != null ) { messageJson = null; return message; } if ( messageJson != null ) { message = ComponentSerializer.parse( messageJson ); messageJson = null; return message; } return null; }
Source:
public HostMetricsRegistry(MetricRegistry registry, String serviceName) { this.hostMetrics = CacheBuilder.newBuilder() .maximumSize(1_000) .build(new CacheLoader<String, HostMetrics>() { @Override public HostMetrics load(String hostname) throws Exception { return new HostMetrics(registry, serviceName, hostname); } }); }

Target:
public HostMetricsRegistry(MetricRegistry registry, String serviceName) { this.hostMetrics = CacheBuilder.newBuilder() .maximumSize(1_000) .expireAfterAccess(1, TimeUnit.DAYS) .build(new CacheLoader<String, HostMetrics>() { @Override public HostMetrics load(String hostname) throws Exception { return new HostMetrics(registry, serviceName, hostname); } }); }
Source:
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Choose interface (To choose command line type 'cl', to choose UI type 'ui'): "); System.out.flush(); String screen = scanner.nextLine(); if ("cl".equals(screen)) { System.out.print("Enter a file name: "); System.out.flush(); String filename = scanner.nextLine(); System.out.print("Enter character to seperate csv file: "); System.out.flush(); String splitBy = scanner.next(); csvToBitext(filename, splitBy, ""); } else if ("ui".equals(screen)) { JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("User Interface"); frame.setPreferredSize(new Dimension(400, 100)); frame.setLayout(new FlowLayout()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel text = new JLabel("Split words by:"); JTextField split = new JTextField(5); JButton btnFile = new JButton("Select Csv File"); JButton btnOk = new JButton("Ok"); JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); btnFile.addActionListener((ActionEvent ae) -> { jfc.setDialogTitle("Select csv file"); jfc.setAcceptAllFileFilterUsed(false); int returnValue = jfc.showOpenDialog(null); }); btnOk.addActionListener((ActionEvent ae) -> { csvToBitext(jfc.getSelectedFile().getPath(), split.getText(), ""); }); frame.add(btnFile); frame.add(text); frame.add(split); frame.add(btnOk); frame.pack(); frame.setVisible(true); } }

Target:
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Choose interface (To choose command line type 'cl', to choose UI type 'ui'): "); String screen = scanner.nextLine(); if ("cl".equals(screen)) { System.out.print("Enter a file name: "); String filename = scanner.nextLine(); System.out.print("Enter character to seperate csv file: "); String splitBy = scanner.next(); csvToBitext(filename, splitBy, ""); } else if ("ui".equals(screen)) { JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("User Interface"); frame.setPreferredSize(new Dimension(400, 100)); frame.setLayout(new FlowLayout()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel text = new JLabel("Split words by:"); JTextField split = new JTextField(5); JButton btnFile = new JButton("Select Csv File"); JButton btnOk = new JButton("Ok"); JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); btnFile.addActionListener((ActionEvent ae) -> { jfc.setDialogTitle("Select csv file"); jfc.setAcceptAllFileFilterUsed(false); int returnValue = jfc.showOpenDialog(null); }); btnOk.addActionListener((ActionEvent ae) -> { csvToBitext(jfc.getSelectedFile().getPath(), split.getText(), ""); }); frame.add(btnFile); frame.add(text); frame.add(split); frame.add(btnOk); frame.pack(); frame.setVisible(true); } }
Source:
public List<String> getZipsOlderThan(int daysAgo) throws Exception { List<String> out = new ArrayList<String>(); List<Long> hourKeysListL = new ArrayList<Long>(); List<String> dirComps = new ArrayList<String>(); String lbLogSplitDir = StaticFileUtils.mergePathString(HadoopLogsConfigs.getMapreduceOutputPrefix(), LB_LOGS_SPLIT); FileStatus[] dateDirsStats = getFileSystem().listStatus(new Path(lbLogSplitDir)); DateTime now = StaticDateTimeUtils.nowDateTime(true); Long daysAgoLong = StaticDateTimeUtils.dateTimeToHourLong( StaticDateTimeUtils.nowDateTime( true).minusDays(daysAgo)); for (FileStatus fileStatus : dateDirsStats) { Long hourLong; String pathStr; try { pathStr = HdfsUtils.pathTailString(fileStatus); hourLong = Long.parseLong(pathStr); if (hourLong < daysAgoLong) { hourKeysListL.add(hourLong); } } catch (Exception ex) { continue; } } Collections.sort(hourKeysListL); for (Long hourLong : hourKeysListL) { dirComps.clear(); dirComps.add(HadoopLogsConfigs.getMapreduceOutputPrefix()); dirComps.add(LB_LOGS_SPLIT); dirComps.add(hourLong.toString()); String pathStr = StaticFileUtils.splitPathToString(StaticFileUtils.joinPath(dirComps)); out.add(pathStr); } return out; }

Target:
public List<String> getZipsOlderThan(int daysAgo) throws Exception { List<String> out = new ArrayList<String>(); List<Long> hourKeysList = new ArrayList<Long>(); List<String> dirComps = new ArrayList<String>(); String lbLogSplitDir = StaticFileUtils.mergePathString(HadoopLogsConfigs.getMapreduceOutputPrefix(), LB_LOGS_SPLIT); FileStatus[] dateDirsStats = getFileSystem().listStatus(new Path(lbLogSplitDir)); DateTime now = StaticDateTimeUtils.nowDateTime(true); Long daysAgoLong = StaticDateTimeUtils.dateTimeToHourLong( StaticDateTimeUtils.nowDateTime( true).minusDays(daysAgo)); for (FileStatus fileStatus : dateDirsStats) { Long hourLong; String pathStr; try { pathStr = HdfsUtils.pathTailString(fileStatus); hourLong = Long.parseLong(pathStr); if (hourLong < daysAgoLong) { hourKeysList.add(hourLong); } } catch (NumberFormatException ex) { continue; } } Collections.sort(hourKeysList); for (Long hourLong : hourKeysList) { dirComps.clear(); dirComps.add(HadoopLogsConfigs.getMapreduceOutputPrefix()); dirComps.add(LB_LOGS_SPLIT); dirComps.add(hourLong.toString()); String pathStr = StaticFileUtils.splitPathToString(StaticFileUtils.joinPath(dirComps)); out.add(pathStr); } return out; }
Source:
public String getPattern() { return "Publishing build information...\\s+" + PatternUtils.WEB_URL_PATTERN; }

Target:
public String getPattern() { return "Publishing build information.*\\s+" + PatternUtils.WEB_URL_PATTERN; }
Source:
public void clearReferers() { for (WordsObject referringObject : referers.keySet()) { for (Property property : referers.get(referringObject)) { property.type = PropertyType.NOTHING; property.objProperty = null; } referers.remove(referringObject); } }

Target:
public void clearReferers() { for (Iterator<ArrayList<Property>> it = referers.values().iterator(); it.hasNext();) { ArrayList<Property> properties = it.next(); for (Property property : properties) { property.type = PropertyType.NOTHING; property.objProperty = null; } it.remove(); } }
Source:
private static ImmutableList<PropertyDefinition> pluginProperties() { return ImmutableList.of( PropertyDefinition.builder(HtmlConstants.FILE_EXTENSIONS_PROP_KEY) .name("HTML File suffixes") .description("List of file suffixes that will be scanned.") .category(CATEGORY) .defaultValue(HtmlConstants.FILE_EXTENSIONS_DEF_VALUE) .deprecatedKey("sonar.web.file.suffixes") .onQualifiers(Qualifiers.PROJECT) .multiValues(true) .build(), PropertyDefinition.builder(HtmlConstants.JSP_FILE_EXTENSIONS_PROP_KEY) .name("JSP File suffixes") .description("List of file suffixes that will be scanned.") .category(CATEGORY) .defaultValue(HtmlConstants.JSP_FILE_EXTENSIONS_DEF_VALUE) .onQualifiers(Qualifiers.PROJECT) .multiValues(true) .build() ); }

Target:
private static ImmutableList<PropertyDefinition> pluginProperties() { return ImmutableList.of( PropertyDefinition.builder(HtmlConstants.FILE_EXTENSIONS_PROP_KEY) .name("HTML File suffixes") .description("List of file suffixes that will be scanned.") .category(CATEGORY) .defaultValue(HtmlConstants.FILE_EXTENSIONS_DEF_VALUE) .deprecatedKey("sonar.web.file.suffixes") .onQualifiers(Qualifiers.PROJECT) .multiValues(true) .build(), PropertyDefinition.builder(HtmlConstants.JSP_FILE_EXTENSIONS_PROP_KEY) .name("JSP File suffixes") .description("List of JSP file suffixes that will be scanned.") .category(CATEGORY) .defaultValue(HtmlConstants.JSP_FILE_EXTENSIONS_DEF_VALUE) .onQualifiers(Qualifiers.PROJECT) .multiValues(true) .build() ); }
Source:
public Object executeWithSubject() throws Exception { SolrClient solrClient = clientFactory.newClient(OfflineGazetteerPlugin.STANDALONE_GAZETTEER_CORE_NAME); Failsafe.with(retryPolicy).get(() -> solrClient.ping()); Iterable<Result> iterable = ResultIterable.resultIterable(catalogFramework, getGazetteerFilter()); session.getConsole().println("Starting sync..."); long counter = 0; Instant start = Instant.now(); for (List<Result> results : Iterables.partition(iterable, PARTITION_SIZE)) { if (Thread.interrupted()) { LOGGER.info("Catalog sync interrupted early, exiting"); session.getConsole().println("Catalog sync interrupted, exiting"); Thread.currentThread().interrupt(); throw new InterruptedException(); } try { solrClient.add( results .stream() .map(Result::getMetacard) .map(OfflineGazetteerPlugin::convert) .collect(Collectors.toList())); } catch (SolrServerException | IOException e) { LOGGER.info("error while adding items to solr", e); session.getConsole().printf("An error occured while syncing: %s", e.getMessage()); throw e; } counter += results.size(); } session .getConsole() .printf( "%nComplete. Processed %d items in %s%n", counter, Duration.between(start, Instant.now()).toString()); return null; }

Target:
public Object executeWithSubject() throws Exception { SolrClient solrClient = clientFactory.newClient(COLLECTION_NAME); Boolean response = Failsafe.with( new RetryPolicy() .retryWhen(false) .withMaxDuration(5, TimeUnit.SECONDS) .withBackoff(50, 1_000, TimeUnit.MILLISECONDS)) .get(() -> solrClient.isAvailable()); if (response == null || !response) { LOGGER.error("Could not contact solr to remove all"); session.getConsole().println("Could not contact solr to remove all, exiting."); return null; } Iterable<Result> iterable = ResultIterable.resultIterable(catalogFramework, getGazetteerFilter()); session.getConsole().println("Starting sync..."); long counter = 0; Instant start = Instant.now(); for (List<Result> results : Iterables.partition(iterable, PARTITION_SIZE)) { if (Thread.interrupted()) { LOGGER.info("Catalog sync interrupted early, exiting"); session.getConsole().println("Catalog sync interrupted, exiting"); Thread.currentThread().interrupt(); throw new InterruptedException(); } try { solrClient.add( results .stream() .map(Result::getMetacard) .map(CatalogGazetteerForwardingPlugin::convert) .collect(Collectors.toList())); } catch (SolrServerException | IOException e) { LOGGER.info("error during syncing while adding items to solr", e); session.getConsole().printf("An error occured while syncing: %s", e.getMessage()); throw e; } counter += results.size(); } session .getConsole() .printf( "%nComplete. Processed %d items in %s%n", counter, Duration.between(start, Instant.now()).toString()); return null; }
Source:
public static void writeMetadata(ByteBuf buf, List<Entry> entries) throws IOException { for (Entry entry : entries) { MetadataIndex index = entry.index; Object value = entry.value; if (value == null) continue; int type = index.getType().getId(); int id = index.getIndex(); buf.writeByte(id); buf.writeByte(type); switch (index.getType()) { case BYTE: buf.writeByte((Byte) value); break; case INT: ByteBufUtils.writeVarInt(buf, (Integer) value); break; case FLOAT: buf.writeFloat((Float) value); break; case STRING: ByteBufUtils.writeUTF8(buf, (String) value); break; case CHAT: writeChat(buf, (TextMessage) value); break; case ITEM: writeSlot(buf, (ItemStack) value); break; case BOOLEAN: buf.writeBoolean((Boolean) value); break; case VECTOR: EulerAngle angle = (EulerAngle) value; buf.writeFloat((float) Math.toDegrees(angle.getX())); buf.writeFloat((float) Math.toDegrees(angle.getY())); buf.writeFloat((float) Math.toDegrees(angle.getZ())); break; case POSITION: { BlockVector vector = (BlockVector) value; buf.writeLong(Position.getPosition(vector)); } break; case OPTPOSITION: if (value != null) { BlockVector vector = (BlockVector) value; buf.writeLong(Position.getPosition(vector)); } break; case DIRECTION: ByteBufUtils.writeVarInt(buf, (Integer) value); break; case OPTUUID: buf.writeBoolean(value != null); if (value != null) { writeUuid(buf, (UUID) value); } break; case BLOCKID: ByteBufUtils.writeVarInt(buf, (Integer) value); break; } } buf.writeByte(0xff); }

Target:
public static void writeMetadata(ByteBuf buf, List<Entry> entries) throws IOException { for (Entry entry : entries) { MetadataIndex index = entry.index; Object value = entry.value; int type = index.getType().getId(); int id = index.getIndex(); buf.writeByte(id); buf.writeByte(type); if (!index.getType().isOptional() && value == null) { continue; } if (index.getType().isOptional()) { buf.writeBoolean(value != null); if (value == null) { continue; } } switch (index.getType()) { case BYTE: buf.writeByte((Byte) value); break; case INT: ByteBufUtils.writeVarInt(buf, (Integer) value); break; case FLOAT: buf.writeFloat((Float) value); break; case STRING: ByteBufUtils.writeUTF8(buf, (String) value); break; case CHAT: writeChat(buf, (TextMessage) value); break; case ITEM: writeSlot(buf, (ItemStack) value); break; case BOOLEAN: buf.writeBoolean((Boolean) value); break; case VECTOR: EulerAngle angle = (EulerAngle) value; buf.writeFloat((float) Math.toDegrees(angle.getX())); buf.writeFloat((float) Math.toDegrees(angle.getY())); buf.writeFloat((float) Math.toDegrees(angle.getZ())); break; case POSITION: case OPTPOSITION: BlockVector vector = (BlockVector) value; buf.writeLong(Position.getPosition(vector)); break; case DIRECTION: ByteBufUtils.writeVarInt(buf, (Integer) value); break; case OPTUUID: writeUuid(buf, (UUID) value); break; case BLOCKID: ByteBufUtils.writeVarInt(buf, (Integer) value); break; } } buf.writeByte(0xff); }
Source:
public int getContainerMemoryMb() { if (getBoolean(JobConfig.JOB_AUTOSIZING_ENABLED, false) && containsKey(JobConfig.JOB_AUTOSIZING_CONTAINER_MEMORY_MB)) { return getInt(JobConfig.JOB_AUTOSIZING_CONTAINER_MEMORY_MB); } else if (containsKey(CLUSTER_MANAGER_MEMORY_MB)) { return getInt(CLUSTER_MANAGER_MEMORY_MB); } else if (containsKey(CONTAINER_MAX_MEMORY_MB)) { log.info("Configuration is deprecated. Please use {}", CONTAINER_MAX_MEMORY_MB, CLUSTER_MANAGER_MEMORY_MB); return getInt(CONTAINER_MAX_MEMORY_MB); } else { return DEFAULT_CONTAINER_MEM; } }

Target:
public int getContainerMemoryMb() { if (new JobConfig(this).getAutosizingEnabled() && containsKey(JobConfig.JOB_AUTOSIZING_CONTAINER_MEMORY_MB)) { return getInt(JobConfig.JOB_AUTOSIZING_CONTAINER_MEMORY_MB); } else if (containsKey(CLUSTER_MANAGER_MEMORY_MB)) { return getInt(CLUSTER_MANAGER_MEMORY_MB); } else if (containsKey(CONTAINER_MAX_MEMORY_MB)) { log.info("Configuration is deprecated. Please use {}", CONTAINER_MAX_MEMORY_MB, CLUSTER_MANAGER_MEMORY_MB); return getInt(CONTAINER_MAX_MEMORY_MB); } else { return DEFAULT_CONTAINER_MEM; } }
Source:
void init(final JBrowserDriverServer driver, final Context context) { if (initialized.compareAndSet(false, true)) { this.context.set(context); SettingsManager.register(stage, view); engine.set(view.get().getEngine()); try { window.set(new WindowServer(stage, context.statusCode)); context.alert.get().listen(this); } catch (RemoteException e) { Util.handleException(e); } final ContextItem thisObject = this; AppThread.exec(context.statusCode, () -> { Settings settings = SettingsManager.settings(); engine.get().setJavaScriptEnabled(settings.javascript()); File userDataDirectory = settings.userDataDirectory(); if (userDataDirectory == null) { try { userDataDirectory = Files.createTempDirectory("userdata").toFile(); } catch (IOException e) { Util.handleException(e); } } if (userDataDirectory != null) { engine.get().setUserDataDirectory(userDataDirectory); } httpListener.set(new HttpListener(thisObject, context.statusCode, context.timeouts.get().getPageLoadTimeoutObjMS())); Accessor.getPageFor(view.get().getEngine()).addLoadListenerClient(httpListener.get()); engine.get().setCreatePopupHandler(new PopupHandler(driver, context)); return null; }); } }

Target:
void init(final JBrowserDriverServer driver, final Context context) { if (initialized.compareAndSet(false, true)) { this.context.set(context); SettingsManager.register(stage, view); engine.set(view.get().getEngine()); try { window.set(new WindowServer(stage, context.statusCode)); context.alert.get().listen(this); } catch (RemoteException e) { Util.handleException(e); } final ContextItem thisObject = this; AppThread.exec(context.statusCode, () -> { Settings settings = SettingsManager.settings(); engine.get().setJavaScriptEnabled(settings.javascript()); engine.get().setUserDataDirectory(context.userDataDirectory.get()); httpListener.set(new HttpListener(thisObject, context.statusCode, context.timeouts.get().getPageLoadTimeoutObjMS())); Accessor.getPageFor(view.get().getEngine()).addLoadListenerClient(httpListener.get()); engine.get().setCreatePopupHandler(new PopupHandler(driver, context)); return null; }); } }
Source:
JobHistoryFileParserHadoop2() { for (CounterTypes ct : CounterTypes.values()) { COUNTER_NAMES.add(ct.toString()); } }

Target:
JobHistoryFileParserHadoop2() { }
Source:
public void initialize(FileExists ignored) { verify(ignored.message().isEmpty(), "annotation.message is not empty"); }

Target:
public void initialize(FileExists ignored) { verify(ignored.message().isEmpty(), "FileExists.message cannot be specified"); }
Source:
public static <I> void checkEverythingImplemented(Class<I> interfaceClass, Class<? extends I> implementationClass) throws ReflectiveOperationException { for (Method interfaceMethod : interfaceClass.getMethods()) { Method implementationMethod = implementationClass.getMethod(interfaceMethod.getName(), interfaceMethod.getParameterTypes()); if (interfaceMethod.equals(implementationMethod) && interfaceMethod.getAnnotation(Deprecated.class) == null) { throw new AssertionError(format( "Method should be overridden in %s: %s", implementationClass, interfaceMethod)); } } }

Target:
public static <I> void checkEverythingImplemented(Class<I> interfaceClass, Class<? extends I> implementationClass) throws ReflectiveOperationException { checkArgument(interfaceClass.isAssignableFrom(implementationClass)); for (Method interfaceMethod : interfaceClass.getMethods()) { Method implementationMethod = implementationClass.getMethod(interfaceMethod.getName(), interfaceMethod.getParameterTypes()); if (interfaceMethod.equals(implementationMethod) && interfaceMethod.getAnnotation(Deprecated.class) == null) { throw new AssertionError(format( "Method should be overridden in %s: %s", implementationClass, interfaceMethod)); } } }
Source:
public static synchronized AbstractStereotypeInstanceEditDialog make(String stereotypeName, Shell shell, IStereotypeInstance instance, IStereotypeCapable artifact, Boolean isEditable) throws TigerstripeException { if (dialogHash == null) { getRegisteredAuditors(); } IConfigurationElement element = dialogHash.get(stereotypeName); if (element != null) { try { Bundle bundle = Platform.getBundle(element.getContributor().getName()); String className = element.getAttribute(DIALOG_CLASS); Class<?> extensionClass = bundle.loadClass(className); for (Constructor<?> constructor : extensionClass.getDeclaredConstructors()) { Class<?>[] paramTypes = constructor.getParameterTypes(); if (paramTypes.length >= 3 && paramTypes[0].isAssignableFrom(Shell.class) && paramTypes[1].isAssignableFrom(IStereotypeInstance.class) && paramTypes[2].isAssignableFrom(IStereotypeCapable.class)) { if (paramTypes.length == 4 && paramTypes[3].isAssignableFrom(Boolean.class)) { return (AbstractStereotypeInstanceEditDialog) constructor.newInstance(shell, instance, artifact, isEditable); } else { return (AbstractStereotypeInstanceEditDialog) constructor.newInstance(shell, instance, artifact); } } } return null; } catch (Exception e) { e.printStackTrace(); } } throw new TigerstripeException("Couldn't instantiate dialog for " + stereotypeName); }

Target:
public static synchronized AbstractStereotypeInstanceEditDialog make(String stereotypeName, Shell shell, IStereotypeInstance instance, IStereotypeCapable artifact, Boolean isEditable) throws TigerstripeException { if (dialogHash == null) { getRegisteredAuditors(); } IConfigurationElement element = dialogHash.get(stereotypeName); if (element != null) { try { Bundle bundle = Platform.getBundle(element.getContributor().getName()); String className = element.getAttribute(DIALOG_CLASS); Class<?> extensionClass = bundle.loadClass(className); for (Constructor<?> constructor : extensionClass.getDeclaredConstructors()) { Class<?>[] paramTypes = constructor.getParameterTypes(); if (paramTypes.length >= CUSTOM_DLG_OLD_CTOR_PARAMS_COUNT && paramTypes[0].isAssignableFrom(Shell.class) && paramTypes[1].isAssignableFrom(IStereotypeInstance.class) && paramTypes[2].isAssignableFrom(IStereotypeCapable.class)) { if (paramTypes.length == CUSTOM_DLG_CTOR_PARAMS_COUNT && paramTypes[3].isAssignableFrom(Boolean.class)) { return (AbstractStereotypeInstanceEditDialog) constructor.newInstance(shell, instance, artifact, isEditable); } else { return (AbstractStereotypeInstanceEditDialog) constructor.newInstance(shell, instance, artifact); } } } return null; } catch (Exception e) { e.printStackTrace(); } } throw new TigerstripeException("Couldn't instantiate dialog for " + stereotypeName); }
Source:
private void scheduleNextAttempt(Throwable throwable) { assert executor.inEventLoop(); state = State.SCHEDULED; if (reconnectionSchedule == null) { reconnectionSchedule = scheduleSupplier.get(); } Optional<Duration> nextInterval = reconnectionSchedule.nextDelay(Optional.ofNullable(throwable)); if (nextInterval.isPresent()) { LOG.debug("[{}] Scheduling next reconnection in {}", logPrefix, nextInterval); nextAttempt = executor.schedule(reconnectionTask, nextInterval.get().toNanos(), TimeUnit.NANOSECONDS); nextAttempt.addListener( (Future<CompletionStage<Boolean>> f) -> { if (f.isSuccess()) { onNextAttemptStarted(f.getNow()); } else if (!f.isCancelled()) { Loggers.warnWithException( LOG, "[{}] Uncaught error while starting reconnection attempt", logPrefix, f.cause()); scheduleNextAttempt(throwable); } }); } else { Loggers.warnWithException( LOG, "Reconnection attempt aborted, at discretion of reconnection policy", logPrefix); onFail.accept(throwable); } }

Target:
private void scheduleNextAttempt(Throwable throwable) { assert executor.inEventLoop(); state = State.SCHEDULED; if (reconnectionSchedule == null) { reconnectionSchedule = scheduleSupplier.get(); } Optional<Duration> nextInterval = reconnectionSchedule.nextDelay(Optional.ofNullable(throwable)); if (nextInterval.isPresent()) { LOG.debug("[{}] Scheduling next reconnection in {}", logPrefix, nextInterval); nextAttempt = executor.schedule(reconnectionTask, nextInterval.get().toNanos(), TimeUnit.NANOSECONDS); nextAttempt.addListener( (Future<CompletionStage<Void>> f) -> { if (f.isSuccess()) { onNextAttemptStarted(f.getNow()); } else if (!f.isCancelled()) { Loggers.warnWithException( LOG, "[{}] Uncaught error while starting reconnection attempt", logPrefix, f.cause()); scheduleNextAttempt(throwable); } }); } else { LOG.debug("Reconnection attempt aborted, at discretion of reconnection policy"); onAbort.accept(throwable); } }
Source:
public boolean containsExpectedPageContents() { if (isElementPresent(By.className("modal-content"))) { return waitForElementPresence(By.tagName("h2")).getText().contains("Uh oh! Something went wrong."); } return waitForElementPresence(By.tagName("h3")).getText().contains("Confirm your Google account"); }

Target:
public boolean containsExpectedPageContents() { return waitForElementPresence(By.tagName("h3")).getText().contains("Confirm your Google account"); }
Source:
public GitIndex getIndex() throws IOException { if (isBare()) throw new IOException( JGitText.get().bareRepositoryNoWorkdirAndIndex); if (index == null) { index = new GitIndex(this); index.read(); } else { index.rereadIfNecessary(); } return index; }

Target:
public GitIndex getIndex() throws IOException, IllegalStateException { if (isBare()) throw new IOException( JGitText.get().bareRepositoryNoWorkdirAndIndex); if (index == null) { index = new GitIndex(this); index.read(); } else { index.rereadIfNecessary(); } return index; }
Source:
public String doExport(DataTransferExportModel exportModel) throws java.io.IOException { String zipLocation = new StringBuilder().append(TMP_DIR) .append(File.separator) .append(FILE_PATH) .append(File.separator) .append(EXPORT_FILE_NAME) .toString(); Predicate<Path> readmeFilter = p -> p.toString().toLowerCase().endsWith("readme.md"); Predicate<Path> datasetsFilter = def -> true; Predicate<Path> pagesFilter = page -> true; boolean exportNavigation = true; if (!exportModel.isExportAll()) { datasetsFilter = filterDatasets(exportModel.getDatasetDefinitions()); pagesFilter = filterPages(exportModel.getPages()); exportNavigation = exportModel.isExportNavigation(); } new File(zipLocation).getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(zipLocation); ZipOutputStream zos = new ZipOutputStream(fos); zipFileSystem(datasetsFS, zos, readmeFilter.or(datasetsFilter)); zipFileSystem(perspectivesFS, zos, readmeFilter.or(pagesFilter)); if (exportNavigation) { zipFileSystem(navigationFS, zos, p -> true); } else { zipFileSystem(navigationFS, zos, readmeFilter); } zipFile(createVersionFile(), "VERSION", zos); zos.close(); fos.close(); moveZipToFileSystem(zipLocation, systemFS); return new StringBuilder().append(SpacesAPI.Scheme.GIT) .append("://") .append(systemFS.getName()) .append(File.separator) .append(FILE_PATH) .append(File.separator) .append(EXPORT_FILE_NAME) .toString(); }

Target:
public String doExport(DataTransferExportModel exportModel) throws java.io.IOException { String zipLocation = new StringBuilder().append(System.getProperty("java.io.tmpdir")) .append(File.separator) .append(FILE_PATH) .append(File.separator) .append(EXPORT_FILE_NAME) .toString(); Predicate<Path> readmeFilter = p -> p.toString().toLowerCase().endsWith("readme.md"); Predicate<Path> datasetsFilter = def -> true; Predicate<Path> pagesFilter = page -> true; boolean exportNavigation = true; if (!exportModel.isExportAll()) { datasetsFilter = filterDatasets(exportModel.getDatasetDefinitions()); pagesFilter = filterPages(exportModel.getPages()); exportNavigation = exportModel.isExportNavigation(); } new File(zipLocation).getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(zipLocation); ZipOutputStream zos = new ZipOutputStream(fos); zipFileSystem(datasetsFS, zos, readmeFilter.or(datasetsFilter)); zipFileSystem(perspectivesFS, zos, readmeFilter.or(pagesFilter)); if (exportNavigation) { zipFileSystem(navigationFS, zos, p -> true); } else { zipFileSystem(navigationFS, zos, readmeFilter); } zipFile(createVersionFile(), "VERSION", zos); zos.close(); fos.close(); moveZipToFileSystem(zipLocation, systemFS); return new StringBuilder().append(SpacesAPI.Scheme.GIT) .append("://") .append(systemFS.getName()) .append(File.separator) .append(FILE_PATH) .append(File.separator) .append(EXPORT_FILE_NAME) .toString(); }
Source:
public long fetchUnzipToTemp(ClientBlobStore store) throws IOException, KeyNotFoundException, AuthorizationException { String key = getKey(); ReadableBlobMeta meta = store.getBlobMeta(key); if (!ServerUtils.canUserReadBlob(meta, user, conf)) { throw new WrappedAuthorizationException(user + " does not have READ access to " + key); } DownloadMeta downloadMeta = fetch(store, key, v -> { Path path = shouldUncompress ? tmpOutputLocation() : constructBlobWithVersionFileName(baseDir, getKey(), v); Path parent = path.getParent(); if (!Files.exists(parent)) { try { Files.createDirectories(parent); } catch (FileAlreadyExistsException e) { } catch (Exception e) { LOG.error("Failed to create parent directory {}", parent, e); throw e; } } return path; }, FileOutputStream::new ); Path finalLocation = downloadMeta.getDownloadPath(); if (shouldUncompress) { Path downloadFile = finalLocation; finalLocation = constructBlobWithVersionFileName(baseDir, getKey(), downloadMeta.getVersion()); ServerUtils.unpack(downloadFile.toFile(), finalLocation.toFile(), symLinksDisabled); LOG.debug("Uncompressed to: {}", downloadFile, finalLocation); } setBlobPermissions(conf, user, finalLocation); return downloadMeta.getVersion(); }

Target:
public long fetchUnzipToTemp(ClientBlobStore store) throws IOException, KeyNotFoundException, AuthorizationException { String key = getKey(); ReadableBlobMeta meta = store.getBlobMeta(key); if (!ServerUtils.canUserReadBlob(meta, user, conf)) { throw new WrappedAuthorizationException(user + " does not have READ access to " + key); } DownloadMeta downloadMeta = fetch(store, key, v -> { Path path = shouldUncompress ? tmpOutputLocation() : constructBlobWithVersionFileName(baseDir, getKey(), v); Path parent = path.getParent(); if (!Files.exists(parent)) { try { Files.createDirectories(parent); } catch (FileAlreadyExistsException e) { } catch (IOException e) { LOG.error("Failed to create parent directory {}", parent, e); throw e; } } return path; }, FileOutputStream::new ); Path finalLocation = downloadMeta.getDownloadPath(); if (shouldUncompress) { Path downloadFile = finalLocation; finalLocation = constructBlobWithVersionFileName(baseDir, getKey(), downloadMeta.getVersion()); ServerUtils.unpack(downloadFile.toFile(), finalLocation.toFile(), symLinksDisabled); LOG.debug("Uncompressed to: {}", downloadFile, finalLocation); } setBlobPermissions(conf, user, finalLocation); return downloadMeta.getVersion(); }