Example usage for java.text SimpleDateFormat format

List of usage examples for java.text SimpleDateFormat format

Introduction

In this page you can find the example usage for java.text SimpleDateFormat format.

Prototype

public final String format(Date date) 

Source Link

Document

Formats a Date into a date-time string.

Usage

From source file:Tester2.java

public static void main(String[] args) {
    try {/*from   w  w  w. j  a  va  2 s . c o  m*/
        String line7 = "1 25544U 98067A   16003.88353887  .00008341  00000-0  12778-3 0  9994";
        String line8 = "2 25544  51.6424 162.4509 0008302 358.1918 164.3460 15.55244436979265";

        double latitude = 36.211389;
        double longitude = -81.668611;
        double altitude = 1016;

        // configure Orekit
        AutoconfigurationCustom.configureOrekit();

        //SUNLocation
        CelestialBody testSun = CelestialBodyFactory.getSun();
        CelestialBody testEarth = CelestialBodyFactory.getEarth();

        // Get UTC time
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy,MM,dd,HH,mm,ss");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        String[] utcTime = sdf.format(new Date()).split(",");

        // Gets times and date
        double futureDayProp = 3; // duration in 24-hour day 
        //AbsoluteDate currentDate = new AbsoluteDate(2016, 1, 1, 23, 50, 0.000, TimeScalesFactory.getUTC());
        AbsoluteDate currentDate = new AbsoluteDate(Integer.parseInt(utcTime[0]), Integer.parseInt(utcTime[1]),
                Integer.parseInt(utcTime[2]), Integer.parseInt(utcTime[3]), Integer.parseInt(utcTime[4]),
                Integer.parseInt(utcTime[5]), TimeScalesFactory.getUTC());

        Tester2 awesome = new Tester2(line7, line8, testSun, testEarth, latitude, longitude, altitude,
                currentDate.shiftedBy(futureDayProp * 24 * 3600));//targetDate.shiftedBy(3*24*3600));
        awesome.QuickCheck();

        System.out.println("done");

        // Propagate from the initial date to the first raising or for the fixed duration
        ////////////////SpacecraftState finalState = TLEProp.propagate(targetDate);

        ///////////////////System.out.println(" Final state : " + finalState.getDate().durationFrom(targetDate));

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

From source file:Main.java

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

    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

    String oeStartDateStr = "04/01/2015";
    String oeEndDateStr = "11/14/2015";

    Calendar cal = Calendar.getInstance();
    Integer year = cal.get(Calendar.YEAR);

    oeStartDateStr = oeStartDateStr.concat(year.toString());
    oeEndDateStr = oeEndDateStr.concat(year.toString());

    Date startDate = sdf.parse(oeStartDateStr);
    Date endDate = sdf.parse(oeEndDateStr);
    Date d = new Date();
    String currDt = sdf.format(d);

    if ((d.after(startDate) && (d.before(endDate)))
            || (currDt.equals(sdf.format(startDate)) || currDt.equals(sdf.format(endDate)))) {
        System.out.println("Date is between 1st april to 14th nov...");
    } else {//from   www  .java  2s  .  co  m
        System.out.println("Date is not between 1st april to 14th nov...");
    }
}

From source file:net.sf.jsignpdf.InstallCert.java

/**
 * The main - whole logic of Install Cert Tool.
 * /*www . j a  v  a2s  . c om*/
 * @param args
 * @throws Exception
 */
public static void main(String[] args) {
    String host;
    int port;
    char[] passphrase;

    System.out.println("InstallCert - Install CA certificate to Java Keystore");
    System.out.println("=====================================================");

    final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    try {
        if ((args.length == 1) || (args.length == 2)) {
            String[] c = args[0].split(":");
            host = c[0];
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
            String p = (args.length == 1) ? "changeit" : args[1];
            passphrase = p.toCharArray();
        } else {
            String tmpStr;
            do {
                System.out.print("Enter hostname or IP address: ");
                tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null);
            } while (tmpStr == null);
            host = tmpStr;
            System.out.print("Enter port number [443]: ");
            tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null);
            port = tmpStr == null ? 443 : Integer.parseInt(tmpStr);
            System.out.print("Enter keystore password [changeit]: ");
            tmpStr = reader.readLine();
            String p = "".equals(tmpStr) ? "changeit" : tmpStr;
            passphrase = p.toCharArray();
        }

        char SEP = File.separatorChar;
        final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
        final File file = new File(dir, "cacerts");

        System.out.println("Loading KeyStore " + file + "...");
        InputStream in = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        in.close();

        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();

        System.out.println("Opening connection to " + host + ":" + port + "...");
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            System.out.println("Starting SSL handshake...");
            socket.startHandshake();
            socket.close();
            System.out.println();
            System.out.println("No errors, certificate is already trusted");
        } catch (SSLException e) {
            System.out.println();
            System.out.println("Certificate is not yet trusted.");
            //        e.printStackTrace(System.out);
        }

        X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.out.println("Could not obtain server certificate chain");
            return;
        }

        System.out.println();
        System.out.println("Server sent " + chain.length + " certificate(s):");
        System.out.println();
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = chain[i];
            System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN());
            System.out.println("   Issuer  " + cert.getIssuerDN());
            sha1.update(cert.getEncoded());
            System.out.println("   sha1    " + toHexString(sha1.digest()));
            md5.update(cert.getEncoded());
            System.out.println("   md5     " + toHexString(md5.digest()));
            System.out.println();
        }

        System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: ");
        String line = reader.readLine().trim();
        int k = -1;
        try {
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
        } catch (NumberFormatException e) {
        }

        if (k < 0 || k >= chain.length) {
            System.out.println("KeyStore not changed");
        } else {
            try {
                System.out.println("Creating keystore backup");
                final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                final File backupFile = new File(dir,
                        CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date()));
                final FileInputStream fis = new FileInputStream(file);
                final FileOutputStream fos = new FileOutputStream(backupFile);
                IOUtils.copy(fis, fos);
                fis.close();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Installing certificate...");

            X509Certificate cert = chain[k];
            String alias = host + "-" + (k + 1);
            ks.setCertificateEntry(alias, cert);

            OutputStream out = new FileOutputStream(file);
            ks.store(out, passphrase);
            out.close();

            System.out.println();
            System.out.println(cert);
            System.out.println();
            System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'");
        }
    } catch (Exception e) {
        System.out.println();
        System.out.println("----------------------------------------------");
        System.out.println("Problem occured during installing certificate:");
        e.printStackTrace();
        System.out.println("----------------------------------------------");
    }
    System.out.println("Press Enter to finish...");
    try {
        reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.qzgf.datacollection.timer.Yd12580TimerTask.java

public static void main(String[] args) {
    PostalServiceSoapProxy proxy = new PostalServiceSoapProxy();

    ///*from w  w w  . j av  a  2s .co m*/
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
    Date currentTime = new Date();//?   
    String nowtime = formatter.format(currentTime); //?  
    //?()
    try {
        String username = "12580postal";
        String passwd = "12580postal";
        String parameter = "";//116,-1,178

        System.out.println("say no");

        //
        username = username + nowtime;
        passwd = passwd + nowtime;

        MD5 md5 = new MD5();
        username = md5.StrToMd5(username);
        passwd = md5.StrToMd5(passwd);

        //         try {
        //            MessageDigest md;
        //            md = MessageDigest.getInstance("MD5");
        //            BASE64Encoder base64en = new BASE64Encoder();
        ////            username=new String(md.digest(username.getBytes("UTF-8")),"UTF-8");
        ////            passwd=new String(md.digest(passwd.getBytes("UTF-8")),"UTF-8");
        //            username=new String(base64en.encode(md.digest(username.getBytes())));
        //            passwd=new String(base64en.encode(md.digest(passwd.getBytes())));
        //         } catch (NoSuchAlgorithmException e) {
        //            // TODO Auto-generated catch block
        //            e.printStackTrace();
        ////         }catch (UnsupportedEncodingException e) {
        ////            // TODO Auto-generated catch block
        ////            e.printStackTrace();
        //         }

        System.out.println("hello");
        //661B4842E1F2F64FABFE96DE5B1CDBEF
        //         username="7D5F89392DDD0DD9A2F76C61C4AD61E2";
        //         passwd="7D5F89392DDD0DD9A2F76C61C4AD61E2";
        Postal[] ps = proxy.getList(username, passwd, parameter);//parameter

        if (ps != null) {
            for (int i = 0; i < ps.length; i++) {
                System.out.println("ps[i].getAddress()" + ps[i].getAddress());
                System.out.println("ps[i].getContactor()" + ps[i].getContactor());
                System.out.println("ps[i].getIsFee()" + ps[i].getIsFee());
                System.out.println("ps[i].getOrderID()" + ps[i].getOrderID());
                System.out.println("ps[i].getPhone()" + ps[i].getPhone());
                System.out.println("ps[i].getPrice()" + ps[i].getPrice());
                System.out.println("ps[i].getSpec()" + ps[i].getSpec());
                System.out.println("ps[i].getCity()" + ps[i].getCity());
                System.out.println("ps[i].getPostCode()" + ps[i].getPostCode());
                System.out.println("ps[i].getCounty()" + ps[i].getCounty());
                System.out.println("ps[i].getProvince()" + ps[i].getProvince());

                System.out.println("ps[i].getRecAddress()" + ps[i].getRecAddress());
                System.out.println("ps[i].getRecCity()" + ps[i].getRecCity());
                System.out.println("ps[i].getRecTel()" + ps[i].getRecTel());
                System.out.println("ps[i].getRecProvince()" + ps[i].getRecProvince());
                System.out.println("ps[i].getRecCounty()" + ps[i].getRecCounty());
                System.out.println("ps[i].getRecName()" + ps[i].getRecName());
                System.out.println("\r\n\r\n");
            }
        }
        ///         System.out.println("???"+proxy.postalGetDataBack("1000068,1000081,1000087,1000088,1000089,1000090"));
    } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:eu.trentorise.opendata.jackan.test.ckan.CkanTestReporter.java

/**
 * Takes as first argument the catalog list files to be used. If not
 * provided, by default test/resources/ckan-instances.txt file is used.
 *//* www. ja va2s .  c  o  m*/
public static void main(String[] args) {

    JackanTestConfig.of().loadConfig();

    String catFilename;

    if (args.length == 2) {
        catFilename = args[1];
        logger.log(Level.INFO, "Using provided catalogs file {0}", catFilename);
    } else {
        catFilename = "ckan-instances.txt";
        logger.log(Level.INFO,
                "Using default catalogs file {0}. If you wish to provide yours pass filename as first argument.",
                catFilename);
    }

    Map<String, String> catalogsNames = readCatalogsList(catFilename);

    List<String> testNames = ALL_TEST_NAMES;

    RunSuite testResults = runTests(catalogsNames, testNames);

    String content = renderRunSuite(catalogsNames, testNames, testResults);

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd--HH-mm-ss");
    saveToDirectory(new File("reports/" + REPORT_PREFIX + "-" + formatter.format(new Date())), content,
            testResults);

    File latestDir = new File("reports/" + REPORT_PREFIX + "-latest");

    FileUtils.deleteQuietly(latestDir);
    saveToDirectory(latestDir, content, testResults);

}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    SimpleDateFormat xmlDateFormat = new SimpleDateFormat("MM.dd.yy");

    MapVariableResolver resolver = new MapVariableResolver();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = dbf.newDocumentBuilder();
    Document document = builder.parse(new File("t.xml"));

    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    xPath.setXPathVariableResolver(resolver);
    XPathExpression expression = xPath.compile("/schedule/show[@date=$date]/guest");

    String formattedDate = xmlDateFormat.format(new Date(2006, 5, 14));
    resolver.addVariable(null, "date", formattedDate);
    Element guest = (Element) expression.evaluate(document, XPathConstants.NODE);

    System.out.println(guest.getElementsByTagName("name").item(0).getTextContent());
}

From source file:com.zimbra.qa.unittest.prov.ldap.TestLdapReadTimeout.java

/**
 * /Users/pshao/dev/workspace/sandbox/sandbox/bin>/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home/bin/java  LdapReadTimeout
 * /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home/bin/java LdapReadTimeout
 * /*from w  w  w.  j  a v  a  2  s .  c om*/
 * zmjava com.zimbra.qa.unittest.TestLdapReadTimeout -s 5
 * zmjava com.zimbra.qa.unittest.TestLdapReadTimeout -H ldap://localhost:389 -D uid=zimbra,cn=admins,cn=zimbra -w zimbra -s 5
 * 
 * @param args
 */
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(O_HELP, false, "print usage");
    options.addOption(O_SLEEP, true, "upon hitting an Exception, minutes to wait until exiting the program.  "
            + "If not specified, will exit immediately.");
    options.addOption(O_URI, true, "URI. e.g. ldap://localhost:389");
    options.addOption(O_BINDDN, true, "bind DN");
    options.addOption(O_PASSWORD, true, "password");

    CommandLine cl = null;
    try {
        CommandLineParser parser = new GnuParser();
        cl = parser.parse(options, args);
        if (cl == null) {
            throw new ParseException("");
        }
    } catch (ParseException e) {
        usage(options);
        e.printStackTrace();
        System.exit(1);
    }

    if (cl.hasOption(O_HELP)) {
        usage(options);
        System.exit(0);
    }

    String uri = null;
    String bindDN = null;
    String password = null;
    Integer minutesToWait = null;

    if (cl.hasOption(O_URI)) {
        uri = cl.getOptionValue(O_URI);
    } else {
        uri = "ldap://localhost:389";
    }

    if (cl.hasOption(O_BINDDN)) {
        bindDN = cl.getOptionValue(O_BINDDN);
    } else {
        bindDN = "uid=zimbra,cn=admins,cn=zimbra";
    }

    if (cl.hasOption(O_PASSWORD)) {
        password = cl.getOptionValue(O_PASSWORD);
    } else {
        password = "zimbra";
    }

    if (cl.hasOption(O_SLEEP)) {
        String wait = cl.getOptionValue(O_SLEEP);

        try {
            minutesToWait = Integer.valueOf(wait);
        } catch (NumberFormatException e) {
            usage(options);
            e.printStackTrace();
            System.exit(1);
        }
    }

    LdapReadTimeoutTester tester = null;

    try {
        // tester = new JNDITest(uri, bindDN, password);  // fails
        tester = new UnboundIDTest(uri, bindDN, password); // works

        System.out.println("=============");
        System.out.println(tester.getClass().getCanonicalName());
        System.out.println("LDAP server URI: " + uri);
        System.out.println("bind DN: " + bindDN);
        System.out.println("=============");
        System.out.println();

    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    long startTime = System.currentTimeMillis();
    test(tester);
    long endTime = System.currentTimeMillis();
    long elapsed = endTime - startTime;

    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    System.out.println();
    System.out.println(tester.getClass().getCanonicalName());
    System.out.println("Started at: " + fmt.format(new Date(startTime)));
    System.out.println("Ended at: " + fmt.format(new Date(endTime)));
    System.out.println("Elapsed = " + (elapsed / 1000) + " seconds");
    System.out.println();

    if (minutesToWait != null) {
        System.out.println("Sleeping for " + minutesToWait + " minutes before exiting...");
        Thread.sleep(minutesToWait * 60 * 1000);
    }
}

From source file:accinapdf.ACCinaPDF.java

/**
 * @param args the command line arguments
 *//*from w w w  . ja  v  a 2  s  . co  m*/
public static void main(String[] args) {

    controller.Logger.create();
    controller.Bundle.getBundle();

    if (GraphicsEnvironment.isHeadless()) {
        // Headless
        // Erro 
        String fich;
        if (args.length != 1) {
            System.err.println(Bundle.getBundle().getString("invalidArgs"));
            return;
        } else {
            fich = args[0];
        }

        try {
            System.out.println(Bundle.getBundle().getString("validating") + " " + fich);
            ArrayList<SignatureValidation> alSv = CCInstance.getInstance().validatePDF(fich, null);
            if (alSv.isEmpty()) {
                System.out.println(Bundle.getBundle().getString("notSigned"));
            } else {
                String newLine = System.getProperty("line.separator");
                String toWrite = "(";
                int numSigs = alSv.size();
                if (numSigs == 1) {
                    toWrite += "1 " + Bundle.getBundle().getString("signature");
                } else {
                    toWrite += numSigs + " " + Bundle.getBundle().getString("signatures");
                }
                toWrite += ")" + newLine;
                for (SignatureValidation sv : alSv) {
                    toWrite += "\t" + sv.getName() + " - ";
                    toWrite += (sv.isCertification()
                            ? WordUtils.capitalize(Bundle.getBundle().getString("certificate"))
                            : WordUtils.capitalize(Bundle.getBundle().getString("signed"))) + " "
                            + Bundle.getBundle().getString("by") + " " + sv.getSignerName();
                    toWrite += newLine + "\t\t";
                    if (sv.isChanged()) {
                        toWrite += Bundle.getBundle().getString("certifiedChangedOrCorrupted");
                    } else {
                        if (sv.isCertification()) {
                            if (sv.isValid()) {
                                if (sv.isChanged() || !sv.isCoversEntireDocument()) {
                                    toWrite += Bundle.getBundle().getString("certifiedButChanged");
                                } else {
                                    toWrite += Bundle.getBundle().getString("certifiedOk");
                                }
                            } else {
                                toWrite += Bundle.getBundle().getString("changedAfterCertified");
                            }
                        } else {
                            if (sv.isValid()) {
                                if (sv.isChanged()) {
                                    toWrite += Bundle.getBundle().getString("signedButChanged");
                                } else {
                                    toWrite += Bundle.getBundle().getString("signedOk");
                                }
                            } else {
                                toWrite += Bundle.getBundle().getString("signedChangedOrCorrupted");
                            }
                        }
                    }
                    toWrite += newLine + "\t\t";
                    if (sv.getOcspCertificateStatus().equals(CertificateStatus.OK)
                            || sv.getCrlCertificateStatus().equals(CertificateStatus.OK)) {
                        toWrite += Bundle.getBundle().getString("certOK");
                    } else if (sv.getOcspCertificateStatus().equals(CertificateStatus.REVOKED)
                            || sv.getCrlCertificateStatus().equals(CertificateStatus.REVOKED)) {
                        toWrite += Bundle.getBundle().getString("certRevoked");
                    } else if (sv.getOcspCertificateStatus().equals(CertificateStatus.UNCHECKED)
                            && sv.getCrlCertificateStatus().equals(CertificateStatus.UNCHECKED)) {
                        toWrite += Bundle.getBundle().getString("certNotVerified");
                    } else if (sv.getOcspCertificateStatus().equals(CertificateStatus.UNCHAINED)) {
                        toWrite += Bundle.getBundle().getString("certNotChained");
                    } else if (sv.getOcspCertificateStatus().equals(CertificateStatus.EXPIRED)) {
                        toWrite += Bundle.getBundle().getString("certExpired");
                    } else if (sv.getOcspCertificateStatus().equals(CertificateStatus.CHAINED_LOCALLY)) {
                        toWrite += Bundle.getBundle().getString("certChainedLocally");
                    }
                    toWrite += newLine + "\t\t";
                    if (sv.isValidTimeStamp()) {
                        toWrite += Bundle.getBundle().getString("validTimestamp");
                    } else {
                        toWrite += Bundle.getBundle().getString("signerDateTime");
                    }
                    toWrite += newLine + "\t\t";

                    toWrite += WordUtils.capitalize(Bundle.getBundle().getString("revision")) + ": "
                            + sv.getRevision() + " " + Bundle.getBundle().getString("of") + " "
                            + sv.getNumRevisions();
                    toWrite += newLine + "\t\t";
                    final DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                    final SimpleDateFormat sdf = new SimpleDateFormat("Z");
                    if (sv.getSignature().getTimeStampToken() == null) {
                        Calendar cal = sv.getSignature().getSignDate();
                        String date = sdf.format(cal.getTime().toLocaleString());
                        toWrite += date + " " + sdf.format(cal.getTime()) + " ("
                                + Bundle.getBundle().getString("signerDateTimeSmall") + ")";
                    } else {
                        Calendar ts = sv.getSignature().getTimeStampDate();
                        String date = df.format(ts.getTime());
                        toWrite += Bundle.getBundle().getString("date") + " " + date + " "
                                + sdf.format(ts.getTime());
                    }
                    toWrite += newLine + "\t\t";
                    boolean ltv = (sv.getOcspCertificateStatus() == CertificateStatus.OK
                            || sv.getCrlCertificateStatus() == CertificateStatus.OK);
                    toWrite += Bundle.getBundle().getString("isLtv") + ": "
                            + (ltv ? Bundle.getBundle().getString("yes") : Bundle.getBundle().getString("no"));
                    String reason = sv.getSignature().getReason();
                    toWrite += newLine + "\t\t";
                    toWrite += Bundle.getBundle().getString("reason") + ": ";
                    if (reason == null) {
                        toWrite += Bundle.getBundle().getString("notDefined");
                    } else if (reason.isEmpty()) {
                        toWrite += Bundle.getBundle().getString("notDefined");
                    } else {
                        toWrite += reason;
                    }
                    String location = sv.getSignature().getLocation();
                    toWrite += newLine + "\t\t";
                    toWrite += Bundle.getBundle().getString("location") + ": ";
                    if (location == null) {
                        toWrite += Bundle.getBundle().getString("notDefined");
                    } else if (location.isEmpty()) {
                        toWrite += Bundle.getBundle().getString("notDefined");
                    } else {
                        toWrite += location;
                    }
                    toWrite += newLine + "\t\t";
                    toWrite += Bundle.getBundle().getString("allowsChanges") + ": ";
                    try {
                        int certLevel = CCInstance.getInstance().getCertificationLevel(sv.getFilename());
                        if (certLevel == PdfSignatureAppearance.CERTIFIED_FORM_FILLING) {
                            toWrite += Bundle.getBundle().getString("onlyAnnotations");
                        } else if (certLevel == PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS) {
                            toWrite += Bundle.getBundle().getString("annotationsFormFilling");
                        } else if (certLevel == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED) {
                            toWrite += Bundle.getBundle().getString("no");
                        } else {
                            toWrite += Bundle.getBundle().getString("yes");
                        }
                    } catch (IOException ex) {
                        controller.Logger.getLogger().addEntry(ex);
                    }
                    toWrite += newLine + "\t\t";
                    if (sv.getOcspCertificateStatus() == CertificateStatus.OK
                            || sv.getCrlCertificateStatus() == CertificateStatus.OK) {
                        toWrite += (Bundle.getBundle().getString("validationCheck1") + " "
                                + (sv.getOcspCertificateStatus() == CertificateStatus.OK
                                        ? Bundle.getBundle().getString("validationCheck2") + ": "
                                                + CCInstance.getInstance().getCertificateProperty(
                                                        sv.getSignature().getOcsp().getCerts()[0].getSubject(),
                                                        "CN")
                                                + " " + Bundle.getBundle().getString("at") + " "
                                                + df.format(sv.getSignature().getOcsp().getProducedAt())
                                        : (sv.getCrlCertificateStatus() == CertificateStatus.OK ? "CRL" : ""))
                                + (sv.getSignature().getTimeStampToken() != null
                                        ? Bundle.getBundle().getString("validationCheck3") + ": "
                                                + CCInstance.getInstance()
                                                        .getCertificateProperty(sv.getSignature()
                                                                .getTimeStampToken().getSID().getIssuer(), "O")
                                        : ""));
                    } else if (sv.getSignature().getTimeStampToken() != null) {
                        toWrite += (Bundle.getBundle().getString("validationCheck3") + ": "
                                + CCInstance.getInstance().getCertificateProperty(
                                        sv.getSignature().getTimeStampToken().getSID().getIssuer(), "O"));
                    }
                    toWrite += newLine;
                }

                System.out.println(toWrite);
                System.out.println(Bundle.getBundle().getString("validationFinished"));
            }
        } catch (IOException | DocumentException | GeneralSecurityException ex) {
            System.err.println(Bundle.getBundle().getString("validationError"));
            Logger.getLogger(ACCinaPDF.class.getName()).log(Level.SEVERE, null, ex);
        }

    } else {
        // GUI
        CCSignatureSettings defaultSettings = new CCSignatureSettings(false);
        if (SystemUtils.IS_OS_WINDOWS) {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    try {
                        UIManager.setLookAndFeel(info.getClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                            | UnsupportedLookAndFeelException ex) {
                        Logger.getLogger(ACCinaPDF.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    break;
                }
            }
        } else if (SystemUtils.IS_OS_LINUX) {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    try {
                        UIManager.setLookAndFeel(info.getClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                            | UnsupportedLookAndFeelException ex) {
                        Logger.getLogger(ACCinaPDF.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    break;
                }
            }
        } else if (SystemUtils.IS_OS_MAC_OSX) {
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.mac.MacLookAndFeel");
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                    | UnsupportedLookAndFeelException ex) {
                Logger.getLogger(ACCinaPDF.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        new SplashScreen().setVisible(true);
    }
}

From source file:org.ala.hbase.RepoDataLoader.java

/**
 * This takes a list of infosource ids...
 * <p/>//  w  w w .  j a v  a2 s.  c  o  m
 * Usage: -stats or -reindex or -gList and list of infosourceId
 *
 * @param args
 */
public static void main(String[] args) throws Exception {
    //RepoDataLoader loader = new RepoDataLoader();
    ApplicationContext context = SpringUtils.getContext();
    RepoDataLoader loader = (RepoDataLoader) context.getBean(RepoDataLoader.class);
    long start = System.currentTimeMillis();
    loader.loadInfoSources();
    String filePath = repositoryDir;
    if (args.length > 0) {
        if (args[0].equalsIgnoreCase("-stats")) {
            loader.statsOnly = true;
            args = (String[]) ArrayUtils.subarray(args, 1, args.length);
        }
        if (args[0].equalsIgnoreCase("-reindex")) {
            loader.reindex = true;
            loader.indexer = context.getBean(PartialIndex.class);
            args = (String[]) ArrayUtils.subarray(args, 1, args.length);
            logger.info("**** -reindex: " + loader.reindex);
            logger.debug("reindex url: " + loader.reindexUrl);
        }
        if (args[0].equalsIgnoreCase("-gList")) {
            loader.gList = true;
            args = (String[]) ArrayUtils.subarray(args, 1, args.length);
            logger.info("**** -gList: " + loader.gList);
        }
        if (args[0].equalsIgnoreCase("-biocache")) {
            Hashtable<String, String> hashTable = new Hashtable<String, String>();
            hashTable.put("accept", "application/json");
            ObjectMapper mapper = new ObjectMapper();
            mapper.getDeserializationConfig().set(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
                    false);
            RestfulClient restfulClient = new RestfulClient(0);
            String fq = "&fq=";
            if (args.length > 1) {
                java.util.Date date = new java.util.Date();
                if (args[1].equals("-lastWeek")) {
                    date = DateUtils.addWeeks(date, -1);
                } else if (args[1].equals("-lastMonth")) {
                    date = DateUtils.addMonths(date, -1);
                } else if (args[1].equals("-lastYear")) {
                    date = DateUtils.addYears(date, -1);
                } else
                    date = null;
                if (date != null) {
                    SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

                    fq += "last_load_date:%5B" + sfd.format(date) + "%20TO%20*%5D";
                }
            }

            Object[] resp = restfulClient
                    .restGet("http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq
                            + "&facets=data_resource_uid&pageSize=0", hashTable);
            logger.info("The URL: " + "http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq
                    + "&facets=data_resource_uid&pageSize=0");
            if ((Integer) resp[0] == HttpStatus.SC_OK) {
                String content = resp[1].toString();
                logger.debug(resp[1]);
                if (content != null && content.length() > "[]".length()) {
                    Map map = mapper.readValue(content, Map.class);
                    try {
                        List<java.util.LinkedHashMap<String, String>> list = ((List<java.util.LinkedHashMap<String, String>>) ((java.util.LinkedHashMap) ((java.util.ArrayList) map
                                .get("facetResults")).get(0)).get("fieldResult"));
                        Set<String> arg = new LinkedHashSet<String>();
                        for (int i = 0; i < list.size(); i++) {
                            java.util.LinkedHashMap<String, String> value = list.get(i);
                            String dataResource = getDataResource(value.get("fq"));
                            Object provider = (loader.getUidInfoSourceMap().get(dataResource));
                            if (provider != null) {
                                arg.add(provider.toString());
                            }
                        }
                        logger.info("Set of biocache infosource ids to load: " + arg);
                        args = new String[] {};
                        args = arg.toArray(args);
                        //handle the situation where biocache-service reports no data resources
                        if (args.length < 1) {
                            logger.error("No biocache data resources found. Unable to load.");
                            System.exit(0);
                        }
                    } catch (Exception e) {
                        logger.error("ERROR: exit process....." + e);
                        e.printStackTrace();
                        System.exit(0);
                    }
                }
            } else {
                logger.warn("Unable to process url: ");
            }
        }
    }
    int filesRead = loader.load(filePath, args); //FIX ME - move to config
    long finish = System.currentTimeMillis();
    logger.info(filesRead + " files scanned/loaded in: " + ((finish - start) / 60000) + " minutes "
            + ((finish - start) / 1000) + " seconds.");
    System.exit(1);
}

From source file:de.codesourcery.eve.skills.ui.utils.CalendarWidget.java

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

    final SimpleDateFormat DF = new SimpleDateFormat("dd.MM");

    final Calendar specialDate = Calendar.getInstance();
    specialDate.add(Calendar.DAY_OF_MONTH, 5);

    final AtomicBoolean doStuff = new AtomicBoolean(false);

    final ICalendarRenderer renderer = new ICalendarRenderer() {

        @Override/*w ww. j  a v  a  2  s  .  co  m*/
        public String getDateLabel(Date date) {
            return DF.format(date);
        }

        @Override
        public String getText(Date date) {
            if (DateUtils.isSameDay(date, specialDate.getTime()) && doStuff.get()) {
                return "SPECIAL !!!";
            }
            return "some\nmultiline\ntext";
        }

        @Override
        public String getToolTip(Date date) {
            return getText(date);
        }

        @Override
        public Color getTextColor(Date date) {
            return Color.RED;
        }
    };

    final JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new GridBagLayout());

    final CalendarWidget widget = new CalendarWidget(new Date(), renderer);

    widget.addSelectionListener(new ISelectionListener<Date>() {

        @Override
        public void selectionChanged(Date selected) {
            System.out.println("Selected date > " + selected);
        }
    });
    frame.getContentPane().add(widget, new ConstraintsBuilder().end());
    frame.pack();
    frame.setVisible(true);

    java.lang.Thread.sleep(2 * 1000);
    doStuff.set(true);
    widget.refreshDateLabel(specialDate.getTime());

}