/* (non-Javadoc)
@see io.github.classgraph.ClasspathElement#open(
nonapi.io.github.classgraph.concurrency.WorkQueue, nonapi.io.github.classgraph.utils.LogNode)
439661
@Override
    void open(final WorkQueue<ClasspathEntryWorkUnit> workQueue, final LogNode log) throws InterruptedException {
        if (!scanSpec.scanJars) {
            if (log != null) {
                log.log("Skipping classpath element, since jar scanning is disabled: " + rawPath);
            }
            skipClasspathElement = true;
            return;
        }
        final LogNode subLog = log == null ? null : log.log("Opening jar: " + rawPath);
        final int plingIdx = rawPath.indexOf('!');
        final String outermostZipFilePathResolved = FastPathResolver.resolve(FileUtils.CURR_DIR_PATH,
                plingIdx < 0 ? rawPath : rawPath.substring(0, plingIdx));
        if (!scanSpec.jarWhiteBlackList.isWhitelistedAndNotBlacklisted(outermostZipFilePathResolved)) {
            if (subLog != null) {
                subLog.log("Skipping jarfile that is blacklisted or not whitelisted: " + rawPath);
            }
            skipClasspathElement = true;
            return;
        }

        try {
            // Get LogicalZipFile for innermost nested jarfile
            Entry<LogicalZipFile, String> logicalZipFileAndPackageRoot;
            try {
                logicalZipFileAndPackageRoot = nestedJarHandler.nestedPathToLogicalZipFileAndPackageRootMap
                        .get(rawPath, subLog);
            } catch (final NullSingletonException e) {
                // Generally thrown on the second and subsequent attempt to call .get(), after the first failed
                throw new IOException("Could not get logical zipfile " + rawPath + " : " + e);
            }
            logicalZipFile = logicalZipFileAndPackageRoot.getKey();
            if (logicalZipFile == null) {
                // Should not happen, but this keeps lgtm static analysis happy
                throw new IOException("Logical zipfile was null");
            }

            // Get the normalized path of the logical zipfile
            zipFilePath = FastPathResolver.resolve(FileUtils.CURR_DIR_PATH, logicalZipFile.getPath());

            // Get package root of jarfile 
            final String packageRoot = logicalZipFileAndPackageRoot.getValue();
            if (!packageRoot.isEmpty()) {
                packageRootPrefix = packageRoot + "/";
            }
        } catch (final IOException | IllegalArgumentException e) {
            if (subLog != null) {
                subLog.log("Could not open jarfile " + rawPath + " : " + e);
            }
            skipClasspathElement = true;
            return;
        }

        if (!scanSpec.enableSystemJarsAndModules && logicalZipFile.isJREJar) {
            // Found a blacklisted JRE jar that was not caught by filtering for rt.jar in ClasspathFinder
            // (the isJREJar value was set by detecting JRE headers in the jar's manifest file)
            if (subLog != null) {
                subLog.log("Ignoring JRE jar: " + rawPath);
            }
            skipClasspathElement = true;
            return;
        }

        if (!logicalZipFile.isWhitelistedAndNotBlacklisted(scanSpec.jarWhiteBlackList)) {
            if (subLog != null) {
                subLog.log("Skipping jarfile that is blacklisted or not whitelisted: " + rawPath);
            }
            skipClasspathElement = true;
            return;
        }

        // Automatically add any nested "lib/" dirs to classpath, since not all classloaders return them
        // as classpath elements
        int childClasspathEntryIdx = 0;
        if (scanSpec.scanNestedJars) {
            for (final FastZipEntry zipEntry : logicalZipFile.entries) {
                for (final String libDirPrefix : ClassLoaderHandlerRegistry.AUTOMATIC_LIB_DIR_PREFIXES) {
                    if (zipEntry.entryNameUnversioned.startsWith(libDirPrefix)
                            && zipEntry.entryNameUnversioned.endsWith(".jar")) {
                        final String entryPath = zipEntry.getPath();
                        if (subLog != null) {
                            subLog.log("Found nested lib jar: " + entryPath);
                        }
                        workQueue.addWorkUnit(new ClasspathEntryWorkUnit(
                                /* rawClasspathEntry = */ new SimpleEntry<>(entryPath, classLoader),
                                /* parentClasspathElement = */ this,
                                /* orderWithinParentClasspathElement = */
                                childClasspathEntryIdx++));
                        break;
                    }
                }
            }
        }

        // Don't add child classpath elements that are identical to this classpath element, or that are duplicates
        final Set<String> scheduledChildClasspathElements = new HashSet<>();
        scheduledChildClasspathElements.add(rawPath);

        // Create child classpath elements from values obtained from Class-Path entry in manifest, resolving
        // the paths relative to the dir or parent jarfile that the jarfile is contained in
        if (logicalZipFile.classPathManifestEntryValue != null) {
            // Get parent dir of logical zipfile within grandparent slice,
            // e.g. for a zipfile slice path of "/path/to/jar1.jar!/lib/jar2.jar", this is "lib",
            // or for "/path/to/jar1.jar", this is "/path/to", or "" if the jar is in the toplevel dir.
            final String jarParentDir = FileUtils
                    .getParentDirPath(logicalZipFile.getPathWithinParentZipFileSlice());
            // Add paths in manifest file's "Class-Path" entry to the classpath, resolving paths relative to
            // the parent directory or jar
            for (final String childClassPathEltPathRelative : logicalZipFile.classPathManifestEntryValue
                    .split(" ")) {
                if (!childClassPathEltPathRelative.isEmpty()) {
                    // Resolve Class-Path entry relative to containing dir
                    String childClassPathEltPath = FastPathResolver.resolve(jarParentDir,
                            childClassPathEltPathRelative);
                    // If this is a nested jar, prepend outer jar prefix
                    final ZipFileSlice parentZipFileSlice = logicalZipFile.getParentZipFileSlice();
                    if (parentZipFileSlice != null) {
                        childClassPathEltPath = parentZipFileSlice.getPath()
                                + (childClassPathEltPath.startsWith("/") ? "!" : "!/") + childClassPathEltPath;
                    }
                    // Only add child classpath elements once
                    if (scheduledChildClasspathElements.add(childClassPathEltPath)) {
                        // Schedule child classpath element for scanning
                        workQueue.addWorkUnit( //
                                new ClasspathEntryWorkUnit(
                                        /* rawClasspathEntry = */ new SimpleEntry<>(childClassPathEltPath,
                                                classLoader),
                                        /* parentClasspathElement = */ this,
                                        /* orderWithinParentClasspathElement = */
                                        childClasspathEntryIdx++));
                    }
                }
            }
        }
        // Add paths in an OSGi bundle jar manifest's "Bundle-ClassPath" entry to the classpath, resolving 
        // the paths relative to the root of the jarfile
        if (logicalZipFile.bundleClassPathManifestEntryValue != null) {
            final String zipFilePathPrefix = zipFilePath + "!/";
            // Class-Path is split on " ", but Bundle-ClassPath is split on ","
            for (String childBundlePath : logicalZipFile.bundleClassPathManifestEntryValue.split(",")) {
                // Assume that Bundle-ClassPath paths have to be given relative to jarfile root
                while (childBundlePath.startsWith("/")) {
                    childBundlePath = childBundlePath.substring(1);
                }
                // Currently the position of "." relative to child classpath entries is ignored (the
                // Bundle-ClassPath path is treated as if "." is in the first position, since child
                // classpath entries are always added to the classpath after the parent classpath
                // entry that they were obtained from).
                if (!childBundlePath.isEmpty() && !childBundlePath.equals(".")) {
                    // Resolve Bundle-ClassPath entry within jar
                    final String childClassPathEltPath = zipFilePathPrefix
                            + FileUtils.sanitizeEntryPath(childBundlePath, /* removeInitialSlash = */ true);
                    // Only add child classpath elements once
                    if (scheduledChildClasspathElements.add(childClassPathEltPath)) {
                        // Schedule child classpath element for scanning
                        workQueue.addWorkUnit(new ClasspathEntryWorkUnit(
                                /* rawClasspathEntry = */ //
                                new SimpleEntry<>(childClassPathEltPath, classLoader),
                                /* parentClasspathElement = */ this,
                                /* orderWithinParentClasspathElement = */
                                childClasspathEntryIdx++));
                    }
                }
            }
        }
    }
1074322
@Override
	public void open(int taskNumber, int numTasks) throws IOException {
		this.fileOutputCommitterWrapper.setupJob(this.jobConf);
		if (Integer.toString(taskNumber + 1).length() <= 6) {
			this.jobConf.set("mapred.task.id", "attempt__0000_r_" + String.format("%" + (6 - Integer.toString(taskNumber + 1).length()) + "s"," ").replace(" ", "0") + Integer.toString(taskNumber + 1) + "_0");
			//compatible for hadoop 2.2.0, the temporary output directory is different from hadoop 1.2.1
			this.jobConf.set("mapreduce.task.output.dir", this.fileOutputCommitterWrapper.getTempTaskOutputPath(this.jobConf,TaskAttemptID.forName(this.jobConf.get("mapred.task.id"))).toString());
		} else {
			throw new IOException("task id too large");
		}
		this.recordWriter = this.hadoopOutputFormat.getRecordWriter(null, this.jobConf, Integer.toString(taskNumber + 1), new DummyHadoopProgressable());
	}
831074
@Override
  public SeekableByteChannel open(
      final StorageResourceId resourceId, GoogleCloudStorageReadOptions readOptions)
      throws IOException {
    logger.atFine().log("open(%s, %s)", resourceId, readOptions);
    Preconditions.checkArgument(
        resourceId.isStorageObject(), "Expected full StorageObject id, got %s", resourceId);

    // The underlying channel doesn't initially read data, which means that we won't see a
    // FileNotFoundException until read is called. As a result, in order to find out if the object
    // exists, we'll need to do an RPC (metadata or data). A metadata check should be a less
    // expensive operation than a read data operation.
    GoogleCloudStorageItemInfo info;
    if (readOptions.getFastFailOnNotFound()) {
      info = getItemInfo(resourceId);
      if (!info.exists()) {
        throw GoogleCloudStorageExceptions.getFileNotFoundException(
            resourceId.getBucketName(), resourceId.getObjectName());
      }
    } else {
      info = null;
    }

    return new GoogleCloudStorageReadChannel(
        gcs,
        resourceId.getBucketName(),
        resourceId.getObjectName(),
        errorExtractor,
        clientRequestHelper,
        readOptions) {

      @Override
      @Nullable
      protected GoogleCloudStorageItemInfo getInitialMetadata() {
        return info;
      }

      @Override
      protected Storage.Objects.Get createRequest() throws IOException {
        return configureRequest(super.createRequest(), resourceId.getBucketName());
      }
    };
  }
1359161
@Override
	public void open(int taskNumber, int numTasks) throws IOException {
		super.open(taskNumber, numTasks);
		
		try {
			this.charset = Charset.forName(charsetName);
		}
		catch (IllegalCharsetNameException e) {
			throw new IOException("The charset " + charsetName + " is not valid.", e);
		}
		catch (UnsupportedCharsetException e) {
			throw new IOException("The charset " + charsetName + " is not supported.", e);
		}
	}
1150900
@Override
    public String ideaOpenAndNavigate(String fileName, int line, int column) throws Exception {
        if (line < 0) line = 0;
        if (column < 0) column = 0;
        String xml = "<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\n" +
                "<methodCall>\n" +
                "  <methodName>fileOpener.openAndNavigate</methodName>\n" +
                "  <params>\n" +
                "    <param><value><string>" + fileName + "</string></value></param>\n" +
                "    <param><value><int>" + line + "</int></value></param>\n" +
                "    <param><value><int>" + column + "</int></value></param>\n" +
                "  </params>\n" +
                "</methodCall>\n";

        return ideaXmlRpc(xml);
    }
596095
public static AsyncFile open(Executor executor, Path path, Set<OpenOption> openOptions) throws IOException {
		FileChannel channel = doOpenChannel(path, openOptions);
		return new AsyncFile(executor, channel, path, null);
	}
1342348
function open(selector) {
            if (p["--debug"] && host.runtime == host.RUNTIME_NODEJS) {
                return debug(p);
            }
            if (p["--ui"] && !ui) {
                if (!nw) {
                    allume.update(allume.STATUS_ERROR, MSG_UI_UNAVAILABLE);
                    return;
                }

                // spawn nw.js process for allume with parameters
                var findpath = nw.findpath;
                childProcess = childProcess || require("child_process");
                path = path || require("path");

                var PATH_NW = findpath();
                var PATH_APP = path.join(__dirname, "..");
                var PATH_CWD = process.cwd();
                var env = Object.create(process.env);
                env.PWD = process.cwd();

                process.argv.splice(1, 1);
                process.argv[0] = PATH_APP;
                for (var a in process.argv) {
                    process.argv[a] = process.argv[a].replace(/"/g, "\"");
                }

                var ls = childProcess.spawn(PATH_NW, process.argv, {"cwd": PATH_CWD, "env" : env});

                ls.stdout.on("data", function(data) {
                    console.log(data.toString().trim());
                });

                ls.stderr.on("data", function(data) {
                    console.error(data.toString().trim());
                });

                return;
            }

            var requests = [];
            var request = selector;
            if (p["--config"]) {
                var json;
                try {
                    json = JSON.parse(p["--config"].json);
                }
                catch(e) {
                    var e = new Error("Make sure the data you pass to the --config switch is valid JSON data.");
                    e.name = "error-invalid-configuration";
                    if (typeof document !== "undefined" && firstOpen) {
                        allume.update(e);
                    }
                    else {
                        console.error(e);
                    }
                    firstOpen = false;
                    return;
                }
                request = { "package" : selector, "configuration" : json };
            }
            requests.push(request);

            if (requests) {
                using.apply(using, requests).then(function () {
                    if (firstOpen) {
                        allume.hide();
                        firstOpen = false;
                    }
                }, function (loader) {
                    usingFailed(loader);
                    var e = new Error(err);
                    e.name = errName;
                    if (typeof document !== "undefined" && firstOpen) {
                        allume.update(e);
                        firstOpen = false;
                    }
                    else {
                        console.error(e);
                    }
                });
            }
        }
1146635
public void crawlToOpen(TreePath path, ArrayList<BugLeafNode> bugLeafNodes, ArrayList<TreePath> treePaths) {
        for (int i = 0; i < getChildCount(path.getLastPathComponent()); i++) {
            if (!isLeaf(getChild(path.getLastPathComponent(), i))) {
                for (BugLeafNode p : bugLeafNodes) {
                    if (p.matches((BugAspects) getChild(path.getLastPathComponent(), i))) {
                        tree.expandPath(path);
                        crawlToOpen(path.pathByAddingChild(getChild(path.getLastPathComponent(), i)), bugLeafNodes, treePaths);
                        break;
                    }
                }
            } else {
                for (BugLeafNode b : bugLeafNodes) {
                    if (getChild(path.getLastPathComponent(), i).equals(b)) {
                        tree.expandPath(path);
                        treePaths.add(path.pathByAddingChild(getChild(path.getLastPathComponent(), i)));
                    }
                }
            }
        }
    }
998585
synchronized void open() throws IOException {
    if (syncer == null) {
      syncer = new SyncThread();
      syncThread = new Thread(syncer);
      syncThread.start();
    }
    if (state != State.BETWEEN_LOG_SEGMENTS)
      throw new IOException("Bad state: " + state);

    startLogSegment(getLastWrittenTxId() + 1, true);
    if (state != State.IN_SEGMENT)
      throw new IOException("Bad state: " + state);
  }
143113
private static void openLog(String rootName) throws Exception {
        s_rootName = rootName;
        String fileName =
                s_rootName + "-" + System.currentTimeMillis() + ".xml";
        File outFile;
        String fedoraHome = Constants.FEDORA_HOME;
        if (fedoraHome == null) {
            // to current dir
            outFile = new File(fileName);
        } else {
            // to client/log
            File logDir =
                    new File(new File(new File(fedoraHome), "client"), "logs");
            if (!logDir.exists()) {
                logDir.mkdir();
            }
            outFile = new File(logDir, fileName);

        }
        s_logPath = outFile.getPath();
        s_log = new PrintStream(new FileOutputStream(outFile), true, "UTF-8");
        s_log.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        s_log.println("<" + s_rootName + ">");
    }
1064251
private void openNewPartIfNecessary(long sizeThreshold) throws IOException {
		final long fileLength = fileStream.getPos();
		if (fileLength >= sizeThreshold) {
			lock();
			try {
				uploadCurrentAndOpenNewPart(fileLength);
			} finally {
				unlock();
			}
		}
	}
755263
@SuppressWarnings("rawtypes")
    @Override
    public void open(Map conf, TopologyContext context, SpoutOutputCollector collector)
    {
        super.open(conf, context, collector);

        this.taskId = context.getThisComponentId() + "_" + context.getThisTaskId();

        if (this.reloadConfig)
        {
            if (conf.containsKey(StormConfigGenerator.INIT_CONFIG_KEY))
            {
                String watchPath = conf.get(StormConfigGenerator.INIT_CONFIG_KEY).toString();
                String logFormat = "Config reload watch start. : WatchPath={0}, Interval(Sec)={1}";
                logger.info(MessageFormat.format(logFormat, watchPath, this.reloadConfigIntervalSec));

                this.watcher = new ConfigFileWatcher(watchPath, this.reloadConfigIntervalSec);
                this.watcher.init();
            }
        }

        onOpen(conf, context);
    }
903491
public synchronized void open() throws IOException {
        if (tmap != null) {
            return;
        }
        final RecordManager rm = createRecordManager(indexPath);
        if (valueSerializer == null) {
            tmap = rm.treeMap(IndexerConstants.INDEX_TREE_KEY);
        } else {
            tmap = rm.treeMap(IndexerConstants.INDEX_TREE_KEY, valueSerializer);
        }
        if (tmap.isEmpty()) {
            rm.close();
            throw new IOException("tree map is empty");
        }
        invTmap = tmap.inverseHashView(IndexerConstants.INVERSE_KEY);
    }
298914
@Override
    public void     start() throws Exception
    {
        if ( !state.compareAndSet(State.LATENT, State.STARTED) )
        {
            throw new IllegalStateException();
        }

        try
        {
            client.create().creatingParentContainersIfNeeded().forPath(queuePath);
        }
        catch ( KeeperException.NodeExistsException ignore )
        {
            // this is OK
        }
        if ( lockPath != null )
        {
            try
            {
                client.create().creatingParentContainersIfNeeded().forPath(lockPath);
            }
            catch ( KeeperException.NodeExistsException ignore )
            {
                // this is OK
            }
        }

        if ( !isProducerOnly || (maxItems != QueueBuilder.NOT_SET) )
        {
            childrenCache.start();
        }

        if ( !isProducerOnly )
        {
            service.submit
                (
                    new Callable<Object>()
                    {
                        @Override
                        public Object call()
                        {
                            runLoop();
                            return null;
                        }
                    }
                );
        }
    }
546722
@Override
    public void open() throws Exception {
        EDb edb = EDb.fromFileDesktop(databaseFile);
        spatialDb = edb.getSpatialDb();
        spatialDb.open(databaseFile.getAbsolutePath());
        GeometryColumn geometryColumnsForTable = spatialDb.getGeometryColumnsForTable(LasCellsTable.TABLENAME);
        crs = CrsUtilities.getCrsFromSrid(geometryColumnsForTable.srid);
        isOpen = true;
    }
918879
public static void main(String[] args
                          ) throws ClassNotFoundException, IOException, 
                                   InterruptedException {
    if (args.length != 1) {
      System.out.println("Usage: IsolationRunner <path>/job.xml");
      System.exit(1);
    }
    File jobFilename = new File(args[0]);
    if (!jobFilename.exists() || !jobFilename.isFile()) {
      System.out.println(jobFilename + " is not a valid job file.");
      System.exit(1);
    }
    JobConf conf = new JobConf(new Path(jobFilename.toString()));
    TaskAttemptID taskId = TaskAttemptID.forName(conf.get("mapred.task.id"));
    boolean isMap = conf.getBoolean("mapred.task.is.map", true);
    int partition = conf.getInt("mapred.task.partition", 0);
    
    // setup the local and user working directories
    FileSystem local = FileSystem.getLocal(conf);
    LocalDirAllocator lDirAlloc = new LocalDirAllocator("mapred.local.dir");
    File workDirName = new File(lDirAlloc.getLocalPathToRead(
                                  TaskTracker.getLocalTaskDir(
                                    taskId.getJobID().toString(), 
                                    taskId.toString())
                                  + Path.SEPARATOR + "work",
                                  conf). toString());
    local.setWorkingDirectory(new Path(workDirName.toString()));
    FileSystem.get(conf).setWorkingDirectory(conf.getWorkingDirectory());
    
    // set up a classloader with the right classpath
    ClassLoader classLoader = makeClassLoader(conf, workDirName);
    Thread.currentThread().setContextClassLoader(classLoader);
    conf.setClassLoader(classLoader);
    
    Task task;
    if (isMap) {
      Path localSplit = new Path(new Path(jobFilename.toString()).getParent(), 
                                 "split.dta");
      DataInputStream splitFile = FileSystem.getLocal(conf).open(localSplit);
      String splitClass = Text.readString(splitFile);
      BytesWritable split = new BytesWritable();
      split.readFields(splitFile);
      splitFile.close();
      task = new MapTask(jobFilename.toString(), taskId, partition, 
                         splitClass, split, 1, conf.getUser());
    } else {
      int numMaps = conf.getNumMapTasks();
      fillInMissingMapOutputs(local, taskId, numMaps, conf);
      task = new ReduceTask(jobFilename.toString(), taskId, partition, numMaps, 
                            1, conf.getUser());
    }
    task.setConf(conf);
    task.run(conf, new FakeUmbilical());
  }
1226313
@Override
	public void open() throws IOException, MemoryAllocationException, InterruptedException {
		this.hashJoin.open(this.firstInput, this.secondInput, this.buildSideOuterJoin);
	}