Example usage for java.lang ClassLoader getResourceAsStream

List of usage examples for java.lang ClassLoader getResourceAsStream

Introduction

In this page you can find the example usage for java.lang ClassLoader getResourceAsStream.

Prototype

public InputStream getResourceAsStream(String name) 

Source Link

Document

Returns an input stream for reading the specified resource.

Usage

From source file:org.apache.oozie.service.TestXLogStreamingService.java

public void testAuditLog() throws Exception {
    setupXLog();/*from ww  w .java 2s. c o  m*/
    XLogFilter xf = new XLogAuditFilter(new XLogUserFilterParam(null));
    xf.setParameter("USER", "oozie");
    xf.setLogLevel("DEBUG|INFO");
    File log4jFile = new File(getTestCaseConfDir(), "test-log4j.properties");
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    InputStream is = cl.getResourceAsStream("test-no-dash-log4j.properties");
    Properties log4jProps = new Properties();
    log4jProps.load(is);
    // prevent conflicts with other tests by changing the log file location
    log4jProps.setProperty("log4j.appender.oozie.File", getTestCaseDir() + "/oozie.log");
    log4jProps.setProperty("log4j.appender.oozieaudit.File", getTestCaseDir() + "/oozie-audit.log");

    log4jProps.store(new FileOutputStream(log4jFile), "");
    setSystemProperty(XLogService.LOG4J_FILE, log4jFile.getName());
    try {
        new Services().init();
        XLog auditLog = XLog.getLog("oozieaudit");
        xf.setParameter(DagXLogInfoService.JOB, "0000000-150322000230582-oozie-puru-C");

        auditLog.info(
                "2015-03-22 00:04:35,494  INFO oozieaudit:520 - IP [127.0.0.1], USER [purushah], GROUP [null], "
                        + "APP [-], JOBID [0000000-150322000230582-oozie-puru-C], OPERATION [start], "
                        + "PARAMETER [null], STATUS [SUCCESS], HTTPCODE [200], ERRORCODE [null], ERRORMESSAGE [L1]");
        auditLog.info(
                "2015-03-22 00:05:13,823  INFO oozieaudit:520 - IP [127.0.0.1], USER [purushah], GROUP [null], "
                        + "APP [-], JOBID [0000000-150322000230582-oozie-puru-C], OPERATION [suspend], "
                        + "PARAMETER [0000000-150322000230582-oozie-puru-C], STATUS [SUCCESS], HTTPCODE [200], ERRORCODE [null], "
                        + "ERRORMESSAGE [L2]");
        auditLog.info(
                "2015-03-22 00:05:13,823  INFO oozieaudit:520 - IP [127.0.0.1], USER [purushah], GROUP [null], "
                        + "APP [-], JOBID [0000001-150322000230582-oozie-puru-C], OPERATION [suspend], "
                        + "PARAMETER [0000001-150322000230582-oozie-puru-C], STATUS [SUCCESS], HTTPCODE [200], ERRORCODE [null], "
                        + "ERRORMESSAGE [L3]");

        String out = doStreamAuditLog(xf);
        String outArr[] = out.split("\n");
        // Lines 2 and 4 are filtered out because they have the wrong user
        assertEquals(2, outArr.length);
        assertTrue(outArr[0].contains("L1"));
        assertTrue(out.contains("L2"));
        assertFalse(out.contains("L3"));

    } finally {
        Services.get().destroy();
    }
}

From source file:com.vmware.vhadoop.vhm.hadoop.HadoopAdaptor.java

private byte[] loadLocalScript(String fileName) {
    ClassLoader cl = HadoopAdaptor.class.getClassLoader();
    InputStream is = ((cl != null) && (fileName != null)) ? cl.getResourceAsStream(fileName) : null;
    if (is == null) {
        _log.log(Level.SEVERE, "VHM: class loader resource " + fileName + " is unavailable");
        return null;
    }//  www  .  j  av  a 2s. c o m

    byte[] result = null;
    try {
        result = IOUtils.toByteArray(is);
    } catch (IOException e) {
        _log.log(Level.SEVERE, "VHM: exception converting class loader resource " + fileName
                + " to byte array - " + e.getMessage());
        _log.log(Level.INFO, "VHM: exception converting class loader resource " + fileName + " to byte array",
                e);
    }

    try {
        is.close();
    } catch (IOException e) {
        _log.fine("VHM: exception closing stream for class loader resource " + fileName);
    }

    return result;
}

From source file:Engine.WorldMap.java

public WorldMap() {
    Map = new double[mapSize][];

    for (int a = 0; a < mapSize; a++) {
        Map[a] = new double[mapSize];
    }//w w w  . ja v a2  s . c  o  m
    //z jakiego powodu tu byo -1, ale ju nie wiem dlaczego
    /*
    ObjectsMap = new ArrayList[mapSize-1][];
    for (int a = 0; a < mapSize-1; a++)
    {
    ObjectsMap[a] = new ArrayList[mapSize-1];
    }
    for (int x = 0; x < mapSize-1; x++) {
       for(int y = 0; y < mapSize-1; y++) {
                ObjectsMap[x][y] = new ArrayList<IRenderableGameObject>();
            }
    }*/
    ObjectsMap = new ArrayList[mapSize][];
    for (int a = 0; a < mapSize; a++) {
        ObjectsMap[a] = new ArrayList[mapSize];
    }
    for (int x = 0; x < mapSize; x++) {
        for (int y = 0; y < mapSize; y++) {
            ObjectsMap[x][y] = new ArrayList<IRenderableGameObject>();
        }
    }

    for (int x = 0; x < mapSize; x++) {
        for (int y = 0; y < mapSize; y++) {
            //ObjectsMap[x][y] = new ArrayList<IRenderableGameObject>();
            Map[x][y] = NoiseHelper(x, y);
            double min = Math.min(Math.abs(mapSize - x - 1), Math.abs(x));
            min = Math.min(min, Math.abs(mapSize - y - 1));
            min = Math.min(min, Math.abs(y));
            if (min < cooling) {
                Map[x][y] *= min / cooling;
            }
        }
    }
    /*
    Map[1][1] = 10;
    Map[3][1] = 20;
    Map[5][1] = 30;
    Map[7][1] = 40;
    Map[9][1] = 50;
    Map[11][1] = 60;*/

    if (startForceCalculator) {
        BufferedImage bufferedImage;
        try {
            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
            InputStream is = classloader.getResourceAsStream("./Images/LUT-1.bmp");

            ///img = ImageIO.read(new File("/Images/face.jpg"));
            bufferedImage = ImageIO.read(is);
            is.close();

            //bufferedImage = ImageIO.read(new File("e:\\Projects\\java 3d tutorial\\Game\\LUT-1.bmp"));
            LUT = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();
        } catch (IOException ex) {
            Logger.getLogger(MapDrawer.class.getName()).log(Level.SEVERE, null, ex);
        }

        ForceCalculator fc = new ForceCalculator(width, height);

        for (int a = 0; a < sourcesCount; a++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int[] fv = new int[4];
            int which = random.nextInt(4);
            fv[which] = random.nextInt(maxRandom);
            //fv[1] = random.nextInt(maxRandom);
            //fv[2] = random.nextInt(maxRandom);
            //fv[3] = random.nextInt(maxRandom);
            int[] maxR = new int[4];
            for (int b = 0; b < maxR.length; b++)
                maxR[b] = maxRadius;
            ForceDescription fd = new ForceDescription(x, y, fv, width, height, maxR);
            forces.add(fd);
        }

        map = fc.map;
        forceMap = fc.forceMap;
        heightMap = fc.heighMap;

        HeightMapToMap();

        ForceCalculatorWorker fcw = new ForceCalculatorWorker(fc, this);
        fcw.start();
        MoveForcesHelperWorker mfhw = new MoveForcesHelperWorker(forces, width, height);
        mfhw.start();
    }
}

From source file:net.ontopia.topicmaps.xml.TMXMLReader.java

private InputSource getTMXMLSchema() throws IOException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    InputStream i = cl.getResourceAsStream("net/ontopia/topicmaps/xml/tmxml.rnc");
    return new InputSource(i);
}

From source file:edu.harvard.hul.ois.fits.service.servlets.FitsServlet.java

public void init() throws ServletException {

    // "fits.home" property set differently in Tomcat 7 and JBoss 7.
    // Tomcat: set in catalina.properties
    // JBoss: set as a command line value "-Dfits.home=<path/to/fits/home>
    fitsHome = System.getProperty(FITS_HOME_SYSTEM_PROP_NAME);
    logger.info(FITS_HOME_SYSTEM_PROP_NAME + ": " + fitsHome);

    if (StringUtils.isEmpty(fitsHome)) {
        logger.fatal(FITS_HOME_SYSTEM_PROP_NAME
                + " system property HAS NOT BEEN SET!!! This web application will not properly run.");
        throw new ServletException(FITS_HOME_SYSTEM_PROP_NAME
                + " system property HAS NOT BEEN SET!!! This web application will not properly run.");
    }// www.j  av a 2 s  . c  om

    // Set the projects properties.
    // First look for a system property pointing to a project properties file. (e.g. - file:/path/to/file)
    // If this value either does not exist or is not valid, the default
    // file that comes with this application will be used for initialization.
    String environmentProjectPropsFile = System.getProperty(ENV_PROJECT_PROPS);
    logger.info(
            "Value of environment property: [ + ENV_PROJECT_PROPS + ] for finding external properties file in location: ["
                    + environmentProjectPropsFile + "]");
    if (environmentProjectPropsFile != null) {
        logger.info("Will look for properties file from environment in location: ["
                + environmentProjectPropsFile + "]");
        try {
            File projectProperties = new File(environmentProjectPropsFile);
            if (projectProperties.exists() && projectProperties.isFile() && projectProperties.canRead()) {
                InputStream is = new FileInputStream(projectProperties);
                applicationProps = new Properties();
                applicationProps.load(is);
            }
        } catch (IOException e) {
            // fall back to default file
            logger.error("Unable to load properties file: [" + environmentProjectPropsFile + "] -- reason: "
                    + e.getMessage(), e);
            logger.error("Falling back to default project.properties file: [" + PROPERTIES_FILE_NAME + "]");
            applicationProps = null;
        }
    }

    if (applicationProps == null) { // did not load from environment variable location
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            InputStream resourceStream = classLoader.getResourceAsStream(PROPERTIES_FILE_NAME);
            if (resourceStream != null) {
                applicationProps = new Properties();
                applicationProps.load(resourceStream);
                logger.info("loaded default applicationProps");
            } else {
                logger.warn("project.properties not found!!!");
            }
        } catch (IOException e) {
            logger.error("Could not load properties file: [" + PROPERTIES_FILE_NAME + "]", e);
            // couldn't load default properties so bail...
            throw new ServletException("Couldn't load an applications properties file.", e);
        }
    }
    int maxPoolSize = Integer
            .valueOf(applicationProps.getProperty("max.objects.in.pool", DEFAULT_MAX_OBJECTS_IN_POOL));
    maxFileUploadSizeMb = Long
            .valueOf(applicationProps.getProperty("max.upload.file.size.MB", DEFAULT_MAX_UPLOAD_SIZE));
    maxRequestSizeMb = Long
            .valueOf(applicationProps.getProperty("max.request.size.MB", DEFAULT_MAX_REQUEST_SIZE));
    maxInMemoryFileSizeMb = Integer
            .valueOf(applicationProps.getProperty("max.in.memory.file.size.MB", DEFAULT_IN_MEMORY_FILE_SIZE));
    logger.info("Max objects in object pool: " + maxPoolSize + " -- Max file upload size: "
            + maxFileUploadSizeMb + "MB -- Max request object size: " + maxRequestSizeMb
            + "MB -- Max in-memory file size: " + maxInMemoryFileSizeMb + "MB");

    logger.debug("Initializing FITS pool");
    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setMinIdle(MIN_IDLE_OBJECTS_IN_POOL);
    poolConfig.setMaxTotal(maxPoolSize);
    poolConfig.setTestOnBorrow(true);
    poolConfig.setBlockWhenExhausted(true);
    fitsWrapperPool = new FitsWrapperPool(new FitsWrapperFactory(), poolConfig);
    logger.debug("FITS pool finished Initializing");

    String uploadBaseDirName = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
    uploadBaseDir = new File(uploadBaseDirName);
    if (!uploadBaseDir.exists()) {
        uploadBaseDir.mkdir();
        logger.info("Created upload base directory: " + uploadBaseDir.getAbsolutePath());
    }
}

From source file:org.apache.oozie.service.TestXLogStreamingService.java

public void testErrorLog() throws Exception {
    setupXLog();//from w w w . j  a va2 s .com
    XLogFilter xf = new XLogFilter(new XLogUserFilterParam(null));
    xf.setParameter("USER", "oozie");
    xf.setLogLevel("DEBUG|INFO");
    // Previously, a dash ("-") was always required somewhere in a line in order for that line to pass the filter; this test
    // checks that this condition is no longer required for log streaming to work
    File log4jFile = new File(getTestCaseConfDir(), "test-log4j.properties");
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    InputStream is = cl.getResourceAsStream("test-no-dash-log4j.properties");
    Properties log4jProps = new Properties();
    log4jProps.load(is);
    // prevent conflicts with other tests by changing the log file location
    log4jProps.setProperty("log4j.appender.oozie.File", getTestCaseDir() + "/oozie.log");
    log4jProps.setProperty("log4j.appender.oozieError.File", getTestCaseDir() + "/oozie-error.log");

    log4jProps.store(new FileOutputStream(log4jFile), "");
    setSystemProperty(XLogService.LOG4J_FILE, log4jFile.getName());
    try {
        new Services().init();
        assertFalse(doStreamDisabledCheck());
        LogFactory.getLog("a")
                .info("2009-06-24 02:43:14,505 INFO _L1_:317 - SERVER[foo] USER[oozie] GROUP[oozie] TOKEN[-] "
                        + "APP[-] JOB[-] ACTION[-] Released Lock");
        LogFactory.getLog("a")
                .warn("2009-06-24 02:44:14,505 WARN _L2_:317 - SERVER[foo] USER[oozie] GROUP[oozie] TOKEN[-] "
                        + "APP[-] JOB[-] ACTION[-] Error while writing to file");
        LogFactory.getLog("a")
                .info("2009-06-24 02:45:14,505 INFO _L3_:317 - SERVER[foo] USER[blah] GROUP[oozie] TOKEN[-]"
                        + "APP[-] JOB[-] ACTION[-] Released Lock");
        LogFactory.getLog("a")
                .error("2009-06-24 02:46:14,505 ERROR _L4_:317 - SERVER[foo] USER[oozie] GROUP[oozie] TOKEN[-] "
                        + "APP[-] JOB[-] ACTION[-] Error while writing to DB");
        LogFactory.getLog("a")
                .info("2009-06-24 02:47:14,505 INFO _L5_:317 SERVER[foo] USER[oozie] GROUP[oozie] TOKEN[-] "
                        + "APP[-] JOB[-] ACTION[-] Released Lock");
        LogFactory.getLog("a")
                .fatal("2009-06-24 02:48:14,505 FATAL _L6_:317 SERVER[foo] USER[blah] GROUP[oozie] TOKEN[-] "
                        + "APP[-] JOB[-] ACTION[-] Released Lock");
        String out = doStreamLog(xf);
        String outArr[] = out.split("\n");
        // Lines 2 and 4 are filtered out because they have the wrong user
        assertEquals(2, outArr.length);
        assertTrue(outArr[0].contains("_L1_"));
        assertFalse(out.contains("_L3_"));
        assertTrue(outArr[1].contains("_L5_"));
        assertFalse(out.contains("_L4_"));
        XLogFilter.reset();
        XLogFilter.defineParameter("USER");
        XLogFilter.defineParameter("GROUP");
        XLogFilter.defineParameter("TOKEN");
        XLogFilter.defineParameter("APP");
        XLogFilter.defineParameter("JOB");
        XLogFilter.defineParameter("ACTION");
        xf = new XLogFilter(new XLogUserFilterParam(null));

        xf.setParameter("USER", "oozie");

        String errorOut = doStreamErrorLog(xf);
        String errorOutArr[] = errorOut.split("\n");
        // Lines 2 and 4 are filtered out because they have the wrong user
        assertEquals(2, errorOutArr.length);
        assertTrue(errorOutArr[0].contains("_L2_"));
        assertTrue(errorOutArr[1].contains("_L4_"));
        assertFalse(errorOut.contains("_L6_"));
    } finally {
        Services.get().destroy();
    }
}

From source file:com.vmware.identity.idm.server.RsaAgentConfFilesUpdater.java

/**
* Update rsa_api.properties, sdconf.rec, sdopts.rec on local sso server conf directory
* @param tenantInfo//  www.  ja  v  a2s  .co  m
* @param rsaConfig
* @throws Exception
*/
public void updateRSAConfigFiles(TenantInformation tenantInfo, RSAAgentConfig rsaConfig) throws Exception {

    Validate.notNull(tenantInfo, "tenantInfo");

    String tenantName = tenantInfo.getTenant().getName();
    Validate.notEmpty(tenantName, "tenantName");

    // read from template from class resource
    ClassLoader classLoader = getClass().getClassLoader();
    InputStream templateStrm = classLoader.getResourceAsStream(RSA_API_PROPERTIES_TEMPLATE);
    Validate.notNull(templateStrm, "rsa_api.properties resource not found");

    // create tenant config directory if it does not exist
    File tenantConfigDir = ensureTenantConfigDirExist(tenantName);

    // create config file
    File tenantConfigFile = new File(tenantConfigDir, RSA_API_PROPERTIES_NAME);

    BufferedReader br = new BufferedReader(new InputStreamReader(templateStrm));

    String lines = "";
    String siteID = _clusterID;
    RSAAMInstanceInfo instInfo = rsaConfig.get_instMap().get(siteID);

    if (instInfo == null) {
        // site info are not defined.
        return;
    }
    String line;
    try {
        line = br.readLine();
        String ls = System.getProperty("line.separator");
        while (line != null) {
            String[] attrVal = line.split("=");

            if (attrVal == null || attrVal.length < 1) {
                continue;
            }

            String attr = attrVal[0].replace("#", "");
            String newLine;
            switch (attr) {
            // keys that are configurable
            case RSA_AGENT_NAME:
                newLine = RSA_AGENT_NAME + "=" + instInfo.get_agentName() + ls;
                lines += newLine;
                break;

            case SDCONF_LOC: {
                byte[] sdConfBytes = instInfo.get_sdconfRec();
                Validate.notNull(sdConfBytes);

                // delete existing file.
                File sdConfFile = new File(tenantConfigDir, SD_CONF_NAME);
                sdConfFile.delete();

                // write the file
                String sdConfFilePath = sdConfFile.getAbsolutePath();
                FileOutputStream fos;
                try {
                    fos = new FileOutputStream(sdConfFilePath);
                } catch (IOException e) {
                    logger.error("Can not create or open sdconf.rec: " + sdConfFilePath, e);
                    throw e;
                }
                try {
                    fos.write(sdConfBytes);
                } catch (IOException e) {
                    logger.error("Can not write to sdconf.rec: " + sdConfFilePath, e);
                    throw e;
                } finally {
                    fos.close();
                }
                // update the api properties
                newLine = SDCONF_LOC + "=" + sdConfFilePath + ls;
                lines += StringEscapeUtils.escapeJava(newLine);

                break;
            }
            case SDOPTS_LOC: {
                byte[] sdOptsBytes = instInfo.get_sdoptsRec();
                if (sdOptsBytes == null) {
                    newLine = "#" + SDOPTS_LOC + "=" + ls;
                    lines += newLine;
                    break;
                }

                // delete existing file.
                File sdOptsFile = new File(tenantConfigDir, SD_OPTS_NAME);
                sdOptsFile.delete();

                // write the file
                String sdOptsFilePath = sdOptsFile.getAbsolutePath();
                FileOutputStream fos;
                try {
                    fos = new FileOutputStream(sdOptsFilePath);
                } catch (IOException e) {
                    logger.error("Can not create or open sdopts.rec: " + sdOptsFilePath, e);
                    throw e;
                }
                try {
                    fos.write(sdOptsBytes);
                } catch (IOException e) {
                    logger.error("Can not write to sdopts.rec: " + sdOptsFilePath, e);
                    throw e;
                } finally {
                    fos.close();
                }
                // update the api properties
                newLine = SDOPTS_LOC + "=" + sdOptsFilePath;
                lines += StringEscapeUtils.escapeJava(newLine);

                break;
            }

            case RSA_LOG_LEVEL:
                newLine = RSA_LOG_LEVEL + "=" + rsaConfig.get_logLevel() + ls;
                lines += newLine;
                break;

            case RSA_LOG_FILE_SIZE:
                newLine = RSA_LOG_FILE_SIZE + "=" + rsaConfig.get_logFileSize() + "MB" + ls;
                lines += newLine;
                break;

            case RSA_LOG_FILE_COUNT:
                newLine = RSA_LOG_FILE_COUNT + "=" + rsaConfig.get_maxLogFileCount() + ls;
                lines += newLine;
                break;

            case RSA_CONNECTION_TIMEOUT:
                newLine = RSA_CONNECTION_TIMEOUT + "=" + rsaConfig.get_connectionTimeOut() + ls;
                lines += newLine;
                break;

            case RSA_READ_TIMEOUT:
                newLine = RSA_READ_TIMEOUT + "=" + rsaConfig.get_readTimeOut() + ls;
                lines += newLine;
                break;

            case RSA_ENC_ALGLIST:
                Set<String> encSet = rsaConfig.get_rsaEncAlgList();
                Validate.notNull(encSet);
                String[] encArray = encSet.toArray(new String[encSet.size()]);

                newLine = RSA_ENC_ALGLIST + "=";
                if (encArray.length > 0) {
                    newLine += encArray[0];
                }
                for (int i = 1; i < encArray.length; i++) {
                    newLine += ("," + encArray[i]);
                }
                newLine += ls;
                lines += newLine;
                break;

            // keys that not configurable
            case RSA_AGENT_PLATFORM:
                newLine = RSA_AGENT_PLATFORM + "=";
                if (SystemUtils.IS_OS_LINUX) {
                    newLine = RSA_AGENT_PLATFORM + "=linux" + ls;
                } else {
                    newLine = RSA_AGENT_PLATFORM + "=windows" + ls;
                }
                lines += newLine;
                break;

            case RSA_CONFIG_DATA_LOC:
                newLine = RSA_CONFIG_DATA_LOC + "=" + tenantConfigDir.getAbsolutePath() + ls;
                lines += StringEscapeUtils.escapeJava(newLine);
                break;

            case SDNDSCRT_LOC:
                File sdndscrtLoc = new File(tenantConfigDir, "secureid");
                newLine = RSA_CONFIG_DATA_LOC + "=" + sdndscrtLoc.getAbsolutePath() + ls;
                lines += StringEscapeUtils.escapeJava(newLine);
                break;

            case RSA_LOG_FILE:
                String ssoConfigDir = IdmUtils.getIdentityServicesLogDir();
                File rsaLogFile = new File(ssoConfigDir, RSA_SECUREID_LOG_NAME);
                newLine = RSA_LOG_FILE + "=" + rsaLogFile.getAbsolutePath() + ls;
                lines += StringEscapeUtils.escapeJava(newLine);
                break;

            default:
                lines += (line + ls);

            }
            line = br.readLine();
        }
    } catch (IOException e) {
        logger.error("Fail to read from rsa_api.properties resource stream", e);
        throw new IDMException("Unable to generate rsa_api property file", e);
    }
    FileWriter fw;
    try {
        fw = new FileWriter(tenantConfigFile);
    } catch (IOException e) {
        logger.error("Fail to create rsa_api.properties file", e);
        throw new IDMException("Unable to generate rsa_api property file", e);
    }

    BufferedWriter out = new BufferedWriter(fw);
    try {
        tenantInfo.get_rsaConfigFilesLock().writeLock().lock();
        out.write(lines.toString());
    } catch (IOException e) {
        logger.error("Fail to write to rsa_api.properties file", e);
        throw new IDMException("Unable to generate rsa_api property file", e);
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            tenantInfo.get_rsaConfigFilesLock().writeLock().unlock();
            logger.error("Fail to close to rsa_api.properties file BufferWriter", e);
            throw new IDMException("Unable to generate rsa_api property file", e);
        }
        tenantInfo.get_rsaConfigFilesLock().writeLock().unlock();
    }
}

From source file:ai.grakn.graql.GraqlShell.java

private void printLicense() {
    StringBuilder result = new StringBuilder("");

    //Get file from resources folder
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream(LICENSE_LOCATION);

    Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name());
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        result.append(line).append("\n");
    }/*from  w w  w  . j  a  va  2  s .c  o m*/
    result.append("\n");
    scanner.close();

    this.print(result.toString());
}

From source file:edu.isi.wings.portal.controllers.ComponentController.java

public boolean initializeComponentFiles(String cid, String lang) {
    try {//from   w w  w  .  ja va  2 s.c om
        Component c = cc.getComponent(cid, true);
        String loc = c.getLocation();
        if (loc == null) {
            loc = cc.getDefaultComponentLocation(cid);
            c.setLocation(loc);
            cc.setComponentLocation(cid, loc);
            cc.save();
        }

        // Copy io.sh from resources
        ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        FileUtils.copyInputStreamToFile(classloader.getResourceAsStream("io.sh"), new File(loc + "/io.sh"));

        int numi = 0, nump = 0, numo = c.getOutputs().size();
        for (ComponentRole r : c.getInputs()) {
            if (r.isParam())
                nump++;
            else
                numi++;
        }

        String suffix = "";
        for (int i = 1; i <= numi; i++)
            suffix += " $INPUTS" + i;
        for (int i = 1; i <= nump; i++)
            suffix += " $PARAMS" + i;
        for (int i = 1; i <= numo; i++)
            suffix += " $OUTPUTS" + i;

        String runscript = "";
        String filename = null;
        for (String line : IOUtils.readLines(classloader.getResourceAsStream("run"))) {
            if (line.matches(".*io\\.sh.*")) {
                // Number of inputs and outputs
                line = ". $BASEDIR/io.sh " + numi + " " + nump + " " + numo + " \"$@\"";
            } else if (line.matches(".*generic_code.*")) {
                // Code invocation
                if (lang.equals("R")) {
                    filename = c.getName() + ".R";
                    line = "Rscript --no-save --no-restore $BASEDIR/" + filename;
                } else if (lang.equals("PHP")) {
                    filename = c.getName() + ".php";
                    line = "php $BASEDIR/" + filename;
                } else if (lang.equals("Python")) {
                    filename = c.getName() + ".py";
                    line = "python $BASEDIR/" + filename;
                } else if (lang.equals("Perl")) {
                    filename = c.getName() + ".pl";
                    line = "perl $BASEDIR/" + filename;
                } else if (lang.equals("Java")) {
                    line = "# Relies on existence of " + c.getName() + ".class file in this directory\n";
                    line += "java -classpath $BASEDIR " + c.getName();
                }
                // Add inputs, outputs as suffixes
                line += suffix;
            }
            runscript += line + "\n";
        }
        File runFile = new File(loc + "/run");
        FileUtils.writeStringToFile(runFile, runscript);
        runFile.setExecutable(true);

        if (filename != null)
            new File(loc + "/" + filename).createNewFile();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        cc.end();
        dc.end();
        prov.end();
    }
    return false;
}