Example usage for java.text DateFormat parse

List of usage examples for java.text DateFormat parse

Introduction

In this page you can find the example usage for java.text DateFormat parse.

Prototype

public Date parse(String source) throws ParseException 

Source Link

Document

Parses text from the beginning of the given string to produce a date.

Usage

From source file:com.bloomreach.bstore.highavailability.models.SolrCore.java

/**
 * Given another solrcore, do a data match between both of these cores.
 * If it fails, specify a reason. The data match is computed base on index version, core availability
 * and last modified time. We can add more based on num docs but that is for future work.
 * @param replica//  w ww .  ja va2s  .  c  o m
 * @return {@link cascading.util.Pair}
 * @return
 */
public Pair<Boolean, String> dataMatch(SolrCore replica) {
    Pair<Boolean, String> dataMatchToReasonPair = new Pair<Boolean, String>(true, "");
    boolean success = true;
    String reason = "";
    if (!this.available) {
        reason = "DataMatch-Failed: this core not available: " + this.toString();
        success = false;
    }
    if (!replica.available) {
        reason = "DataMatch-Failed: replica core not available: " + replica.toString();
        success = false;
    }

    // If the source version is greater than the replication version, it is a failed replication. Destination version
    // can be greater than the source (solr can decide to increment version of index after replication on the
    // destination node)
    if (this.version > replica.version) {
        reason = ("DataMatch-Failed: Version mismatch: this:" + this.version + " replica:" + replica.version);
        success = false;
    }

    // We also need to do a sanity check on the last update time
    if (StringUtils.isBlank(this.lastModified) || StringUtils.isBlank(replica.lastModified)) {
        logger.warn(
                "Either replica or source last index update time is unkown, will not do the timestamp check, source: "
                        + this.host + " " + this.name + " replica: " + replica.host + " " + replica.name);
    } else {
        String solrTimeFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
        try {
            DateFormat format = new SimpleDateFormat(solrTimeFormat);
            Date sourceDate = format.parse(this.lastModified);
            Date replicaDate = format.parse(replica.lastModified);
            long delta = Math.abs(sourceDate.getTime() - replicaDate.getTime());
            logger.info("this is the delta: " + delta + " souce: " + this.name + "replica: " + replica.name);
            // If the time diff greater than 60 minutes, we will mark it as unsuccessful since our
            // replication timeout is set at 60 minutes
            if (delta > 60 * 60 * 1000) {
                reason += "  last index update time between source and replica are different more than 60 minutes: source: "
                        + this.lastModified + " replica: " + replica.lastModified;
                success = false;
            }
        } catch (Exception e) {
            logger.warn(
                    "Can't parse the date of last index update date, skipping last update time check, source: "
                            + this.host + " " + this.name + " " + this.lastModified + " replica: "
                            + replica.host + " " + replica.name + replica.lastModified);
            logger.warn("ST: " + ExceptionUtils.getFullStackTrace(e));
        }
    }

    dataMatchToReasonPair.setLhs(success);
    dataMatchToReasonPair.setRhs(reason);

    return dataMatchToReasonPair;
}

From source file:info.rmapproject.core.rmapservice.impl.openrdf.ORMapStatementMgrTest.java

@SuppressWarnings("unused")
@Test//from w w  w .j av a2  s .  com
public void testGetAssertingAgents() {
    try {

        //create new test agent
        RMapAgent agent = new ORMapAgent(AGENT_IRI, ID_PROVIDER_IRI, AUTH_ID_IRI, NAME);
        java.net.URI agentId = agent.getId().getIri();
        if (!rmapService.isAgentId(agentId)) {
            rmapService.createAgent(agent, requestAgent);
        }
        if (rmapService.isAgentId(agentId)) {
            System.out.println("Test Agent successfully created!  URI is " + agentId);
        }

        //create disco            
        InputStream stream = new ByteArrayInputStream(discoRDF.getBytes(StandardCharsets.UTF_8));
        RioRDFHandler handler = new RioRDFHandler();
        Set<Statement> stmts = handler.convertRDFToStmtList(stream, RDFType.RDFXML, "");
        ORMapDiSCO disco = new ORMapDiSCO(stmts);
        IRI keyId = ORAdapter.uri2OpenRdfIri(new java.net.URI("ark:/29297/testkey"));
        ORMapEvent event = discomgr.createDiSCO(disco, requestAgent, triplestore);

        Set<URI> sysAgents = new HashSet<URI>();
        sysAgents.add(agentId);

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date dateFrom = dateFormat.parse("2014-1-1");
        Date dateTo = dateFormat.parse("2050-1-1");
        IRI subject = ORAdapter.getValueFactory().createIRI("http://dx.doi.org/10.1109/ACCESS.2014.2332453");
        IRI predicate = ORAdapter.getValueFactory().createIRI("http://purl.org/dc/elements/1.1/subject");
        Value object = ORAdapter.getValueFactory().createLiteral("Hadoop");
        RMapSearchParams params = new RMapSearchParams();
        params.setDateRange(dateFrom, dateTo);
        params.setSystemAgents(sysAgents);

        ORMapStatementMgr stmtMgr = new ORMapStatementMgr();
        Set<IRI> agentIds = stmtMgr.getAssertingAgents(subject, predicate, object, params, triplestore);

        assertTrue(agentIds.size() == 1);

        Iterator<IRI> iter = agentIds.iterator();
        IRI matchingAgentId = iter.next();
        assertTrue(matchingAgentId.toString().equals(agentId.toString()));
        rmapService.deleteDiSCO(disco.getId().getIri(), requestAgent);

    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }
}

From source file:net.webpasswordsafe.server.report.JasperReportServlet.java

private Timestamp convertToDateTime(String pValue) throws ParseException {
    Timestamp pDateValue = null;/*from   w w  w . j av a2  s  .c o  m*/
    if (!"".equals(pValue)) {
        // try with timestamp
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            pDateValue = new Timestamp(dateFormat.parse(pValue).getTime());
        } catch (ParseException pe) {
            // try without timestamp
            dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            pDateValue = new Timestamp(dateFormat.parse(pValue).getTime());
            // throw exception if neither parsed
        }
    }
    return pDateValue;
}

From source file:com.glaf.core.util.GetterUtils.java

public static Date get(String value, DateFormat dateFormat, Date defaultValue) {

    if (value == null) {
        return defaultValue;
    }/*www  . j av  a 2s .c  om*/

    try {
        Date date = dateFormat.parse(value.trim());

        if (date != null) {
            return date;
        }
    } catch (Exception e) {
    }

    return defaultValue;
}

From source file:org.openmrs.module.errorlogging.web.controller.ViewErrorLoggingController.java

/**
 * Convert input string arguments to Date
 *
 * @param exceptionDateTime date string/*from   w w w . j  av  a 2s.c  o m*/
 * @return converted date
 */
private Date getDateTime(String exceptionDateTime) {
    Date stExceptionDateTime = null;
    if (StringUtils.isNotBlank(exceptionDateTime)) {
        exceptionDateTime = exceptionDateTime.trim();

        String dateTime = exceptionDateTime + ":00";
        DateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
        try {
            stExceptionDateTime = (Date) format.parse(dateTime);
        } catch (ParseException ex) {
            log.error("Cannot parse date", ex);
        }
    }
    return stExceptionDateTime;
}

From source file:com.cyw.common.util.bean.DateConverter.java

protected Object convertToDate(Class type, Object value, String pattern) {
    DateFormat df = new SimpleDateFormat(pattern);
    if (value instanceof String) {
        try {/*from w ww  .j  a v  a 2 s .c  o  m*/
            if (StringUtils.isEmpty(value.toString())) {
                return null;
            }
            Date date = df.parse((String) value);
            if (type.equals(Timestamp.class)) {
                return new Timestamp(date.getTime());
            }
            return date;
        } catch (Exception pe) {
            pe.printStackTrace();
            throw new ConversionException("Error converting String to Date");
        }
    } else if (value instanceof Timestamp) {
        try {
            Timestamp timestamp = (Timestamp) value;
            Date date = new Date(timestamp.getTime());
            return date;
        } catch (Exception pe) {
            pe.printStackTrace();
            throw new ConversionException("Error converting Timestamp to Date");
        }
    } else if (value instanceof java.sql.Date) {
        try {
            java.sql.Date sqlDate = (java.sql.Date) value;
            return new Date(sqlDate.getTime());
        } catch (Exception pe) {
            pe.printStackTrace();
            throw new ConversionException("Error converting String to Date");
        }
    } else if (value instanceof Date) {
        return value;
    }
    throw new ConversionException("Could not convert " + value.getClass().getName() + " to " + type.getName());
}

From source file:com.luna.common.repository.UserRepository2ImplForDefaultSearchIT.java

@Test
public void testEqForDate() throws ParseException {
    int count = 15;
    String dateStr = "2012-01-15 16:59:00";
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    for (int i = 0; i < count; i++) {
        User user = createUser();/* w  ww .  jav a 2 s .c  om*/
        user.setRegisterDate(df.parse(dateStr));
        userRepository2.save(user);
    }

    Searchable search = Searchable.newSearchable().addSearchParam("registerDate_eq", dateStr);
    assertEquals(count, userRepository2.countAllByDefault(search));
}

From source file:com.gargoylesoftware.htmlunit.ExternalTest.java

/**
 * Tests that the deployed snapshot is not more than two weeks old.
 *
 * Currently it is configured to check every week.
 *
 * @throws Exception if an error occurs//from   w  ww . ja  va 2s . co  m
 */
@Test
public void snapshot() throws Exception {
    if (isDifferentWeek()) {
        final List<String> lines = FileUtils.readLines(new File("pom.xml"));
        String version = null;
        for (int i = 0; i < lines.size(); i++) {
            if ("<artifactId>htmlunit</artifactId>".equals(lines.get(i).trim())) {
                version = getValue(lines.get(i + 1));
                break;
            }
        }
        if (version.contains("SNAPSHOT")) {
            try (final WebClient webClient = getWebClient()) {
                final XmlPage page = webClient
                        .getPage("https://oss.sonatype.org/content/repositories/snapshots/"
                                + "net/sourceforge/htmlunit/htmlunit/" + version + "/maven-metadata.xml");
                final String timestamp = page.getElementsByTagName("timestamp").get(0).getTextContent();
                final DateFormat format = new SimpleDateFormat("yyyyMMdd.HHmmss", Locale.ROOT);
                final long snapshotMillis = format.parse(timestamp).getTime();
                final long nowMillis = System.currentTimeMillis();
                final long days = TimeUnit.MILLISECONDS.toDays(nowMillis - snapshotMillis);
                assertTrue("Snapshot not deployed for " + days + " days", days < 14);
            }
        }
    }
}

From source file:com.vrv.common.converter.DateConverter.java

@SuppressWarnings("rawtypes")
protected Object convertToDate(Class type, Object value, String pattern) {
    DateFormat df = new SimpleDateFormat(pattern);
    if (value instanceof String) {
        try {/*from   w  ww .ja va 2 s .c  o  m*/
            if (StringUtils.isEmpty(value.toString())) {
                return null;
            }
            Date date = df.parse((String) value);
            if (type.equals(Timestamp.class)) {
                return new Timestamp(date.getTime());
            }
            return date;
        } catch (Exception pe) {
            pe.printStackTrace();
            throw new ConversionException("Error converting String to Date");
        }
    } else if (value instanceof Timestamp) {
        try {
            Timestamp timestamp = (Timestamp) value;
            Date date = new Date(timestamp.getTime());
            return date;
        } catch (Exception pe) {
            pe.printStackTrace();
            throw new ConversionException("Error converting Timestamp to Date");
        }
    } else if (value instanceof java.sql.Date) {
        try {
            java.sql.Date sqlDate = (java.sql.Date) value;
            return new Date(sqlDate.getTime());
        } catch (Exception pe) {
            pe.printStackTrace();
            throw new ConversionException("Error converting String to Date");
        }
    } else if (value instanceof Date) {
        return value;
    }
    throw new ConversionException("Could not convert " + value.getClass().getName() + " to " + type.getName());
}

From source file:microsoft.exchange.webservices.data.core.EwsUtilities.java

/**
 * Parses the./*from   w  ww  .  jav a 2  s  .  c o m*/
 *
 * @param <T>   the generic type
 * @param cls   the cls
 * @param value the value
 * @return the t
 * @throws java.text.ParseException the parse exception
 */
@SuppressWarnings("unchecked")
public static <T> T parse(Class<T> cls, String value) throws ParseException {
    if (cls.isEnum()) {
        final Map<Class<?>, Map<String, String>> member = SCHEMA_TO_ENUM_DICTIONARIES.getMember();

        String val = value;
        final Map<String, String> stringToEnumDict = member.get(cls);
        if (stringToEnumDict != null) {
            final String strEnumName = stringToEnumDict.get(value);
            if (strEnumName != null) {
                val = strEnumName;
            }
        }
        for (T o : cls.getEnumConstants()) {
            if (o.toString().equals(val)) {
                return o;
            }
        }
        return null;
    } else if (Number.class.isAssignableFrom(cls)) {
        if (Double.class.isAssignableFrom(cls)) {
            return (T) ((Double) Double.parseDouble(value));
        } else if (Integer.class.isAssignableFrom(cls)) {
            return (T) ((Integer) Integer.parseInt(value));
        } else if (Long.class.isAssignableFrom(cls)) {
            return (T) ((Long) Long.parseLong(value));
        } else if (Float.class.isAssignableFrom(cls)) {
            return (T) ((Float) Float.parseFloat(value));
        } else if (Byte.class.isAssignableFrom(cls)) {
            return (T) ((Byte) Byte.parseByte(value));
        } else if (Short.class.isAssignableFrom(cls)) {
            return (T) ((Short) Short.parseShort(value));
        } else if (BigInteger.class.isAssignableFrom(cls)) {
            return (T) (new BigInteger(value));
        } else if (BigDecimal.class.isAssignableFrom(cls)) {
            return (T) (new BigDecimal(value));
        }
    } else if (Date.class.isAssignableFrom(cls)) {
        DateFormat df = createDateFormat(XML_SCHEMA_DATE_TIME_FORMAT);
        return (T) df.parse(value);
    } else if (Boolean.class.isAssignableFrom(cls)) {
        return (T) ((Boolean) Boolean.parseBoolean(value));
    } else if (String.class.isAssignableFrom(cls)) {
        return (T) value;
    }
    return null;
}