Example usage for java.lang System getProperty

List of usage examples for java.lang System getProperty

Introduction

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

Prototype

public static String getProperty(String key) 

Source Link

Document

Gets the system property indicated by the specified key.

Usage

From source file:com.clustercontrol.agent.Agent.java

/**
 * ?/*w ww .  j a v  a2s  .co  m*/
 * 
 * @param args ??
 */
public static void main(String[] args) throws Exception {

    // ?
    if (args.length != 1) {
        System.out.println("Usage : java Agent [Agent.properties File Path]");
        System.exit(1);
    }

    try {
        // System
        m_log.info("starting Hinemos Agent...");
        m_log.info("java.vm.version = " + System.getProperty("java.vm.version"));
        m_log.info("java.vm.vendor = " + System.getProperty("java.vm.vendor"));
        m_log.info("java.home = " + System.getProperty("java.home"));
        m_log.info("os.name = " + System.getProperty("os.name"));
        m_log.info("os.arch = " + System.getProperty("os.arch"));
        m_log.info("os.version = " + System.getProperty("os.version"));
        m_log.info("user.name = " + System.getProperty("user.name"));
        m_log.info("user.dir = " + System.getProperty("user.dir"));
        m_log.info("user.country = " + System.getProperty("user.country"));
        m_log.info("user.language = " + System.getProperty("user.language"));
        m_log.info("file.encoding = " + System.getProperty("file.encoding"));

        // System(SET)
        String limitKey = "jdk.xml.entityExpansionLimit"; // TODO JRE???????????????????
        System.setProperty(limitKey, "0");
        m_log.info(limitKey + " = " + System.getProperty(limitKey));

        // TODO ???agentHome
        // ??????????
        File file = new File(args[0]);
        agentHome = file.getParentFile().getParent() + "/";
        m_log.info("agentHome=" + agentHome);

        // 
        long startDate = HinemosTime.currentTimeMillis();
        m_log.info("start date = " + new Date(startDate) + "(" + startDate + ")");
        agentInfo.setStartupTime(startDate);

        // Agent??
        m_log.info("Agent.properties = " + args[0]);

        // ?
        File scriptDir = new File(agentHome + "script/");
        if (scriptDir.exists()) {
            File[] listFiles = scriptDir.listFiles();
            if (listFiles != null) {
                for (File f : listFiles) {
                    boolean ret = f.delete();
                    if (ret) {
                        m_log.debug("delete script : " + f.getName());
                    } else {
                        m_log.warn("delete script error : " + f.getName());
                    }
                }
            } else {
                m_log.warn("listFiles is null");
            }
        } else {
            //????????
            boolean ret = scriptDir.mkdir();
            if (!ret) {
                m_log.warn("mkdir error " + scriptDir.getPath());
            }
        }

        // queue?
        m_sendQueue = new SendQueue();

        // Agent?
        Agent agent = new Agent(args[0]);

        //-----------------
        //-- 
        //-----------------
        m_log.debug("exec() : create topic ");

        m_receiveTopic = new ReceiveTopic(m_sendQueue);
        m_receiveTopic.setName("ReceiveTopicThread");
        m_log.info("receiveTopic start 1");
        m_receiveTopic.start();
        m_log.info("receiveTopic start 2");

        // ?
        agent.exec();

        m_log.info("Hinemos Agent started");

        // ?
        agent.waitAwakeAgent();
    } catch (Throwable e) {
        m_log.error("Agent.java: Runtime Exception Occurred. " + e.getClass().getName() + ", " + e.getMessage(),
                e);
    }
}

From source file:com.moss.appsnap.server.AppSnapServer.java

public static void main(String[] args) throws Exception {
    System.setProperty("org.mortbay.log.class", Slf4jLog.class.getName());

    File log4jConfigFile = new File("log4j.xml");

    if (log4jConfigFile.exists()) {
        DOMConfigurator.configureAndWatch(log4jConfigFile.getAbsolutePath(), 1000);
    } else {//from www  .  j a  v  a2s.c  om
        BasicConfigurator.configure();
        Logger.getRootLogger().setLevel(Level.INFO);
    }

    ServerConfiguration config;

    JAXBContext context = JAXBContext.newInstance(ServerConfiguration.class, VeracityId.class);
    JAXBHelper helper = new JAXBHelper(context);

    Logger log = Logger.getLogger(AppSnapServer.class);

    File[] configPaths = new File[] { new File("settings.xml"),
            new File(new File(System.getProperty("user.home")), ".appsnap-server.xml"),
            new File("/etc/appsnap-server.xml") };

    File configFile = null;

    for (File next : configPaths) {
        if (next.exists()) {
            configFile = next;
        }
    }

    if (configFile == null) {

        log.warn("No config file found.");

        for (int x = configPaths.length - 1; x >= 0; x--) {
            File next = configPaths[x];
            log.warn("Attempting to create default config file at " + next.getAbsolutePath());
            ServerConfiguration defaults = new ServerConfiguration();
            defaults.idProofRecipie(
                    new PasswordProofRecipie(new SimpleId("mr-admin-dude"), "my-super-secret-password"));
            try {
                helper.writeToFile(helper.writeToXmlString(defaults), next);
                log.warn("done");
                break;
            } catch (Exception e) {
                log.warn("Error writing file: " + e.getMessage(), e);
            }
        }
        System.exit(1);
        return;
    } else {
        log.info("Reading configuration from " + configFile.getAbsolutePath());
        config = helper.readFromFile(configFile);
    }

    ProxyFactory proxyFactory = new ProxyFactory(new HessianProxyProvider());
    try {
        new AppSnapServer(config, proxyFactory);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Unexpected Error.  Shutting Down.");
        System.exit(1);
    }
}

From source file:fr.cs.examples.propagation.DSSTPropagation.java

/** Program entry point.
 * @param args program arguments/*  w  w  w . ja  v a 2  s .  com*/
 */
public static void main(String[] args) {
    try {

        // configure Orekit data acces
        Utils.setDataRoot("tutorial-orekit-data");

        // input/output (in user's home directory)
        File input = new File(new File(System.getProperty("user.home")), "dsst-propagation.in");
        File output = new File(input.getParentFile(), "dsst-propagation.out");

        new DSSTPropagation().run(input, output);

    } catch (IOException ioe) {
        System.err.println(ioe.getLocalizedMessage());
        System.exit(1);
    } catch (IllegalArgumentException iae) {
        System.err.println(iae.getLocalizedMessage());
        System.exit(1);
    } catch (OrekitException oe) {
        System.err.println(oe.getLocalizedMessage());
        System.exit(1);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    }
}

From source file:org.psidnell.omnifocus.Main.java

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

    ActiveOptionProcessor<CommandLine> processor = new ActiveOptionProcessor<>(PROG, OPTIONS);

    boolean cmdLineFailure = !processor.processOptions(null, args, STARTUP);

    ApplicationContext appContext = ApplicationContextFactory.getContext();

    Main main = appContext.getBean("main", Main.class);
    main.setProcessor(processor);// w w  w . ja  v  a2s  .  c o m

    if (cmdLineFailure || "true".equals(System.getProperty(CommandLine.PRINT_HELP))) {
        main.printHelp();
        return;
    }

    if ("true".equals(System.getProperty(CommandLine.PRINT_INFO))) {
        main.printAdditionalInfo();
        return;
    }

    main.procesPreLoadOptions(args);

    if (main.exportFile != null) {
        main.data.exportData(new File(main.exportFile), (f) -> true);
        return;
    }

    main.loadData();

    main.processPostLoadOptions(args);

    main.run();

    LOGGER.debug("Exiting");
}

From source file:com.jkoolcloud.tnt4j.streams.StreamsDaemon.java

/**
 * Main entry point for running as a system service.
 *
 * @param args//from   w ww  .j a  v  a  2  s .  co m
 *            command-line arguments. Supported arguments:
 *            <table summary="TNT4J-Streams daemon command line arguments">
 *            <tr>
 *            <td>&nbsp;&nbsp;</td>
 *            <td>&nbsp;command_name</td>
 *            <td>(mandatory) service handling command name: {@code start} or {@code stop}</td>
 *            </tr>
 *            <tr>
 *            <td>&nbsp;&nbsp;</td>
 *            <td>&nbsp;stream command-line arguments</td>
 *            <td>(optional) list of streams configuration supported command-line arguments</td>
 *            </tr>
 *            </table>
 *
 * @see com.jkoolcloud.tnt4j.streams.StreamsAgent#main(String...)
 */
public static void main(String... args) {
    LOGGER.log(OpLevel.INFO,
            StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME, "StreamsDaemon.start.main"),
            StreamsAgent.pkgVersion(), System.getProperty("java.version"));
    try {
        String cmd = START_COMMAND;
        if (args.length > 0) {
            LOGGER.log(OpLevel.INFO, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                    "StreamsDaemon.processing.args"), Arrays.toString(args));
            StreamsAgent.processArgs(Arrays.copyOfRange(args, 1, args.length));
            cmd = args[0];
        }

        if (START_COMMAND.equalsIgnoreCase(cmd)) {
            instance.start();
        } else {
            instance.stop();
        }
    } catch (Exception e) {
        LOGGER.log(OpLevel.FATAL,
                StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME, "StreamsDaemon.fatal.error"),
                e);
    }
}

From source file:fr.cs.examples.frames.Frames3.java

public static void main(String[] args) {
    try {/*ww  w.  j a v  a 2 s . co m*/

        // configure Orekit and printing format
        Autoconfiguration.configureOrekit();

        // Initial state definition :
        // ==========================

        // Date
        // ****
        AbsoluteDate initialDate = new AbsoluteDate(new DateComponents(1970, 04, 07), TimeComponents.H00,
                TimeScalesFactory.getUTC());

        // Orbit
        // *****
        // The Sun is in the orbital plane for raan ~ 202
        double mu = 3.986004415e+14; // gravitation coefficient
        Frame eme2000 = FramesFactory.getEME2000(); // inertial frame
        Orbit orbit = new CircularOrbit(7178000.0, 0.5e-4, -0.5e-4, FastMath.toRadians(50.),
                FastMath.toRadians(220.), FastMath.toRadians(5.300), PositionAngle.MEAN, eme2000, initialDate,
                mu);

        // Attitude laws
        // *************

        // Earth
        Frame earthFrame = FramesFactory.getITRF(IERSConventions.IERS_2010, true);
        BodyShape earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
                Constants.WGS84_EARTH_FLATTENING, earthFrame);

        // Target pointing attitude provider over satellite nadir at date, without yaw compensation
        NadirPointing nadirLaw = new NadirPointing(eme2000, earth);

        // Target pointing attitude provider with yaw compensation
        final PVCoordinatesProvider sun = CelestialBodyFactory.getSun();
        YawSteering yawSteeringLaw = new YawSteering(eme2000, nadirLaw, sun, Vector3D.MINUS_I);

        // Propagator : Eckstein-Hechler analytic propagator
        Propagator propagator = new EcksteinHechlerPropagator(orbit, yawSteeringLaw,
                Constants.EIGEN5C_EARTH_EQUATORIAL_RADIUS, Constants.EIGEN5C_EARTH_MU,
                Constants.EIGEN5C_EARTH_C20, Constants.EIGEN5C_EARTH_C30, Constants.EIGEN5C_EARTH_C40,
                Constants.EIGEN5C_EARTH_C50, Constants.EIGEN5C_EARTH_C60);

        // Let's write the results in a file in order to draw some plots.
        propagator.setMasterMode(10, new OrekitFixedStepHandler() {

            PrintStream out = null;

            public void init(SpacecraftState s0, AbsoluteDate t) throws PropagationException {
                try {
                    File file = new File(System.getProperty("user.home"), "XYZ.dat");
                    System.out.println("Results written to file: " + file.getAbsolutePath());
                    out = new PrintStream(file);
                    out.println("#time X Y Z Wx Wy Wz");
                } catch (IOException ioe) {
                    throw new PropagationException(ioe, LocalizedFormats.SIMPLE_MESSAGE,
                            ioe.getLocalizedMessage());
                }
            }

            public void handleStep(SpacecraftState currentState, boolean isLast) throws PropagationException {
                try {

                    // get the transform from orbit/attitude reference frame to spacecraft frame
                    Transform inertToSpacecraft = currentState.toTransform();

                    // get the position of the Sun in orbit/attitude reference frame
                    Vector3D sunInert = sun.getPVCoordinates(currentState.getDate(), currentState.getFrame())
                            .getPosition();

                    // convert Sun position to spacecraft frame
                    Vector3D sunSat = inertToSpacecraft.transformPosition(sunInert);

                    // and the spacecraft rotational rate also
                    Vector3D spin = inertToSpacecraft.getRotationRate();

                    // Lets calculate the reduced coordinates
                    double sunX = sunSat.getX() / sunSat.getNorm();
                    double sunY = sunSat.getY() / sunSat.getNorm();
                    double sunZ = sunSat.getZ() / sunSat.getNorm();

                    out.format(Locale.US, "%s %12.3f %12.3f %12.3f %12.7f %12.7f %12.7f%n",
                            currentState.getDate(), sunX, sunY, sunZ, spin.getX(), spin.getY(), spin.getZ());

                    if (isLast) {
                        out.close();
                    }
                } catch (OrekitException oe) {
                    throw new PropagationException(oe);
                }
            }

        });

        System.out.println("Running...");
        propagator.propagate(initialDate.shiftedBy(6000));

    } catch (OrekitException oe) {
        System.err.println(oe.getMessage());
    }
}

From source file:com.moss.appkeep.server.AppkeepServer.java

public static void main(String[] args) throws Exception {
    System.setProperty("org.mortbay.log.class", Slf4jLog.class.getName());

    File log4jConfigFile = new File("log4j.xml");

    if (log4jConfigFile.exists()) {
        DOMConfigurator.configureAndWatch(log4jConfigFile.getAbsolutePath(), 1000);
    } else {/*from   w ww  .j  a v  a2  s  . c  o m*/
        BasicConfigurator.configure();
        Logger.getRootLogger().setLevel(Level.INFO);
    }

    ServerConfiguration config;

    JAXBContext context = JAXBContext.newInstance(ServerConfiguration.class,

            VeracityId.class, SimpleId.class,

            PasswordProofRecipie.class, ProofDelegationRecipie.class);

    JAXBHelper helper = new JAXBHelper(context);

    Logger log = Logger.getLogger(AppkeepServer.class);

    File configFile = new File("settings.xml");
    if (!configFile.exists())
        configFile = new File(new File(System.getProperty("user.dir")), ".appkeep-server.xml");
    if (!configFile.exists())
        configFile = new File("/etc/appkeep-server.xml");

    if (!configFile.exists()) {
        config = new ServerConfiguration();
        helper.writeToFile(helper.writeToXmlString(config), configFile);
        log.warn("Created default config file at " + configFile.getAbsolutePath());
    } else {
        log.info("Reading configuration from " + configFile.getAbsolutePath());
        config = helper.readFromFile(configFile);
    }

    ProxyFactory proxyFactory = new ProxyFactory(new HessianProxyProvider());
    try {
        new AppkeepServer(config, proxyFactory);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Unexpected Error.  Shutting Down.");
        System.exit(1);
    }
}

From source file:org.asamk.signal.Main.java

public static void main(String[] args) {
    // Workaround for BKS truststore
    Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 1);

    Namespace ns = parseArgs(args);
    if (ns == null) {
        System.exit(1);//from  w w w. jav  a  2s  . co m
    }

    final String username = ns.getString("username");
    Manager m;
    Signal ts;
    DBusConnection dBusConn = null;
    try {
        if (ns.getBoolean("dbus") || ns.getBoolean("dbus_system")) {
            try {
                m = null;
                int busType;
                if (ns.getBoolean("dbus_system")) {
                    busType = DBusConnection.SYSTEM;
                } else {
                    busType = DBusConnection.SESSION;
                }
                dBusConn = DBusConnection.getConnection(busType);
                ts = (Signal) dBusConn.getRemoteObject(SIGNAL_BUSNAME, SIGNAL_OBJECTPATH, Signal.class);
            } catch (DBusException e) {
                e.printStackTrace();
                if (dBusConn != null) {
                    dBusConn.disconnect();
                }
                System.exit(3);
                return;
            }
        } else {
            String settingsPath = ns.getString("config");
            if (TextUtils.isEmpty(settingsPath)) {
                settingsPath = System.getProperty("user.home") + "/.config/signal";
                if (!new File(settingsPath).exists()) {
                    String legacySettingsPath = System.getProperty("user.home") + "/.config/textsecure";
                    if (new File(legacySettingsPath).exists()) {
                        settingsPath = legacySettingsPath;
                    }
                }
            }

            m = new Manager(username, settingsPath);
            ts = m;
            if (m.userExists()) {
                try {
                    m.load();
                } catch (Exception e) {
                    System.err
                            .println("Error loading state file \"" + m.getFileName() + "\": " + e.getMessage());
                    System.exit(2);
                    return;
                }
            }
        }

        switch (ns.getString("command")) {
        case "register":
            if (dBusConn != null) {
                System.err.println("register is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.userHasKeys()) {
                m.createNewIdentity();
            }
            try {
                m.register(ns.getBoolean("voice"));
            } catch (IOException e) {
                System.err.println("Request verify error: " + e.getMessage());
                System.exit(3);
            }
            break;
        case "verify":
            if (dBusConn != null) {
                System.err.println("verify is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.userHasKeys()) {
                System.err.println("User has no keys, first call register.");
                System.exit(1);
            }
            if (m.isRegistered()) {
                System.err.println("User registration is already verified");
                System.exit(1);
            }
            try {
                m.verifyAccount(ns.getString("verificationCode"));
            } catch (IOException e) {
                System.err.println("Verify error: " + e.getMessage());
                System.exit(3);
            }
            break;
        case "link":
            if (dBusConn != null) {
                System.err.println("link is not yet implemented via dbus");
                System.exit(1);
            }

            // When linking, username is null and we always have to create keys
            m.createNewIdentity();

            String deviceName = ns.getString("name");
            if (deviceName == null) {
                deviceName = "cli";
            }
            try {
                System.out.println(m.getDeviceLinkUri());
                m.finishDeviceLink(deviceName);
                System.out.println("Associated with: " + m.getUsername());
            } catch (TimeoutException e) {
                System.err.println("Link request timed out, please try again.");
                System.exit(3);
            } catch (IOException e) {
                System.err.println("Link request error: " + e.getMessage());
                System.exit(3);
            } catch (InvalidKeyException e) {
                e.printStackTrace();
                System.exit(3);
            } catch (UserAlreadyExists e) {
                System.err.println("The user " + e.getUsername() + " already exists\nDelete \""
                        + e.getFileName() + "\" before trying again.");
                System.exit(3);
            }
            break;
        case "addDevice":
            if (dBusConn != null) {
                System.err.println("link is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            try {
                m.addDeviceLink(new URI(ns.getString("uri")));
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(3);
            } catch (InvalidKeyException e) {
                e.printStackTrace();
                System.exit(2);
            } catch (URISyntaxException e) {
                e.printStackTrace();
                System.exit(2);
            }
            break;
        case "listDevices":
            if (dBusConn != null) {
                System.err.println("listDevices is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            try {
                List<DeviceInfo> devices = m.getLinkedDevices();
                for (DeviceInfo d : devices) {
                    System.out.println("Device " + d.getId()
                            + (d.getId() == m.getDeviceId() ? " (this device)" : "") + ":");
                    System.out.println(" Name: " + d.getName());
                    System.out.println(" Created: " + d.getCreated());
                    System.out.println(" Last seen: " + d.getLastSeen());
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(3);
            }
            break;
        case "removeDevice":
            if (dBusConn != null) {
                System.err.println("removeDevice is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            try {
                int deviceId = ns.getInt("deviceId");
                m.removeLinkedDevices(deviceId);
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(3);
            }
            break;
        case "send":
            if (dBusConn == null && !m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }

            if (ns.getBoolean("endsession")) {
                if (ns.getList("recipient") == null) {
                    System.err.println("No recipients given");
                    System.err.println("Aborting sending.");
                    System.exit(1);
                }
                try {
                    ts.sendEndSessionMessage(ns.<String>getList("recipient"));
                } catch (IOException e) {
                    handleIOException(e);
                } catch (EncapsulatedExceptions e) {
                    handleEncapsulatedExceptions(e);
                } catch (AssertionError e) {
                    handleAssertionError(e);
                } catch (DBusExecutionException e) {
                    handleDBusExecutionException(e);
                } catch (UntrustedIdentityException e) {
                    e.printStackTrace();
                }
            } else {
                String messageText = ns.getString("message");
                if (messageText == null) {
                    try {
                        messageText = IOUtils.toString(System.in);
                    } catch (IOException e) {
                        System.err.println("Failed to read message from stdin: " + e.getMessage());
                        System.err.println("Aborting sending.");
                        System.exit(1);
                    }
                }

                try {
                    List<String> attachments = ns.getList("attachment");
                    if (attachments == null) {
                        attachments = new ArrayList<>();
                    }
                    if (ns.getString("group") != null) {
                        byte[] groupId = decodeGroupId(ns.getString("group"));
                        ts.sendGroupMessage(messageText, attachments, groupId);
                    } else {
                        ts.sendMessage(messageText, attachments, ns.<String>getList("recipient"));
                    }
                } catch (IOException e) {
                    handleIOException(e);
                } catch (EncapsulatedExceptions e) {
                    handleEncapsulatedExceptions(e);
                } catch (AssertionError e) {
                    handleAssertionError(e);
                } catch (GroupNotFoundException e) {
                    handleGroupNotFoundException(e);
                } catch (AttachmentInvalidException e) {
                    System.err.println("Failed to add attachment: " + e.getMessage());
                    System.err.println("Aborting sending.");
                    System.exit(1);
                } catch (DBusExecutionException e) {
                    handleDBusExecutionException(e);
                } catch (UntrustedIdentityException e) {
                    e.printStackTrace();
                }
            }

            break;
        case "receive":
            if (dBusConn != null) {
                try {
                    dBusConn.addSigHandler(Signal.MessageReceived.class,
                            new DBusSigHandler<Signal.MessageReceived>() {
                                @Override
                                public void handle(Signal.MessageReceived s) {
                                    System.out
                                            .print(String.format("Envelope from: %s\nTimestamp: %d\nBody: %s\n",
                                                    s.getSender(), s.getTimestamp(), s.getMessage()));
                                    if (s.getGroupId().length > 0) {
                                        System.out.println("Group info:");
                                        System.out.println("  Id: " + Base64.encodeBytes(s.getGroupId()));
                                    }
                                    if (s.getAttachments().size() > 0) {
                                        System.out.println("Attachments: ");
                                        for (String attachment : s.getAttachments()) {
                                            System.out.println("-  Stored plaintext in: " + attachment);
                                        }
                                    }
                                    System.out.println();
                                }
                            });
                } catch (DBusException e) {
                    e.printStackTrace();
                }
                while (true) {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        System.exit(0);
                    }
                }
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            int timeout = 60;
            if (ns.getInt("timeout") != null) {
                timeout = ns.getInt("timeout");
            }
            boolean returnOnTimeout = true;
            if (timeout < 0) {
                returnOnTimeout = false;
                timeout = 3600;
            }
            try {

                for (int i = 0; i < 10; i++) {
                    System.out.println("Numero di threads: " + Thread.activeCount());
                    m.receiveMessages(timeout, returnOnTimeout, new ReceiveMessageHandler(m));
                }

            } catch (IOException e) {
                System.err.println("Error while receiving messages: " + e.getMessage());
                System.exit(3);
            } catch (AssertionError e) {
                handleAssertionError(e);
            }
            break;
        case "quitGroup":
            if (dBusConn != null) {
                System.err.println("quitGroup is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }

            try {
                m.sendQuitGroupMessage(decodeGroupId(ns.getString("group")));
            } catch (IOException e) {
                handleIOException(e);
            } catch (EncapsulatedExceptions e) {
                handleEncapsulatedExceptions(e);
            } catch (AssertionError e) {
                handleAssertionError(e);
            } catch (GroupNotFoundException e) {
                handleGroupNotFoundException(e);
            } catch (UntrustedIdentityException e) {
                e.printStackTrace();
            }

            break;
        case "updateGroup":
            if (dBusConn != null) {
                System.err.println("updateGroup is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }

            try {
                byte[] groupId = null;
                if (ns.getString("group") != null) {
                    groupId = decodeGroupId(ns.getString("group"));
                }
                byte[] newGroupId = m.sendUpdateGroupMessage(groupId, ns.getString("name"),
                        ns.<String>getList("member"), ns.getString("avatar"));
                if (groupId == null) {
                    System.out.println("Creating new group \"" + Base64.encodeBytes(newGroupId) + "\" ");
                }
            } catch (IOException e) {
                handleIOException(e);
            } catch (AttachmentInvalidException e) {
                System.err.println("Failed to add avatar attachment for group\": " + e.getMessage());
                System.err.println("Aborting sending.");
                System.exit(1);
            } catch (GroupNotFoundException e) {
                handleGroupNotFoundException(e);
            } catch (EncapsulatedExceptions e) {
                handleEncapsulatedExceptions(e);
            } catch (UntrustedIdentityException e) {
                e.printStackTrace();
            }

            break;
        case "daemon":
            if (dBusConn != null) {
                System.err.println("Stop it.");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            DBusConnection conn = null;
            try {
                try {
                    int busType;
                    if (ns.getBoolean("system")) {
                        busType = DBusConnection.SYSTEM;
                    } else {
                        busType = DBusConnection.SESSION;
                    }
                    conn = DBusConnection.getConnection(busType);
                    conn.exportObject(SIGNAL_OBJECTPATH, m);
                    conn.requestBusName(SIGNAL_BUSNAME);
                } catch (DBusException e) {
                    e.printStackTrace();
                    System.exit(3);
                }
                try {
                    m.receiveMessages(3600, false, new DbusReceiveMessageHandler(m, conn));
                } catch (IOException e) {
                    System.err.println("Error while receiving messages: " + e.getMessage());
                    System.exit(3);
                } catch (AssertionError e) {
                    handleAssertionError(e);
                }
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }

            break;
        }
        System.exit(0);
    } finally {
        if (dBusConn != null) {
            dBusConn.disconnect();
        }
    }
}

From source file:com.ibm.replication.iidr.utils.Bookmarks.java

public static void main(String[] args) throws ConfigurationException, IllegalArgumentException,
        IllegalAccessException, FileNotFoundException, IOException {
    System.setProperty("log4j.configurationFile",
            System.getProperty("user.dir") + File.separatorChar + "conf" + File.separatorChar + "log4j2.xml");
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    LoggerConfig loggerConfig = config.getLoggerConfig("com.ibm.replication.iidr.utils.Bookmarks");
    loggerConfig.setLevel(Level.DEBUG);
    ctx.updateLoggers();/*from   w w  w.java  2 s.c o m*/
    new Bookmarks("EventLogBookmarks.properties");
}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.FormFileUploaderClientApplication.java

/**
 * Run the program./*from  ww w  .java2s. c o  m*/
 * 
 * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value.
 */
public static void main(String[] args) {
    // takes file path from first program's argument
    if (args.length < 1) {
        logger.error("****** Path to input file must be first argument to program! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    String filePath = args[0];
    File uploadFile = new File(filePath);
    if (!uploadFile.exists()) {
        logger.error("****** File does not exist at expected locations! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    if (args.length > 1) {
        serverUrl = args[1];
    }

    logger.info("File to upload: " + filePath);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverUrl);
        FileBody bin = new FileBody(uploadFile);
        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart(FORM_FIELD_DATAFILE, bin).build();
        httppost.setEntity(reqEntity);

        logger.info("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            logger.info("HTTP Response Status Line: " + response.getStatusLine());
            // Expecting a 200 Status Code
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String reason = response.getStatusLine().getReasonPhrase();
                logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode()
                        + "] -- Reason (if available): " + reason);
            } else {
                HttpEntity resEntity = response.getEntity();
                InputStream is = resEntity.getContent();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));

                String output;
                StringBuilder sb = new StringBuilder("Response data received:");
                while ((output = in.readLine()) != null) {
                    sb.append(System.getProperty("line.separator"));
                    sb.append(output);
                }
                logger.info(sb.toString());
                in.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        logger.error("Caught exception: " + e.getMessage(), e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            logger.warn("Exception closing HTTP client: " + e.getMessage(), e);
        }
        logger.info("DONE");
    }
}