Example usage for java.lang System getenv

List of usage examples for java.lang System getenv

Introduction

In this page you can find the example usage for java.lang System getenv.

Prototype

public static String getenv(String name) 

Source Link

Document

Gets the value of the specified environment variable.

Usage

From source file:com.linecorp.platform.channel.sample.Main.java

public static void main(String[] args) {

    BusinessConnect bc = new BusinessConnect();

    /**/*from  w w  w .ja  v a 2  s .  c  om*/
     * Prepare the required channel secret and access token
     */
    String channelSecret = System.getenv("CHANNEL_SECRET");
    String channelAccessToken = System.getenv("CHANNEL_ACCESS_TOKEN");
    if (channelSecret == null || channelSecret.isEmpty() || channelAccessToken == null
            || channelAccessToken.isEmpty()) {
        System.err.println("Error! Environment variable CHANNEL_SECRET and CHANNEL_ACCESS_TOKEN not defined.");
        return;
    }

    port(Integer.valueOf(System.getenv("PORT")));
    staticFileLocation("/public");

    /**
     * Define the callback url path
     */
    post("/events", (request, response) -> {
        String requestBody = request.body();

        /**
         * Verify whether the channel signature is valid or not
         */
        String channelSignature = request.headers("X-LINE-CHANNELSIGNATURE");
        if (channelSignature == null || channelSignature.isEmpty()) {
            response.status(400);
            return "Please provide valid channel signature and try again.";
        }
        if (!bc.validateBCRequest(requestBody, channelSecret, channelSignature)) {
            response.status(401);
            return "Invalid channel signature.";
        }

        /**
         * Parse the http request body
         */
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
        objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()));
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        EventList events;
        try {
            events = objectMapper.readValue(requestBody, EventList.class);
        } catch (IOException e) {
            response.status(400);
            return "Invalid request body.";
        }

        ApiHttpClient apiHttpClient = new ApiHttpClient(channelAccessToken);

        /**
         * Process the incoming messages/operations one by one
         */
        List<String> toUsers;
        for (Event event : events.getResult()) {
            switch (event.getEventType()) {
            case Constants.EventType.MESSAGE:
                toUsers = new ArrayList<>();
                toUsers.add(event.getContent().getFrom());

                // @TODO: We strongly suggest you should modify this to process the incoming message/operation async
                bc.sendTextMessage(toUsers, "You said: " + event.getContent().getText(), apiHttpClient);
                break;
            case Constants.EventType.OPERATION:
                if (event.getContent().getOpType() == Constants.OperationType.ADDED_AS_FRIEND) {
                    String newFriend = event.getContent().getParams().get(0);
                    Profile profile = bc.getProfile(newFriend, apiHttpClient);
                    String displayName = profile == null ? "Unknown" : profile.getDisplayName();
                    toUsers = new ArrayList<>();
                    toUsers.add(newFriend);
                    bc.sendTextMessage(toUsers, displayName + ", welcome to be my friend!", apiHttpClient);
                    Connection connection = null;
                    connection = DatabaseUrl.extract().getConnection();
                    toUsers = bc.getFriends(newFriend, connection);
                    if (toUsers.size() > 0) {
                        bc.sendTextMessage(toUsers, displayName + " just join us, let's welcome him/her!",
                                apiHttpClient);
                    }
                    bc.addFriend(newFriend, displayName, connection);
                    if (connection != null) {
                        connection.close();
                    }
                }
                break;
            default:
                // Unknown type?
            }
        }
        return "Events received successfully.";
    });

    get("/", (request, response) -> {
        Map<String, Object> attributes = new HashMap<>();
        attributes.put("message", "Hello World!");
        return new ModelAndView(attributes, "index.ftl");
    }, new FreeMarkerEngine());
}

From source file:com.github.lynxdb.server.run.Setup.java

public static void main(String[] args) {

    init();/*from w  ww .ja v  a  2 s.co  m*/

    Vhost system = Vhost.getSystemVhost();

    CreateKeyspaceSpecification keyspaceSpec = new CreateKeyspaceSpecification(
            System.getenv("cassandra_keyspace")).ifNotExists().withSimpleReplication(1);

    ct.execute(keyspaceSpec);

    init(System.getenv("cassandra_keyspace"));

    CreateTableSpecification vhosts = CreateTableSpecification.createTable("vhosts").ifNotExists()
            .partitionKeyColumn("vhostid", DataType.uuid()).column("vhostname", DataType.text());

    ct.execute(vhosts);

    CreateTableSpecification users = CreateTableSpecification.createTable("users").ifNotExists()
            .partitionKeyColumn("userlogin", DataType.text()).column("userpassword", DataType.text())
            .column("rank", DataType.text()).column("vhostid", DataType.uuid());

    ct.execute(users);

    ct.getSession().execute(
            "CREATE MATERIALIZED VIEW IF NOT EXISTS lynx.users_by_vhost AS SELECT * FROM lynx.users WHERE vhostid IS NOT NULL PRIMARY KEY (vhostid, userlogin)");

    CreateTableSpecification suggest_tagk = CreateTableSpecification.createTable("suggest_tagk").ifNotExists()
            .partitionKeyColumn("vhostid", DataType.uuid()).clusteredKeyColumn("tagk", DataType.text());

    ct.execute(suggest_tagk);

    CreateTableSpecification suggest_tagv = CreateTableSpecification.createTable("suggest_tagv").ifNotExists()
            .partitionKeyColumn("vhostid", DataType.uuid()).clusteredKeyColumn("tagv", DataType.text());

    ct.execute(suggest_tagv);

    CreateTableSpecification suggest_name = CreateTableSpecification.createTable("suggest_name").ifNotExists()
            .partitionKeyColumn("vhostid", DataType.uuid()).clusteredKeyColumn("name", DataType.text());

    ct.execute(suggest_name);

    CreateTableSpecification list = CreateTableSpecification.createTable("list").ifNotExists()
            .partitionKeyColumn("vhostid", DataType.uuid()).partitionKeyColumn("name", DataType.text())
            .clusteredKeyColumn("group", DataType.cint()).clusteredKeyColumn("tags", DataType.text());

    ct.execute(list);

    CreateTableSpecification series = CreateTableSpecification.createTable("series").ifNotExists()
            .partitionKeyColumn("vhostid", DataType.uuid()).partitionKeyColumn("name", DataType.text())
            .partitionKeyColumn("tags", DataType.text()).partitionKeyColumn("group", DataType.cint())
            .clusteredKeyColumn("time", DataType.cint()).clusteredKeyColumn("random", DataType.smallint())
            .column("value", DataType.cdouble());

    ct.execute(series);

    Insert systemVhost = QueryBuilder.insertInto("vhosts").value("vhostid", system.getId()).value("vhostname",
            system.getName());

    ct.execute(systemVhost);

    Insert adminUser = QueryBuilder.insertInto("users").value("userlogin", "admin")
            .value("userpassword", "2fa2849275b7af3e4137bcd867423462a409c1c264f7c5d8f67c3985429a6557")
            .value("vhostid", system.getId()).value("rank", User.Rank.RW_USER.name());

    ct.execute(adminUser);

    ct.getSession().getCluster().close();

    System.exit(0);

}

From source file:copi.ScalaEntryPoint.java

public static void main(String[] args) {
    /*//from  w  w  w  . j  a v a2 s. c o m
       * Set lwjgl library path so that LWJGL finds the natives depending on
       * the OS.
       */
    File libDir = new File(path);

    if (!libDir.exists()) {
        // create native lib folder 
        libDir.mkdir();

        // retrieve os type
        String osName = System.getProperty("os.name");

        // try to determine if the system is 64 bit  
        boolean is64bit = false;
        if (System.getProperty("os.name").contains("Windows")) {
            is64bit = (System.getenv("ProgramFiles(x86)") != null);
        } else {
            is64bit = (System.getProperty("os.arch").indexOf("64") != -1);
        }

        // construct name of native lib file 
        String natLibLWJGL = "";
        if (osName.startsWith("Windows")) {
            natLibLWJGL += "lwjgl";
            if (is64bit)
                natLibLWJGL += "64";
            natLibLWJGL += ".dll";
        } else if (osName.startsWith("Linux")) {
            natLibLWJGL += "liblwjgl";
            if (is64bit)
                natLibLWJGL += "64";
            natLibLWJGL += ".so";
        } else if (osName.startsWith("Mac OS X")) {
            natLibLWJGL += "liblwjgl";
            natLibLWJGL += ".jnilib";
        } else {
            System.out.println("Unsupported OS: " + osName + ". Exiting.");
            System.exit(-1);
        }

        // try to establish an input stream on the native lib inside the jar
        InputStream fis = ScalaEntryPoint.class.getResourceAsStream("/" + natLibLWJGL);
        if (fis == null) {
            System.out.println("Native library file " + natLibLWJGL + " was not found inside JAR.");
            System.exit(-1);
        }

        // establish an output stream on the target file 
        File fOut = new File(path + "/" + natLibLWJGL);
        try (FileOutputStream fos = new FileOutputStream(fOut)) {
            // create file at destination if not already existing
            if (!fOut.exists())
                fOut.createNewFile();

            // making buffer for copy operation 
            byte[] buffer = new byte[1024];
            int readBytes;

            // Open output stream and copy data between source file in JAR and the temporary file
            try {
                while ((readBytes = fis.read(buffer)) != -1) {
                    fos.write(buffer, 0, readBytes);
                }
            } finally {
                fos.close();
                fis.close();
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
            System.exit(-1);
        }

        // register shutdown hook
        JVMShutdownHook jvmShutdownHook = new JVMShutdownHook();
        Runtime.getRuntime().addShutdownHook(jvmShutdownHook);

    }

    // set lwjgl native library path
    System.setProperty("org.lwjgl.librarypath", libDir.getAbsolutePath());

    // start COPI
    System.out.println("Starting COPI ...");
    (new SICApplicationLogic()).render();
}

From source file:azkaban.jobtype.HadoopSecureHiveWrapper.java

public static void main(final String[] args) throws Exception {

    String propsFile = System.getenv(ProcessJob.JOB_PROP_ENV);
    Properties prop = new Properties();
    prop.load(new BufferedReader(new FileReader(propsFile)));

    hiveScript = prop.getProperty("hive.script");

    final Configuration conf = new Configuration();

    UserGroupInformation.setConfiguration(conf);
    securityEnabled = UserGroupInformation.isSecurityEnabled();

    if (shouldProxy(prop)) {
        UserGroupInformation proxyUser = null;
        String userToProxy = prop.getProperty("user.to.proxy");
        if (securityEnabled) {
            String filelocation = System.getenv(UserGroupInformation.HADOOP_TOKEN_FILE_LOCATION);
            if (filelocation == null) {
                throw new RuntimeException("hadoop token information not set.");
            }// w  w  w.  j a va 2s. com
            if (!new File(filelocation).exists()) {
                throw new RuntimeException("hadoop token file doesn't exist.");
            }

            logger.info("Found token file " + filelocation);

            logger.info("Setting " + HadoopSecurityManager.MAPREDUCE_JOB_CREDENTIALS_BINARY + " to "
                    + filelocation);
            System.setProperty(HadoopSecurityManager.MAPREDUCE_JOB_CREDENTIALS_BINARY, filelocation);

            UserGroupInformation loginUser = null;

            loginUser = UserGroupInformation.getLoginUser();
            logger.info("Current logged in user is " + loginUser.getUserName());

            logger.info("Creating proxy user.");
            proxyUser = UserGroupInformation.createProxyUser(userToProxy, loginUser);

            for (Token<?> token : loginUser.getTokens()) {
                proxyUser.addToken(token);
            }
        } else {
            proxyUser = UserGroupInformation.createRemoteUser(userToProxy);
        }

        logger.info("Proxied as user " + userToProxy);

        proxyUser.doAs(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                runHive(args);
                return null;
            }
        });

    } else {
        logger.info("Not proxying. ");
        runHive(args);
    }
}

From source file:PersistentEcho.java

public static void main(String[] args) {
    String argString = "";
    boolean notProperty = true;

    // Are there arguments? 
    // If so retrieve them.
    if (args.length > 0) {
        for (String arg : args) {
            argString += arg + " ";
        }//from   ww w.  j av a 2s . c  o  m
        argString = argString.trim();
    }
    // No arguments, is there
    // an environment variable?
    // If so, //retrieve it.
    else if ((argString = System.getenv("PERSISTENTECHO")) != null) {
    }
    // No environment variable
    // either. Retrieve property value.
    else {
        notProperty = false;
        // Set argString to null.
        // If it's still null after
        // we exit the try block,
        // we've failed to retrieve
        // the property value.
        argString = null;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("PersistentEcho.txt");
            Properties inProperties = new Properties();
            inProperties.load(fileInputStream);
            argString = inProperties.getProperty("argString");
        } catch (IOException e) {
            System.err.println("Can't read property file.");
            System.exit(1);
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                }
                ;
            }
        }
    }
    if (argString == null) {
        System.err.println("Couldn't find argString property");
        System.exit(1);
    }

    // Somehow, we got the
    // value. Echo it already!
    System.out.println(argString);

    // If we didn't retrieve the
    // value from the property,
    // save it //in the property.
    if (notProperty) {
        Properties outProperties = new Properties();
        outProperties.setProperty("argString", argString);
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream("PersistentEcho.txt");
            outProperties.store(fileOutputStream, "PersistentEcho properties");
        } catch (IOException e) {
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                }
                ;
            }
        }
    }
}

From source file:androidimporter.AndroidImporter.java

public static void main(String[] args) throws ParseException {
    //"/usr/local/apache-ant/bin/ant"
    String antPath = System.getProperty("ANT_PATH", System.getenv("ANT_PATH"));
    if (antPath == null || !new File(antPath).exists()) {
        throw new RuntimeException("Cannot find ant at " + antPath
                + ".  Please specify location to ant via the ANT_PATH environment variable or java system property.");
    }/* w ww.jav  a2  s .  c  o  m*/

    Options opts = new Options()
            .addOption("i", "android-resource-dir", true, "Android project res directory path")
            .addOption("o", "cn1-project-dir", true, "Path to the CN1 output project directory.")
            .addOption("r", "cn1-resource-file", false,
                    "Path to CN1 output .res file.  Defaults to theme.res in project dir")
            .addOption("p", "package", true, "Java package to place GUI forms in.")
            .addOption("h", "help", false, "Usage instructions");

    CommandLineParser parser = new DefaultParser();

    CommandLine line = parser.parse(opts, args);

    if (line.hasOption("help")) {
        showHelp(opts);
        System.exit(0);
    }
    args = line.getArgs();

    if (args.length < 1) {
        System.out.println("No command provided.");
        showHelp(opts);
        System.exit(0);
    }

    switch (args[0]) {
    case "import-project": {

        if (!line.hasOption("android-resource-dir") || !line.hasOption("cn1-project-dir")
                || !line.hasOption("package")) {
            System.out.println("Please provide android-resource-dir, package, and cn1-project-dir options");
            showHelp(opts);
            System.exit(1);
        }
        File resDir = findResDir(new File(line.getOptionValue("android-resource-dir")));
        if (resDir == null || !resDir.isDirectory()) {
            System.out.println("Failed to find android resource directory from provided value");
            showHelp(opts);
            System.exit(1);
        }

        File projDir = new File(line.getOptionValue("cn1-project-dir"));
        File resFile = new File(projDir, "src" + File.separator + "theme.res");
        if (line.hasOption("cn1-resource-file")) {
            resFile = new File(line.getOptionValue("cn1-resource-file"));
        }

        JavaSEPort.setShowEDTViolationStacks(false);
        JavaSEPort.setShowEDTWarnings(false);
        JFrame frm = new JFrame("Placeholder");
        frm.setVisible(false);
        Display.init(frm.getContentPane());
        JavaSEPort.setBaseResourceDir(resFile.getParentFile());
        try {
            System.out.println("About to import project at " + resDir.getAbsolutePath());
            System.out.println("Codename One Output Project: " + projDir.getAbsolutePath());
            System.out.println("Resource file: " + resFile.getAbsolutePath());
            System.out.println("Java Package: " + line.getOptionValue("package"));
            AndroidProjectImporter.importProject(resDir, projDir, resFile, line.getOptionValue("package"));
            Runtime.getRuntime().exec(new String[] { antPath, "init" }, new String[] {},
                    resFile.getParentFile().getParentFile());
            //runAnt(new File(resFile.getParentFile().getParentFile(), "build.xml"), "init");
            System.exit(0);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            System.exit(0);
        }
        break;
    }

    default:
        System.out.println("Unknown command " + args[0]);
        showHelp(opts);
        break;

    }

}

From source file:hdfs.MiniHDFS.java

public static void main(String[] args) throws Exception {
    if (args.length != 1 && args.length != 3) {
        throw new IllegalArgumentException(
                "Expected: MiniHDFS <baseDirectory> [<kerberosPrincipal> <kerberosKeytab>], " + "got: "
                        + Arrays.toString(args));
    }//from   w w w .  ja  v a2s . com
    boolean secure = args.length == 3;

    // configure Paths
    Path baseDir = Paths.get(args[0]);
    // hadoop-home/, so logs will not complain
    if (System.getenv("HADOOP_HOME") == null) {
        Path hadoopHome = baseDir.resolve("hadoop-home");
        Files.createDirectories(hadoopHome);
        System.setProperty("hadoop.home.dir", hadoopHome.toAbsolutePath().toString());
    }
    // hdfs-data/, where any data is going
    Path hdfsHome = baseDir.resolve("hdfs-data");

    // configure cluster
    Configuration cfg = new Configuration();
    cfg.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, hdfsHome.toAbsolutePath().toString());
    // lower default permission: TODO: needed?
    cfg.set(DFSConfigKeys.DFS_DATANODE_DATA_DIR_PERMISSION_KEY, "766");

    // optionally configure security
    if (secure) {
        String kerberosPrincipal = args[1];
        String keytabFile = args[2];

        cfg.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos");
        cfg.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, "true");
        cfg.set(DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY, kerberosPrincipal);
        cfg.set(DFSConfigKeys.DFS_DATANODE_KERBEROS_PRINCIPAL_KEY, kerberosPrincipal);
        cfg.set(DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY, kerberosPrincipal);
        cfg.set(DFSConfigKeys.DFS_NAMENODE_KEYTAB_FILE_KEY, keytabFile);
        cfg.set(DFSConfigKeys.DFS_DATANODE_KEYTAB_FILE_KEY, keytabFile);
        cfg.set(DFSConfigKeys.DFS_NAMENODE_ACLS_ENABLED_KEY, "true");
        cfg.set(DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY, "true");
        cfg.set(DFSConfigKeys.IGNORE_SECURE_PORTS_FOR_TESTING_KEY, "true");
    }

    UserGroupInformation.setConfiguration(cfg);

    // TODO: remove hardcoded port!
    MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(cfg);
    if (secure) {
        builder.nameNodePort(9998);
    } else {
        builder.nameNodePort(9999);
    }
    MiniDFSCluster dfs = builder.build();

    // Configure contents of the filesystem
    org.apache.hadoop.fs.Path esUserPath = new org.apache.hadoop.fs.Path("/user/elasticsearch");
    try (FileSystem fs = dfs.getFileSystem()) {

        // Set the elasticsearch user directory up
        fs.mkdirs(esUserPath);
        if (UserGroupInformation.isSecurityEnabled()) {
            List<AclEntry> acls = new ArrayList<>();
            acls.add(new AclEntry.Builder().setType(AclEntryType.USER).setName("elasticsearch")
                    .setPermission(FsAction.ALL).build());
            fs.modifyAclEntries(esUserPath, acls);
        }

        // Install a pre-existing repository into HDFS
        String directoryName = "readonly-repository";
        String archiveName = directoryName + ".tar.gz";
        URL readOnlyRepositoryArchiveURL = MiniHDFS.class.getClassLoader().getResource(archiveName);
        if (readOnlyRepositoryArchiveURL != null) {
            Path tempDirectory = Files.createTempDirectory(MiniHDFS.class.getName());
            File readOnlyRepositoryArchive = tempDirectory.resolve(archiveName).toFile();
            FileUtils.copyURLToFile(readOnlyRepositoryArchiveURL, readOnlyRepositoryArchive);
            FileUtil.unTar(readOnlyRepositoryArchive, tempDirectory.toFile());

            fs.copyFromLocalFile(true, true,
                    new org.apache.hadoop.fs.Path(
                            tempDirectory.resolve(directoryName).toAbsolutePath().toUri()),
                    esUserPath.suffix("/existing/" + directoryName));

            FileUtils.deleteDirectory(tempDirectory.toFile());
        }
    }

    // write our PID file
    Path tmp = Files.createTempFile(baseDir, null, null);
    String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
    Files.write(tmp, pid.getBytes(StandardCharsets.UTF_8));
    Files.move(tmp, baseDir.resolve(PID_FILE_NAME), StandardCopyOption.ATOMIC_MOVE);

    // write our port file
    tmp = Files.createTempFile(baseDir, null, null);
    Files.write(tmp, Integer.toString(dfs.getNameNodePort()).getBytes(StandardCharsets.UTF_8));
    Files.move(tmp, baseDir.resolve(PORT_FILE_NAME), StandardCopyOption.ATOMIC_MOVE);
}

From source file:edu.mit.lib.mama.Mama.java

public static void main(String[] args) {

    Properties props = findConfig(args);
    DBI dbi = new DBI(props.getProperty("dburl"), props);
    // Advanced instrumentation/metrics if requested
    if (System.getenv("MAMA_DB_METRICS") != null) {
        dbi.setTimingCollector(new InstrumentedTimingCollector(metrics));
    }/*  w  w w  .  j a va 2  s  .c  om*/
    // reassign default port 4567
    if (System.getenv("MAMA_SVC_PORT") != null) {
        port(Integer.valueOf(System.getenv("MAMA_SVC_PORT")));
    }
    // if API key given, use exception monitoring service
    if (System.getenv("HONEYBADGER_API_KEY") != null) {
        reporter = new HoneybadgerReporter();
    }

    get("/ping", (req, res) -> {
        res.type("text/plain");
        res.header("Cache-Control", "must-revalidate,no-cache,no-store");
        return "pong";
    });

    get("/metrics", (req, res) -> {
        res.type("application/json");
        res.header("Cache-Control", "must-revalidate,no-cache,no-store");
        ObjectMapper objectMapper = new ObjectMapper()
                .registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, true));
        try (ServletOutputStream outputStream = res.raw().getOutputStream()) {
            objectMapper.writer().withDefaultPrettyPrinter().writeValue(outputStream, metrics);
        }
        return "";
    });

    get("/shutdown", (req, res) -> {
        boolean auth = false;
        try {
            if (!isNullOrEmpty(System.getenv("MAMA_SHUTDOWN_KEY")) && !isNullOrEmpty(req.queryParams("key"))
                    && System.getenv("MAMA_SHUTDOWN_KEY").equals(req.queryParams("key"))) {
                auth = true;
                return "Shutting down";
            } else {
                res.status(401);
                return "Not authorized";
            }
        } finally {
            if (auth) {
                stop();
            }
        }
    });

    get("/item", (req, res) -> {
        if (isNullOrEmpty(req.queryParams("qf")) || isNullOrEmpty(req.queryParams("qv"))) {
            halt(400, "Must supply field and value query parameters 'qf' and 'qv'");
        }
        itemReqs.mark();
        Timer.Context context = respTime.time();
        try (Handle hdl = dbi.open()) {
            if (findFieldId(hdl, req.queryParams("qf")) != -1) {
                List<String> results = findItems(hdl, req.queryParams("qf"), req.queryParams("qv"),
                        req.queryParamsValues("rf"));
                if (results.size() > 0) {
                    res.type("application/json");
                    return "{ " + jsonValue("field", req.queryParams("qf"), true) + ",\n"
                            + jsonValue("value", req.queryParams("qv"), true) + ",\n" + jsonValue("items",
                                    results.stream().collect(Collectors.joining(",", "[", "]")), false)
                            + "\n" + " }";
                } else {
                    res.status(404);
                    return "No items found for: " + req.queryParams("qf") + "::" + req.queryParams("qv");
                }
            } else {
                res.status(404);
                return "No such field: " + req.queryParams("qf");
            }
        } catch (Exception e) {
            if (null != reporter)
                reporter.reportError(e);
            res.status(500);
            return "Internal system error: " + e.getMessage();
        } finally {
            context.stop();
        }
    });

    awaitInitialization();
}

From source file:cz.muni.fi.crocs.EduHoc.Main.java

/**
 * @param args the command line arguments
 *///from w w w  . jav a  2s.  c om
public static void main(String[] args) {
    System.out.println("JeeTool \n");

    Options options = OptionsMain.createOptions();

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println("cannot parse parameters");
        OptionsMain.printHelp(options);
        System.err.println(ex.toString());
        return;
    }
    boolean silent = cmd.hasOption("s");
    boolean verbose = cmd.hasOption("v");

    if (!silent) {
        System.out.println(ANSI_GREEN + "EduHoc home is: " + System.getenv("EDU_HOC_HOME") + "\n" + ANSI_RESET);
    }

    //help
    if (cmd.hasOption("h")) {
        OptionsMain.printHelp(options);
        return;
    }

    String filepath;
    //path to config list of nodes
    if (cmd.hasOption("a")) {
        filepath = cmd.getOptionValue("a");
    } else {
        filepath = System.getenv("EDU_HOC_HOME") + "/config/motePaths.txt";
    }

    //create motelist
    MoteList moteList = new MoteList(filepath);
    if (verbose) {
        moteList.setVerbose();
    }
    if (silent) {
        moteList.setSilent();
    }

    if (verbose) {
        System.out.println("reading motelist from file " + filepath);
    }

    if (cmd.hasOption("i")) {
        List<Integer> ids = new ArrayList<Integer>();
        String arg = cmd.getOptionValue("i");
        String[] IdArgs = arg.split(",");
        for (String s : IdArgs) {
            if (s.contains("-")) {
                int start = Integer.parseInt(s.substring(0, s.indexOf("-")));
                int end = Integer.parseInt(s.substring(s.indexOf("-") + 1, s.length()));
                for (int i = start; i <= end; i++) {
                    ids.add(i);
                }
            } else {
                ids.add(Integer.parseInt(s));
            }
        }
        moteList.setIds(ids);
    }

    moteList.readFile();

    if (cmd.hasOption("d")) {
        //only detect nodes
        return;
    }

    //if make
    if (cmd.hasOption("m") || cmd.hasOption("c") || cmd.hasOption("u")) {
        UploadMain upload = new UploadMain(moteList, cmd);
        upload.runMake();
    }

    //if execute command
    if (cmd.hasOption("E")) {
        try {
            ExecuteShellCommand com = new ExecuteShellCommand();
            if (verbose) {
                System.out.println("Executing shell command " + cmd.getOptionValue("E"));
            }

            com.executeCommand(cmd.getOptionValue("E"));
        } catch (IOException ex) {
            System.err.println("Execute command " + cmd.getOptionValue("E") + " failed");
        }
    }

    //if serial
    if (cmd.hasOption("l") || cmd.hasOption("w")) {
        SerialMain serial = new SerialMain(cmd, moteList);
        if (silent) {
            serial.setSilent();
        }
        if (verbose) {
            serial.setVerbose();
        }
        serial.startSerial();
    }

}

From source file:at.tuwien.ifs.somtoolbox.apps.SOMToolboxMain.java

/**
 * Central Main for SOMToolbox./*from   ww w .j av a  2s .  c o  m*/
 * 
 * @param args the command line args
 */
public static void main(String[] args) {
    int screenWidth = 80;
    try {
        screenWidth = Integer.parseInt(System.getenv("COLUMNS"));
    } catch (Exception e) {
        screenWidth = 80;
    }

    JSAP jsap = new JSAP();
    try {
        jsap.registerParameter(new UnflaggedOption("main", JSAP.STRING_PARSER, null, false, false));
        jsap.registerParameter(new Switch("gui", 'G', "gui"));
        jsap.registerParameter(new Switch("version", JSAP.NO_SHORTFLAG, "version"));
        jsap.registerParameter(new Switch("listmains", JSAP.NO_SHORTFLAG, "list-mains"));
        jsap.registerParameter(
                new FlaggedOption("help", JSAP.STRING_PARSER, null, false, JSAP.NO_SHORTFLAG, "help"));
    } catch (JSAPException e) {
        assert false;
    }
    JSAPResult result = jsap.parse(args);

    ArrayList<Class<? extends SOMToolboxApp>> runnables = SubClassFinder.findSubclassesOf(SOMToolboxApp.class,
            true);
    Collections.sort(runnables, SOMToolboxApp.TYPE_GROUPED_COMPARATOR);

    // args > 0
    boolean useGUI = result.getBoolean("gui", false);
    if (useGUI) {
        UiUtils.setSOMToolboxLookAndFeel();
    }

    if (result.getBoolean("listmains")) {
        if (useGUI) {
            showAvailableRunnables(runnables, args);
        } else {
            printAvailableRunnables(screenWidth, runnables);
        }
    } else if (result.getBoolean("version")) {
        if (result.userSpecified("main")) {
            printVersion(result.getString("main"));
        } else {
            printVersion("somtoolbox");
        }
    } else if (result.userSpecified("main")) {
        String mainClass = result.getString("main");
        String[] cleanArgs = Arrays.copyOfRange(args, 1, args.length);
        if (!invokeMainClass(runnables, mainClass, cleanArgs, useGUI)) {
            Logger.getLogger("at.tuwien.ifs.somtoolbox").severe("Runnable \"" + mainClass + "\" not found.");
            printAvailableRunnables(screenWidth, runnables);
        }
    } else if (result.contains("help")) {
        if (result.getString("help") != null) {
            invokeMainClass(runnables, result.getString("help"), new String[] { "--help" }, useGUI);
        } else {
            printHelp();
        }
    } else {
        if (useGUI) {
            showAvailableRunnables(runnables, args);
        } else {
            printAvailableRunnables(screenWidth, runnables);
        }

    }
}