Example usage for java.io File separatorChar

List of usage examples for java.io File separatorChar

Introduction

In this page you can find the example usage for java.io File separatorChar.

Prototype

char separatorChar

To view the source code for java.io File separatorChar.

Click Source Link

Document

The system-dependent default name-separator character.

Usage

From source file:com.jaxio.celerio.template.pack.PackLoader.java

private void addTemplatePacksDefinedInXML(List<TemplatePack> packs) {
    List<Pack> packsInConfig = config.getCelerio().getConfiguration().getPacks();

    for (Pack packInConfig : packsInConfig) {
        if (!packInConfig.isEnable()) {
            log.warn("The pack " + packInConfig.getName() + " has been disabled");
            continue;
        }/*from w  w  w  .j  a va  2 s.  c o m*/

        // pack in local folder
        if (packInConfig.hasPath() && packInConfig.hasName()) {
            // the root is the folder that contains both "celerio" folder and "META-INF" folder
            File packRoot = new File(config.getBaseDir() + File.separatorChar + packInConfig.getPath());
            if (packRoot.exists()) {
                try {
                    File celerioPackXml = new File(packRoot, LOCAL_CELERIO_PACK);
                    if (celerioPackXml.exists()) {
                        CelerioPack celerioPack = celerioPackConfigLoader.load(celerioPackXml);
                        TemplatePackInfo templatePackInfo = new TemplatePackInfo(celerioPack);
                        templatePackInfo.overrideProperties(packInConfig.getProperties());
                        packs.add(new LocalResourcePackFile(templatePackInfo, new File(packRoot,
                                "celerio" + File.separatorChar + celerioPack.getPackName().getValue())));
                    } else {
                        log.error("Skipping pack " + packInConfig + " the file "
                                + celerioPackXml.getAbsolutePath() + " is missing");
                    }
                } catch (IOException ioe) {
                    log.error("Could not load the pack " + packInConfig, ioe);
                }
            } else {
                log.warn("The packPath " + packInConfig.getPath() + " for the pack " + packInConfig.getName()
                        + " does not exist!");
            }
            continue;
        }

        // pack in jar on classpath
        if (!packInConfig.hasPath() && packInConfig.hasName()) {
            TemplatePack tp = null;
            try {
                tp = getPackFromClassPath(packInConfig);
                packs.add(tp);
            } catch (TemplatePackNotFoundException tpnfe) {
                // when working with multi maven projets with a single conf, the packs
                // are filtered out by simply not providing them on the classpath.
                // It is therefore ok to skip not found packs.
                log.warn(tpnfe.getMessage());
            }
            continue;
        }

        log.warn("Found an invalid pack declaration: " + packInConfig);
    }
}

From source file:eionet.gdem.utils.Utils.java

/**
 * Saving an URL stream to the specified text file.
 * @param srcUrl Source URL//from   w w w . ja v a2s.  c o m
 * @throws IOException If an error occurs.
 */
public static String saveSrcFile(String srcUrl) throws IOException {

    String fileName = null;
    String tmpFileName = Properties.tmpFolder + File.separatorChar + "gdem_" + System.currentTimeMillis()
            + ".xml";
    InputStream is = null;
    FileOutputStream fos = null;

    try {

        URL url = new URL(srcUrl);
        is = url.openStream();
        File file = new File(tmpFileName);
        fos = new FileOutputStream(file);

        int bufLen = 0;
        byte[] buf = new byte[1024];

        while ((bufLen = is.read(buf)) != -1) {
            fos.write(buf, 0, bufLen);
        }

        fileName = tmpFileName;
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception e) {
            }
        }
        if (fos != null) {
            try {
                fos.flush();
                fos.close();
            } catch (Exception e) {
            }
        }
    }

    return fileName;

}

From source file:com.nridge.core.base.std.FilUtl.java

/**
 * Generates a unique path and file name combination based on the parameters
 * provided./*  ww w.  j  a v a  2s . c o  m*/
 *
 * @param aPathName Path name.
 * @param aFilePrefix File name prefix (appended with random id)
 * @param aFileExtension File name extension.
 *
 * @return A unique path and file name combination.
 */
static public String generateUniquePathFileName(String aPathName, String aFilePrefix, String aFileExtension) {
    String pathFileName;

    if (StringUtils.isNotEmpty(aPathName))
        pathFileName = String.format("%s%c%s", aPathName, File.separatorChar, aFilePrefix);
    else
        pathFileName = aFilePrefix;

    // http://www.javapractices.com/topic/TopicAction.do?Id=56

    UUID uniqueId = UUID.randomUUID();
    byte idBytes[] = uniqueId.toString().getBytes();
    Checksum checksumValue = new CRC32();
    checksumValue.update(idBytes, 0, idBytes.length);
    long longValue = checksumValue.getValue();

    if (StringUtils.startsWith(aFileExtension, "."))
        return String.format("%s_%d%s", pathFileName, longValue, aFileExtension);
    else
        return String.format("%s_%d.%s", pathFileName, longValue, aFileExtension);
}

From source file:com.agomezmoron.pageObjects.BasePage.java

/**
 * This method builds the file selector path for each Page Object.
 * //from   www .  java 2  s . c  o  m
 * @return the file selectors path.
 */
protected String getSelectorsFilePath() {
    String filePath = "selectors" + File.separatorChar;
    String baseName = this.getClass().getSimpleName().replace("Page", "").toLowerCase();
    filePath += baseName + ".properties";
    return filePath;
}

From source file:edu.du.penrose.systems.fedoraProxy.util.FedoraProxyServletContextListener.java

public void contextInitialized(ServletContextEvent context) {

    FedoraProxyServletContextListener.myServletContext = context.getServletContext();

    String realPath = myServletContext.getRealPath("/");
    if (!realPath.endsWith("" + File.separatorChar)) {
        realPath = realPath + File.separatorChar;
    }//  w  ww  .  ja  va  2s.  co m

    System.setProperty("fedoraProxy.root", realPath);
}

From source file:AppMain.java

@Override
public void handle(Request request, Response response) {

    long time = System.currentTimeMillis();
    System.out.print(request.getPath().toString() + "\t" + request.getValues("Host") + " ");
    System.out.println(request.getValues("User-agent") + " ");
    response.setDate("Date", time);
    try {//ww  w  .j  a  v  a 2s .  c om

        //static? send the file
        if (request.getPath().toString().startsWith("/static/")) {
            String path = request.getPath().toString().substring("/static/".length());
            File requested = new File("static" + File.separatorChar + path.replace('/', File.separatorChar));
            if (!requested.getCanonicalPath().startsWith(new File("static").getCanonicalPath())) {
                System.err.println("Error, path outside the static folder:" + path);
                return;
            }
            if (!requested.isFile()) {
                System.err.println("Error, file not found:" + path);
                return;
            }
            //valid path, send it
            String mimet = URLConnection.guessContentTypeFromName(path);
            if (path.endsWith(".js"))
                mimet = "application/javascript";
            if (path.endsWith(".css"))
                mimet = "text/css";
            System.out.println("sending static resource:'" + path + "' mimetype:" + mimet);
            response.setDate("Date", requested.lastModified());
            try (PrintStream body = response.getPrintStream()) {
                response.setValue("Content-Type", mimet);
                FileInputStream fis = new FileInputStream(requested);
                //copy the stream
                IOUtils.copy(fis, body);
                fis.close();
            }
            return;
        }
        //main page, show the index
        if (request.getPath().toString().equals("/")) {
            try (PrintStream body = response.getPrintStream()) {
                response.setValue("Content-Type", "text/html;charset=utf-8");
                File file = new File("index.html");
                System.out.println(file.getAbsolutePath());
                byte[] data;
                try (FileInputStream fis = new FileInputStream(file)) {
                    data = new byte[(int) file.length()];
                    fis.read(data);
                }
                body.write(data);
            }
        }

        if (request.getPath().toString().startsWith("/parse")) {
            response.setValue("Content-Type", "application/json;charset=utf-8");
            try (PrintStream body = response.getPrintStream()) {
                String text = request.getQuery().get("text");
                String pattern = request.getQuery().get("pattern");
                if (text == null || pattern == null) {
                    body.write("{'error':'pattern or text not specified'}".getBytes("UTF-8"));
                    body.close();
                }
                System.err.println("request to parse text: " + text + "\nfor pattern: " + pattern);
                MatchingResults results = null;
                JSONObject ret = new JSONObject();
                try {
                    long start = System.currentTimeMillis();
                    results = fm.matches(text, pattern, FlexiMatcher.getDefaultAnnotator(), true, false, true);
                    ret.put("time to parse", System.currentTimeMillis() - start);
                } catch (RuntimeException r) {
                    body.write(("{\"error\":" + JSONObject.quote(r.getMessage()) + "}").getBytes("UTF-8"));
                    body.close();
                    return;
                }
                ret.put("matches", results.isMatching());
                ret.put("empty_match", results.isEmptyMatch());
                ret.put("text", text);
                ret.put("pattern", pattern);
                if (!results.getAnnotations().isPresent()) {
                    body.write(ret.toString().getBytes("UTF-8"));
                    body.close();
                    return;
                }
                for (LinkedList<TextAnnotation> interpretation : results.getAnnotations().get()) {
                    JSONObject addMe = new JSONObject();

                    for (TextAnnotation v : interpretation) {
                        addMe.append("annotations", new JSONObject(v.toJSON()));
                    }
                    ret.append("interpretations", addMe);
                }
                body.write(ret.toString(1).getBytes("UTF-8"));
            }
            return;
        }

        if (request.getPath().toString().startsWith("/trace")) {
            response.setValue("Content-Type", "application/json;charset=utf-8");
            try (PrintStream body = response.getPrintStream()) {
                String text = request.getQuery().get("text");
                String pattern = request.getQuery().get("pattern");
                if (text == null || pattern == null) {
                    body.write("{'error':'pattern or text not specified'}".getBytes("UTF-8"));
                    body.close();
                }
                System.err.println("request to parse text: " + text + "\nfor pattern: " + pattern);
                JSONObject ret = new JSONObject();
                ListingAnnotatorHandler ah;
                try {
                    long start = System.currentTimeMillis();
                    ah = new ListingAnnotatorHandler();
                    fm.matches(text, pattern, ah, true, false, true);
                    ret.put("time", System.currentTimeMillis() - start);
                } catch (RuntimeException r) {
                    body.write(("{\"error\":" + JSONObject.quote(r.getMessage()) + "}").getBytes("UTF-8"));
                    body.close();
                    return;
                }
                ret.put("text", text);
                ret.put("pattern", pattern);
                LinkedList<TextAnnotation> nonOverlappingTA = new LinkedList<>();
                JSONObject addMe = new JSONObject();
                for (TextAnnotation v : ah.getAnnotations()) {
                    if (nonOverlappingTA.stream().anyMatch(p -> p.getSpan().intersects(v.getSpan()))) {
                        ret.append("interpretations", addMe);
                        addMe = new JSONObject();
                        addMe.append("annotations", new JSONObject(v.toJSON()));
                        nonOverlappingTA.clear();
                    } else {
                        addMe.append("annotations", new JSONObject(v.toJSON()));
                    }
                    nonOverlappingTA.add(v);

                }
                ret.append("interpretations", addMe);
                body.write(ret.toString(1).getBytes("UTF-8"));
            }
            return;
        }

        if (request.getPath().toString().startsWith("/addtag")) {
            if (tagCount == 0)
                fwTag.write("\n#tags added from web interface at " + LocalDate.now().toString() + "\n");

            tagCount++;
            response.setValue("Content-Type", "application/json;charset=utf-8");
            try (PrintStream body = response.getPrintStream()) {
                String tag = request.getQuery().getOrDefault("tag", "");
                String pattern = request.getQuery().getOrDefault("pattern", "");

                if (tag.isEmpty() || pattern.isEmpty()) {
                    body.write("{\"error\":\"tag or pattern not specified\"}".getBytes("UTF-8"));
                    body.close();
                    return;
                }

                String identifier = request.getQuery().getOrDefault("identifier", "");
                String annotationTemplate = request.getQuery().getOrDefault("annotation_template", "").trim();

                if (identifier.isEmpty()) {
                    identifier = "auto_" + LocalDate.now().toString() + "_" + tagCount;
                }

                //check that rule identifiers are known
                for (String part : ExpressionParser.split(pattern)) {
                    if (!part.startsWith("["))
                        continue;
                    if (!fm.isBoundRule(ExpressionParser.ruleName(part))) {
                        body.write(("{\"error\":\"rule '" + ExpressionParser.ruleName(part) + "' non known\"}")
                                .getBytes("UTF-8"));
                        body.close();
                        return;
                    }
                }

                fwTag.write(tag + "\t" + pattern + "\t" + identifier + "\t" + annotationTemplate + "\n");
                fwTag.flush();
                if (annotationTemplate.isEmpty())
                    fm.addTagRule(tag, pattern, identifier);
                else
                    fm.addTagRule(tag, pattern, identifier, annotationTemplate);
                body.write(("{\"identifier\":" + JSONObject.quote(identifier) + "}").getBytes("UTF-8"));
            }
            return;

        }
        //unknown request
        try (PrintStream body = response.getPrintStream()) {
            response.setValue("Content-Type", "text/plain");
            response.setDate("Last-Modified", time);
            response.setCode(401);
            body.println("HTTP request for page '" + request.getPath().toString() + "' non understood in "
                    + this.getClass().getCanonicalName());
        }
    } catch (IOException | JSONException e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:aiai.ai.station.StationService.java

@PostConstruct
public void init() {
    if (!globals.isStationEnabled) {
        return;// w  w  w.  j  a va  2  s. c  o  m
    }

    final File file = new File(globals.stationDir, Consts.ENV_YAML_FILE_NAME);
    if (!file.exists()) {
        log.warn("Station's environment config file doesn't exist: {}", file.getPath());
        return;
    }
    try {
        env = FileUtils.readFileToString(file, Charsets.UTF_8);
        envYaml = EnvYamlUtils.toEnvYaml(env);
        if (envYaml == null) {
            log.error("env.yaml wasn't found or empty. path: {}{}env.yaml", globals.stationDir,
                    File.separatorChar);
            throw new IllegalStateException("Station isn't configured, env.yaml is empty or doesn't exist");
        }
    } catch (IOException e) {
        log.error("Error", e);
        throw new IllegalStateException("Error while loading file: " + file.getPath(), e);
    }

    final File metadataFile = new File(globals.stationDir, Consts.METADATA_YAML_FILE_NAME);
    if (!metadataFile.exists()) {
        log.warn("Station's metadata file doesn't exist: {}", file.getPath());
        return;
    }
    try (FileInputStream fis = new FileInputStream(metadataFile)) {
        metadata = MetadataUtils.to(fis);
    } catch (IOException e) {
        log.error("Error", e);
        throw new IllegalStateException("Error while loading file: " + metadataFile.getPath(), e);
    }
    //noinspection unused
    int i = 0;
}

From source file:at.medevit.elexis.gdt.tools.GDTFileHelper.java

public static String determineOutgoingFileName(IGDTCommunicationPartner cp) {
    String directory = cp.getOutgoingDirectory();
    String filenameHeader = cp.getShortIDReceiver() + CoreHub.localCfg
            .get(GDTPreferenceConstants.CFG_GDT_FILETRANSFER_SHORTNAME, GDTConstants.GDT_SHORT_ID_DEFAULT);
    String filename = null;//  w  w  w  . ja va 2  s  .  c o  m

    if (cp.getRequiredFileType().equalsIgnoreCase(GDTConstants.GDT_FILETRANSFER_TYP_FEST)) {
        if (cp.getFixedCommmunicationFileName() != null) {
            filename = cp.getFixedCommmunicationFileName();
        } else {
            filename = filenameHeader + ".GDT";
        }
    } else if (cp.getRequiredFileType().equalsIgnoreCase(GDTConstants.GDT_FILETRANSFER_TYPE_HOCHZAEHLEND)) {
        int counter = 0;
        while (true) {
            filename = filenameHeader + "." + threePlaces.format(counter);
            File file = new File(directory + File.separatorChar + filename);
            if (file.exists()) {
                counter++;
            } else {
                break;
            }
        }
    } else {
        logger.log("Invalid file transfer type returned, neither fest nor hochzaehlend!", Log.ERRORS);
    }
    return filename;
}

From source file:de.egore911.versioning.deployer.performer.PerformCheckout.java

private static void performSvn(String target, String url) {
    String tmp = target + File.separatorChar + "checkout";
    try {//from   w ww  .  java2 s .  c om
        File tmpDir = new File(tmp);
        SVNURL svnurl = SVNURL.parseURIEncoded(url);
        SvnOperationFactory svnOperationFactory = new SvnOperationFactory();
        try {
            SvnCheckout checkout = svnOperationFactory.createCheckout();
            checkout.setSingleTarget(SvnTarget.fromFile(tmpDir));
            checkout.setSource(SvnTarget.fromURL(svnurl));
            checkout.run();
        } finally {
            svnOperationFactory.dispose();
        }
        FileUtils.copyDirectory(tmpDir, new File(target));
        FileUtils.deleteDirectory(tmpDir);
    } catch (SVNException | IOException e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:de.thb.ue.backend.service.ParticipantService.java

@Override
public List<Participant> add(int amount, Evaluation evaluation)
        throws EvaluationException, ParticipantException {
    List<Participant> createdParticipants = new ArrayList<>(amount);
    List<BufferedImage> qrcs = new ArrayList<>(amount);
    for (int i = 0; i < amount; i++) {
        String voteToken = UUID.randomUUID().toString();
        createdParticipants.add(new Participant(evaluation, false, voteToken, ""));
        try {/*from  www  . j  a  va 2s  .c o m*/
            qrcs.add(QRCGeneration.generateQRC(
                    "{\"voteToken\":\"" + voteToken + "\",\"host\":\"" + hostadress + "\"}",
                    QRCGeneration.SIZE_SMALL, ErrorCorrectionLevel.Q, QRCGeneration.ENCODING_UTF_8));
        } catch (WriterException | IOException e) {
            throw new ParticipantException(ParticipantException.ERROR_CREATING_QRC_PDF, e.getMessage());
        }
    }
    participantRepo.save(createdParticipants);
    File workingDirectory = new File(
            (workingDirectoryPath.isEmpty() ? "" : (workingDirectoryPath + File.separatorChar))
                    + evaluation.getUid());

    if (!workingDirectory.exists()) {
        try {
            FileUtils.forceMkdir(workingDirectory);
        } catch (IOException e) {
            log.error("Can't create directory for " + evaluation.getUid());
        }
    }

    PDFGeneration.createQRCPDF(qrcs, evaluation.getUid(), evaluation.getSubject().getName(),
            evaluation.getSemesterType(), LocalDate.now().getYear(), workingDirectory);
    return createdParticipants;
}