/*
(non-Javadoc)

@see jgrass.io.MapWriter#open(java.lang.String) this method tests for the existence of the
needed folder structure and creates missing parts. The dataOutputType for the map to be
created is checked
172282
public boolean open( String fileName, String locationPath, String mapsetName ) {

        if (dataWindow != null) {
            name = fileName;
            this.locationPath = locationPath;
            this.mapsetPath = locationPath + File.separator + mapsetName;
            fcellFilePath = mapsetPath + File.separator + GrassLegacyConstans.FCELL + File.separator + name;

            if (!checkStructure())
                return false;
            if (!createEmptyHeader(fcellFilePath, dataWindow.getRows()))
                return false;
        } else {
            return false;
        }

        return true;
    }
1282389
public static void openFile(
		ServletContext servletContext,
		HttpServletRequest request,
		HttpServletResponse response,
		DomainName domain,
		Path book,
		final Path path
	) throws ServletException, IOException, SkipPageException {
		// Only allow from localhost and when open enabled
		if(!isAllowed(servletContext, request)) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			throw ServletUtil.SKIP_PAGE_EXCEPTION;
		} else {
			final String[] command;
			ResourceRef resourceRef = ResourceRefResolver.getResourceRef(servletContext, request, domain, book, path.toString());
			Book bookObj = SemanticCMS.getInstance(servletContext).getBook(resourceRef.getBookRef());
			if(bookObj.isAccessible()) throw new FileNotFoundException("Book is inaccessible: " + resourceRef);
			ResourceStore resourceStore = bookObj.getResources();
			if(!resourceStore.isAvailable()) throw new FileNotFoundException("Resource store is unavailable: " + resourceRef);
			java.io.File resourceFile = resourceStore.getResource(resourceRef.getPath()).getFile();
			if(resourceFile == null) throw new FileNotFoundException("Resource is not a local file: " + resourceRef);
			if(resourceFile.isDirectory()) {
				command = new String[] {
					// TODO: What is good windows path?
					//isWindows()
					//	? "C:\\Program Files (x86)\\OpenOffice 4\\program\\swriter.exe"
					"/usr/bin/konqueror",
					resourceFile.getCanonicalPath()
				};
			} else {
				// Open the file with the appropriate application based on extension
				String extension = FileUtils.getExtension(resourceFile.getName()).toLowerCase(Locale.ROOT);
				// Check registered file openers first
				FileOpener fileOpener;
				synchronized(fileOpenersLock) {
					@SuppressWarnings("unchecked")
					Map<String,FileOpener> fileOpeners = (Map<String,FileOpener>)servletContext.getAttribute(FILE_OPENERS_REQUEST_ATTRIBUTE_NAME);
					if(fileOpeners != null) {
						fileOpener = fileOpeners.get(extension);
					} else {
						fileOpener = null;
					}
				}
				if(fileOpener != null) {
					command = fileOpener.getCommand(resourceFile);
				} else {
					// Use default behavior
					switch(extension) {
						case "gif" :
						case "jpg" :
						case "jpeg" :
						case "png" :
							command = new String[] {
								isWindows()
									? "C:\\Program Files (x86)\\OpenOffice 4\\program\\swriter.exe"
									: "/usr/bin/gwenview",
								resourceFile.getCanonicalPath()
							};
							break;
						case "doc" :
						case "docx" :
						case "odt" :
							command = new String[] {
								isWindows()
									? "C:\\Program Files (x86)\\OpenOffice 4\\program\\swriter.exe"
									: "/usr/bin/libreoffice",
								"--writer",
								resourceFile.getCanonicalPath()
							};
							break;
						case "csv" :
						case "ods" :
						case "sxc" :
						case "xls" :
							command = new String[] {
								isWindows()
									? "C:\\Program Files (x86)\\OpenOffice 4\\program\\scalc.exe"
									: "/usr/bin/libreoffice",
								"--calc",
								resourceFile.getCanonicalPath()
							};
							break;
						case "pdf" :
							command = new String[] {
								isWindows()
									? "C:\\Program Files (x86)\\Adobe\\Reader 11.0\\Reader\\AcroRd32.exe"
									: "/usr/bin/okular",
								resourceFile.getCanonicalPath()
							};
							break;
						case "c" :
						case "csh" :
						case "h" :
						case "java" :
						case "jsp" :
						case "jspx" :
						case "sh" :
						case "txt" :
						case "xml" :
							if(isWindows()) {
								command = new String[] {
									"C:\\Program Files\\NetBeans 7.4\\bin\\netbeans64.exe",
									"--open",
									resourceFile.getCanonicalPath()
								};
							} else {
								command = new String[] {
									//"/usr/bin/kwrite",
									"/opt/netbeans-8.0.2/bin/netbeans",
									"--jdkhome",
									getJdkPath(),
									"--open",
									resourceFile.getCanonicalPath()
								};
							}
							break;
						case "dia" :
							command = new String[] {
								isWindows()
									? "C:\\Program Files (x86)\\Dia\\bin\\diaw.exe"
									: "/usr/bin/dia",
								resourceFile.getCanonicalPath()
							};
							break;
						case "zip" :
							if(isWindows()) {
								command = new String[] {
									resourceFile.getCanonicalPath()
								};
							} else {
								command = new String[] {
									"/usr/bin/konqueror",
									resourceFile.getCanonicalPath()
								};
							}
							break;
						case "mp3" :
						case "wma" :
							command = new String[] {
								isWindows()
									? "C:\\Program Files\\VideoLAN\\VLC.exe"
									: "/usr/bin/vlc",
								resourceFile.getCanonicalPath()
							};
							break;
						default :
							throw new IllegalArgumentException("Unsupprted file type by extension: " + extension);
					}
				}
			}
			// Start the process
			final Process process = Runtime.getRuntime().exec(command);
			// Result is watched in the background only
			// Java 1.8: Lambda
			new Thread(
				new Runnable() {
					@Override
					public void run() {
						try {
							final ProcessResult result = ProcessResult.getProcessResult(process);
							int exitVal = result.getExitVal();
							if(exitVal != 0) {
								logger.log(Level.SEVERE, "Non-zero exit status from \"{0}\": {1}", new Object[]{path, exitVal});
							}
							String stdErr = result.getStderr();
							if(!stdErr.isEmpty()) {
								logger.log(Level.SEVERE, "Standard error from \"{0}\":\n{1}", new Object[]{path, stdErr});
							}
							if(logger.isLoggable(Level.INFO)) {
								String stdOut = result.getStdout();
								if(!stdOut.isEmpty()) {
									logger.log(Level.INFO, "Standard output from \"{0}\":\n{1}", new Object[]{path, stdOut});
								}
							}
						} catch(IOException e) {
							logger.log(Level.SEVERE, null, e);
						}
					}
				}
			).start();
		}
	}
792170
void open() throws IOException {
        ListIterator<Appender> ite = appenderList.listIterator();
        while (ite.hasNext()) {
            Appender p = ite.next();
            if (p != null) p.open();
        }
    }
463085
@Override
    void open(final WorkQueue<ClasspathEntryWorkUnit> workQueue, final LogNode log) {
        if (!scanSpec.scanDirs) {
            if (log != null) {
                log.log("Skipping classpath element, since dir scanning is disabled: " + classpathEltDir);
            }
            skipClasspathElement = true;
            return;
        }
        try {
            // Auto-add nested lib dirs
            int childClasspathEntryIdx = 0;
            for (final String libDirPrefix : ClassLoaderHandlerRegistry.AUTOMATIC_LIB_DIR_PREFIXES) {
                final File libDir = new File(classpathEltDir, libDirPrefix);
                if (libDir.exists() && libDir.isDirectory()) {
                    // Sort directory entries for consistency
                    final File[] listFiles = libDir.listFiles();
                    if (listFiles != null) {
                        Arrays.sort(listFiles);
                        // Add all jarfiles within lib dir as child classpath entries
                        for (final File file : listFiles) {
                            if (file.isFile() && file.getName().endsWith(".jar")) {
                                if (log != null) {
                                    log.log("Found lib jar: " + file);
                                }
                                workQueue.addWorkUnit(new ClasspathEntryWorkUnit(
                                        /* rawClasspathEntry = */ //
                                        new SimpleEntry<>(file.getPath(), classLoader),
                                        /* parentClasspathElement = */ this,
                                        /* orderWithinParentClasspathElement = */ childClasspathEntryIdx++));
                            }
                        }
                    }
                }
            }
            for (final String packageRootPrefix : ClassLoaderHandlerRegistry.AUTOMATIC_PACKAGE_ROOT_PREFIXES) {
                final File packageRootDir = new File(classpathEltDir, packageRootPrefix);
                if (packageRootDir.exists() && packageRootDir.isDirectory()) {
                    if (log != null) {
                        log.log("Found package root: " + packageRootDir);
                    }
                    workQueue
                            .addWorkUnit(new ClasspathEntryWorkUnit(
                                    /* rawClasspathEntry = */ new SimpleEntry<>(packageRootDir.getPath(),
                                            classLoader),
                                    /* parentClasspathElement = */ this,
                                    /* orderWithinParentClasspathElement = */ childClasspathEntryIdx++));
                }
            }
        } catch (final SecurityException e) {
            if (log != null) {
                log.log("Skipping classpath element, since dir cannot be accessed: " + classpathEltDir);
            }
            skipClasspathElement = true;
            return;
        }
    }
414209
private JsonWriter open(JsonScope empty, String openBracket) throws IOException {
        beforeValue(true);
        stack.add(empty);
        out.write(openBracket);
        return this;
    }
773598
public void open(Path errFilePath) throws IOException {
    this.fs.mkdirs(errFilePath.getParent());
    OutputStream os =
        this.closer.register(this.fs.exists(errFilePath) ? this.fs.append(errFilePath) : this.fs.create(errFilePath));
    this.writer = this.closer
        .register(new BufferedWriter(new OutputStreamWriter(os, ConfigurationKeys.DEFAULT_CHARSET_ENCODING)));
  }
301964
public FSDataInputStream open(Path f, int bufferSize) throws IOException {
    return fs.open(f, bufferSize);
  }
934072
static void openURL(String url) {
    try {
      openURL(new URL(url));
    } catch (MalformedURLException ex) {
      Tools.showError(ex);
    }
  }
459388
@Override
  public int create(String path, @mode_t long mode, FuseFileInfo fi) {
    final AlluxioURI uri = mPathResolverCache.getUnchecked(path);
    final int flags = fi.flags.get();
    LOG.trace("create({}, {}) [Alluxio: {}]", path, Integer.toHexString(flags), uri);

    try {
      if (mOpenFiles.size() >= MAX_OPEN_FILES) {
        LOG.error("Cannot create {}: too many open files (MAX_OPEN_FILES: {})", path,
            MAX_OPEN_FILES);
        return -ErrorCodes.EMFILE();
      }

      FileOutStream os = mFileSystem.createFile(uri);
      synchronized (mOpenFiles) {
        mOpenFiles.add(new OpenFileEntry(mNextOpenFileId, path, null, os));
        fi.fh.set(mNextOpenFileId);

        // Assuming I will never wrap around (2^64 open files are quite a lot anyway)
        mNextOpenFileId += 1;
      }
      LOG.debug("{} created and opened", path);
    } catch (FileAlreadyExistsException e) {
      LOG.debug("Failed to create {}, file already exists", path);
      return -ErrorCodes.EEXIST();
    } catch (InvalidPathException e) {
      LOG.debug("Failed to create {}, path is invalid", path);
      return -ErrorCodes.ENOENT();
    } catch (Throwable t) {
      LOG.error("Failed to create {}", path, t);
      return AlluxioFuseUtils.getErrorCode(t);
    }

    return 0;
  }
153201
@Override
	public void open(InputSplit ignored) throws IOException {
		try {
			establishConnection();
			statement = dbConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
			resultSet = statement.executeQuery(query);
		} catch (SQLException se) {
			close();
			throw new IllegalArgumentException("open() failed." + se.getMessage(), se);
		} catch (ClassNotFoundException cnfe) {
			throw new IllegalArgumentException("JDBC-Class not found. - " + cnfe.getMessage(), cnfe);
		}
	}
1239895
public void open(String filePath, FileSystem fs, boolean isFileSyncEachTime) throws IOException
    {
        Path dstPath = new Path(filePath);

        if (fs.exists(dstPath) == true)
        {
            this.delegateStream = fs.append(dstPath);
        }
        else
        {
            this.delegateStream = fs.create(dstPath);
        }

        this.isFileSyncEachTime = isFileSyncEachTime;
    }
49587
public void openExample( Object o ) {
		if (o instanceof PathLabel) {
			PathLabel p = (PathLabel)o;
			if( p.path.length == 1 )
				openFile(new File(p.path[0]));
			else {
//				openFile(new File(p.path[0]));
				openImageSet(p.path);
			}
		} else if (o instanceof String) {
			openFile(new File((String) o));
		} else {
			throw new IllegalArgumentException("Unknown example object type.  Please override openExample()");
		}
	}
806459
@Override
  public void open() {
    try {
      if (this.isOpened() == false) {
        System.out.println(formatVersionInfo() + " Opening ...");

        this.traceLogfile = FileSystems.getDefault().getPath(this.logDirPath.toString(), super.getName() + ".log").toFile();
        this.fileOutputStream = new FileOutputStream(this.traceLogfile);
        this.setBufferedOutputStream(new BufferedOutputStream(this.fileOutputStream, this.getBufferSize()));
        this.setTracePrintStream(new TracePrintStream(this.getBufferedOutputStream(), this.getThreadMap()));

        this.getTracePrintStream().printf("--> TraceLog opened!%n");
        this.getTracePrintStream().printf("    Time     : %tc%n", new Date());
        this.getTracePrintStream().printf("    Bufsize  : %d%n", this.getBufferSize());
        this.getTracePrintStream().printf("    Autoflush: %b%n%n", this.isAutoflush());
        this.setOpened(true);
      }
      else {
        System.err.println("WARNING: Tracelog is opened already.");
      }
    }
    catch (FileNotFoundException ex) {
      ex.printStackTrace(System.err);
    }
  }
634492
@Override
	public void open(FileInputSplit split) throws IOException {
		// read Excel
		super.open(split);
		// infer schema (requires to read file again)
		if (this.customSchema == null) {
			ExcelFlinkFileInputFormat effif = new ExcelFlinkFileInputFormat(this.shocr);
			effif.open(split);
			SpreadSheetCellDAO[] currentRow = effif.nextRecord(null);
			int i = 0;
			while ((currentRow != null) && (i != this.maxInferRows)) {
				this.converter.updateSpreadSheetCellRowToInferSchemaInformation(currentRow);
				i++;
				currentRow = effif.nextRecord(null);
			}
			effif.close();
			this.customSchema = this.converter.getSchemaRow();
		} else {
			this.converter.setSchemaRow(this.customSchema);
		}
	}
939795
private void createResourceFolder() throws IOException {
        if(!Files.exists(resourceLocation.toPath()))
            Files.createDirectories(resourceLocation.toPath());
    }
918500
@Override
	public void open(FileInputSplit split) throws IOException {
		super.open(split);
		
		// instantiate the parsers
		@SuppressWarnings("unchecked")
		FieldParser<Object>[] parsers = new FieldParser[fieldTypes.length];
		
		for (int i = 0; i < fieldTypes.length; i++) {
			if (fieldTypes[i] != null) {
				Class<? extends FieldParser<?>> parserType = FieldParser.getParserForType(fieldTypes[i]);
				if (parserType == null) {
					throw new RuntimeException("No parser available for type '" + fieldTypes[i].getName() + "'.");
				}
				

				@SuppressWarnings("unchecked")
				FieldParser<Object> p = (FieldParser<Object>) InstantiationUtil.instantiate(parserType, FieldParser.class);
				parsers[i] = p;
			}
		}
		this.fieldParsers = parsers;
		
		// skip the first line, if we are at the beginning of a file and have the option set
		if (this.skipFirstLineAsHeader && this.splitStart == 0) {
			readLine(); // read and ignore
		}
	}
253250
public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException {
        if (this.svgCacheDir != null) {
            return new FileOutputStream(new File(this.svgCacheDir, name), mode == Context.MODE_APPEND);
        }
        return this.application.openFileOutput(name, mode);
    }