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:info.rmapproject.core.rmapservice.impl.openrdf.ORMapResourceMgrTest.java

@SuppressWarnings("unused")
@Test//from w  ww.j  av  a 2 s.c om
public void testGetRelatedAgents() {

    try {

        //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("rmap: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");

        RMapSearchParams params = new RMapSearchParams();
        params.setDateRange(dateFrom, dateTo);
        params.setSystemAgents(sysAgents);

        Set<IRI> agentIris = resourcemgr.getResourceAssertingAgents(
                ORAdapter.uri2OpenRdfIri(disco.getId().getIri()), params, triplestore);

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

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

    } catch (Exception e) {
        e.printStackTrace();
        fail();
    } finally {
        rmapService.closeConnection();
    }

}

From source file:gov.nih.nci.cabig.caaers.dao.query.AbstractQuery.java

public String createDateQuery(String fullAttributeName, String dateString, String predicate) throws Exception {
    Date dateValue = null;//from   ww w  .  ja va2s  .c om
    predicate = parseOperator(predicate);
    try {
        //dateValue = java.text.DateFormat.getDateTimeInstance().parse(dateString);
        DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        dateValue = formatter.parse(dateString);

    } catch (Exception ex) {
        throw new Exception("Error parsing date " + dateString + ": " + ex.getMessage(), ex);
    }
    String yearPredicate = null;
    String monthPredicate = null;

    if (predicate.equals(">") || predicate.equals(">=")) {
        yearPredicate = ">";
        monthPredicate = ">";
    } else if (predicate.equals("<") || predicate.equals("<=")) {
        yearPredicate = "<";
        monthPredicate = "<";
    }

    StringBuilder dateQuery = new StringBuilder();
    // parse the date value into a Java Date object
    Calendar cal = Calendar.getInstance();
    cal.setTime(dateValue);
    dateQuery.append("(");

    int month = cal.get(Calendar.MONTH) + 1;
    if (!predicate.equals("=")) {
        String yearQuery = "year(" + fullAttributeName + ") " + yearPredicate + " '" + cal.get(Calendar.YEAR)
                + "'";
        String monthQuery = "year(" + fullAttributeName + ") = '" + cal.get(Calendar.YEAR) + "' AND " + "month("
                + fullAttributeName + ") " + monthPredicate + " '" + month + "'";
        String dayQuery = "year(" + fullAttributeName + ") = '" + cal.get(Calendar.YEAR) + "' AND " + "month("
                + fullAttributeName + ") = '" + month + "' AND " + "day(" + fullAttributeName + ") " + predicate
                + " '" + cal.get(Calendar.DAY_OF_MONTH) + "'";
        dateQuery.append(yearQuery).append(" OR (").append(monthQuery).append(") OR (").append(dayQuery)
                .append(")");
    } else {
        dateQuery.append("year(").append(fullAttributeName).append(") = '").append(cal.get(Calendar.YEAR))
                .append("' AND ").append("month(").append(fullAttributeName).append(") = '").append(month)
                .append("' AND ").append("day(").append(fullAttributeName).append(") = '")
                .append(cal.get(Calendar.DAY_OF_MONTH)).append("'");
    }
    dateQuery.append(")");
    return dateQuery.toString();
}

From source file:org.motechproject.mobile.core.dao.hibernate.GatewayRequestDAOImplTest.java

@Before
public void setUp() {
    mDDAO = (GatewayRequestDAO) applicationContext.getBean("gatewayRequestDAO", GatewayRequestDAO.class);

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    try {//from  ww  w  .  j  av a2 s .  c o  m
        dateFrom1 = df.parse("2009-08-21");
        dateFrom2 = df.parse("2009-09-04");
        dateTo1 = df.parse("2009-10-30");
        dateTo2 = df.parse("2009-11-04");
        schedule = df.parse("2009-10-02");
    } catch (ParseException e) {
        e.printStackTrace();
    }

    text = "First";
    md1.setId(1000000001l);
    md1.setMessage(text);
    md1.setRecipientsNumber("123445");
    md1.setDateFrom(new Date());

    md2.setId(10000000002l);
    md2.setMessage("Second");
    md2.setRecipientsNumber("123445");
    md2.setDateFrom(new Date());

    md3.setId(10000000003l);
    md3.setMessage("Third");
    md3.setRecipientsNumber("123445");
    md3.setDateFrom(new Date());

    md4.setId(10000000004l);
    md4.setMessage("Test for dummies 4");
    md4.setRecipientsNumber("123445, 54321");
    md4.setDateFrom(dateFrom1);
    md4.setDateTo(dateTo1);
    md4.setMessageStatus(MStatus.FAILED);

    md5.setId(10000000005l);
    md5.setDateSent(new Date());
    md5.setRecipientsNumber("12345,54321");
    md5.setMessage("insertion with responsedetailsobject");
    md5.setDateFrom(dateFrom2);
    md5.setDateTo(dateTo2);
    md5.setMessageStatus(MStatus.FAILED);

    md6.setId(10000000006l);
    md6.setDateSent(new Date());
    md6.setRecipientsNumber("12345,54321");
    md6.setMessage("another test for dummies");
    md6.setDateFrom(new Date());

    rd1.setId(40000000001l);
    rd1.setMessageStatus(MStatus.PENDING);
    rd1.setRecipientNumber("123445");

    rd2.setId(40000000002l);
    rd2.setMessageStatus(MStatus.FAILED);
    rd2.setRecipientNumber("54321");

    grd4.setId(40000000003l);
    grd4.setMessage("some messaege 4");
    grd4.setMessageType(MessageType.TEXT);
    grd4.setNumberOfPages(1);
    Set<GatewayRequest> gwrs4 = new HashSet<GatewayRequest>();
    gwrs4.add(md4);
    grd4.setGatewayRequests(gwrs4);

    grd5.setId(40000000004l);
    grd5.setMessage("some messaege 5");
    grd5.setMessageType(MessageType.TEXT);
    grd5.setNumberOfPages(1);
    Set<GatewayRequest> gwrs5 = new HashSet<GatewayRequest>();
    gwrs5.add(md4);
    grd5.setGatewayRequests(gwrs5);

    setUpInitialData();
}

From source file:cz.tyr.android.currencyrates.bank.RaiffeisenBank.java

@Override
public int downloadData() {
    if (mCurrency == null) {
        mCurrency = getDefaultCurrencyValue();
    }/*from   w  ww.j a  v a  2  s .com*/

    String dateStr = null;
    String rateStr = null;

    String url = getDataUrl();

    if (DEBUG > 0) {
        Log.d(TAG, "Download data for RB_CZ");
        Log.d(TAG, " * url = : " + url);
        Log.d(TAG, " * currency = " + mCurrency);
        Log.d(TAG, " * exchange = " + mExchangeType);
        Log.d(TAG, " * direction = " + mExchangeDirection);
    }

    HttpClient sClient = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    InputStream stream = null;

    try {
        stream = sClient.execute(request).getEntity().getContent();
    } catch (IOException e) {
        Log.d(TAG, "Problem downloading the XML data.");
        return 1;
    }

    try {
        if (DEBUG > 1)
            Log.d(TAG, " - Factory start");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        Document doc = dbf.newDocumentBuilder().parse(stream);
        if (DEBUG > 1)
            Log.d(TAG, " - Factory end");

        if (doc != null && doc.hasChildNodes()) {
            if (DEBUG > 1)
                Log.d(TAG, " - Parse start");

            // find the root element
            for (int i = 0; i < doc.getChildNodes().getLength(); i++) {
                Node root = doc.getChildNodes().item(i);

                if (root.getNodeType() == Node.ELEMENT_NODE || root.getNodeName().equals("exchange_rates")) {
                    NodeList list = doc.getChildNodes().item(i).getChildNodes();

                    // find first node
                    for (int j = 0; j < list.getLength(); j++) {
                        Node n = list.item(j);

                        // check the attributes of this element
                        if (n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().equals("exchange_rate")) {
                            boolean go = false;

                            if (DEBUG > 1)
                                Log.d(TAG, " # Got EXCHANGE_RATE element!");

                            for (int k = 0; k < n.getAttributes().getLength(); k++) {
                                Node a = n.getAttributes().item(k);

                                if (a.getNodeName().equals("type") && a.getNodeValue().equals(
                                        "XML_RATE_TYPE_EBNK_" + mExchangeDirection + "_" + mExchangeType)) {
                                    if (DEBUG > 1)
                                        Log.d(TAG, " - CORRECT ELEMENT! TAKE THE DATE!");

                                    go = true;
                                } else if (go && a.getNodeName().equals("valid_from")) {
                                    if (DEBUG > 1)
                                        Log.d(TAG, " - GOT DATE! " + a.getNodeValue());

                                    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
                                    Date fdate = (Date) formatter.parse(a.getNodeValue());
                                    formatter = new SimpleDateFormat(
                                            mResources.getString(R.string.date_time_format));

                                    dateStr = formatter.format(fdate);

                                    // stop the loop
                                    break;
                                }
                            }

                            // if it is correct element, go for the rate
                            if (go) {
                                if (DEBUG > 1)
                                    Log.d(TAG, " - Searching for the rate!");

                                NodeList currencies = n.getChildNodes();

                                // check the attributes
                                for (int k = 0; k < currencies.getLength(); k++) {
                                    Node c = currencies.item(k);

                                    if (c.getNodeType() == Node.ELEMENT_NODE
                                            && c.getNodeName().equals("currency")) {
                                        boolean bool = false;
                                        String rateTmp = null;

                                        for (int l = 0; l < c.getAttributes().getLength(); l++) {
                                            Node a = c.getAttributes().item(l);

                                            if (a.getNodeName().equals("name")
                                                    && a.getNodeValue().equals(mCurrency)) {
                                                if (DEBUG > 1)
                                                    Log.d(TAG, " -- Got the Currency!!!");

                                                bool = true;
                                            } else if (a.getNodeName().equals("rate")) {
                                                if (DEBUG > 1)
                                                    Log.d(TAG, " -- Got the RATE!!!" + a.getNodeValue());
                                                rateTmp = a.getNodeValue();
                                            }

                                            if (bool && rateTmp != null) {
                                                rateStr = rateTmp;

                                                if (DEBUG > 1)
                                                    Log.d(TAG, " -- Got the Currency VALUE: " + rateStr);

                                                // stop the loop
                                                break;
                                            }
                                        }
                                    }

                                    // stop the loop
                                    if (rateStr != null) {
                                        break;
                                    }
                                }
                            }
                        }

                        // stop the loop
                        if (rateStr != null) {
                            break;
                        }
                    }
                }

                // stop the loop
                if (rateStr != null) {
                    break;
                }
            }

            if (DEBUG > 1)
                Log.d(TAG, " - Parse end");
        }
    } catch (Exception e) {
        e.printStackTrace();
        return 1;
    }

    // Check the values
    if (dateStr == null || rateStr == null) {
        Log.d(TAG, " # One of the values is null!");
        return 1;
    }

    setCurrencyDate(dateStr);
    setCurrencyRate(Float.parseFloat(rateStr));

    return 0;
}

From source file:com.appeligo.search.actions.account.BaseAccountAction.java

public void setEarliestSmsTime(String earliestSmsTime) {
    DateFormat format = SimpleDateFormat.getTimeInstance(DateFormat.SHORT);
    try {//from w  ww. j a  v  a 2  s.co m
        this.earliestSmsTime = new Time(format.parse(earliestSmsTime).getTime());
    } catch (ParseException e) {
        log.error("Format from account_macros.vm was wrong", e);
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:de.betterform.xml.xforms.ui.AbstractFormControl.java

/**
 * convert a localized value into its XML Schema datatype representation. If the value given cannot be parsed with
 * the locale in betterForm context the default locale (US) will be used as fallback. This can be convenient for
 * user-agents that do not pass a localized value back.
 *
 * @param value the value to convert//from w ww  .  ja v a  2s  .  co  m
 * @return converted value that can be used to update instance data and match the Schema datatype lexical space
 * @throws java.text.ParseException in case the incoming string cannot be converted into a Schema datatype representation
 */
protected String delocaliseValue(String value) throws XFormsException, ParseException {
    if (value == null || value.equals("")) {
        return value;
    }
    if (Config.getInstance().getProperty(XFormsProcessorImpl.BETTERFORM_ENABLE_L10N).equals("true")) {
        Locale locale = (Locale) getModel().getContainer().getProcessor().getContext()
                .get(XFormsProcessorImpl.BETTERFORM_LOCALE);
        XFormsProcessorImpl processor = this.model.getContainer().getProcessor();

        if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":float")
                || processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":decimal")
                || processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":double")) {

            NumberFormat formatter = NumberFormat.getNumberInstance(locale);
            formatter.setMaximumFractionDigits(Double.SIZE);
            BigDecimal number;

            try {
                number = strictParse(value, locale);
            } catch (ParseException e) {
                LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale);
                return value;
            } catch (NumberFormatException nfe) {
                LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale);
                return value;
            } catch (InputMismatchException ime) {
                LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale);
                return value;
            }
            return number.toPlainString();
        } else if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":date")) {
            DateFormat df = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
            Date d = null;
            try {
                d = df.parse(value);
            } catch (ParseException e) {
                //try the default locale - else fail with ParseException
                df = new SimpleDateFormat("yyyy-MM-dd");
                df.setLenient(false);
                d = df.parse(value);
            }
            df = new SimpleDateFormat("yyyy-MM-dd");
            return df.format(d);
        } else if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":dateTime")) {
            String timezone = "";
            // int position = ;
            if (value.contains("GMT")) {
                timezone = value.substring(value.indexOf("GMT") + 3, value.length());
            } else if (value.contains("+")) {
                timezone = value.substring(value.indexOf("+"), value.length());

            } else if (value.contains("Z")) {
                timezone = "Z";
            }

            DateFormat sf = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale);
            Date d = null;
            try {
                d = sf.parse(value);
            } catch (ParseException e) {
                //try the default locale - else fail with ParseException
                sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                d = null;
                d = sf.parse(value);
            }
            sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            String converted = sf.format(d);
            if (!timezone.equals("")) {
                return converted + timezone;
            }
            return converted;
        }
    }
    return value;
}

From source file:de.hero.vertretungsplan.HtmlWork.java

public void extractTable(StringBuffer strHtml) throws IOException {
    SharedPreferences.Editor editor = mySharedPreferences.edit();

    ArrayList<HashMap<String, String>> lstEintraege = new ArrayList<HashMap<String, String>>();

    HashMap<String, String> hmEintrag = new HashMap<String, String>();

    int intIndex = strHtml.indexOf("<table");
    strHtml.delete(0, intIndex - 1);//from  w ww .  ja  v a  2  s .co m
    intIndex = strHtml.indexOf("</table");
    strHtml.delete(intIndex, strHtml.length() - 1);
    DateFormat dfm = new SimpleDateFormat("dd.MM.yyyy");
    DateFormat dfm2 = new SimpleDateFormat("dd.MM.yy");
    Date dat = new Date();
    try {
        dat = dfm.parse(strHtml.substring(strHtml.indexOf(":") + 2));
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //      int date = dat.getDate();
    //      int month = dat.getMonth() + 1;

    //String strAktualisierungsText =  ((date < 10) ? "0" + date : date)  + "." + ((month < 10) ? "0" + month : month) + "." + (dat.getYear() + 1900) + " - " + strHtml.substring(strHtml.indexOf("<td>") + 4,strHtml.indexOf("</td"));
    String datumVertretungsplan = dfm2.format(dat);
    String aOderBWoche = strHtml.substring(strHtml.indexOf("<td>") + 4, strHtml.indexOf("</td"));
    Log.d("HtmlWork", "strAktualisierungsText " + datumVertretungsplan);
    editor.putString(context.getString(R.string.datumVertretungsplan), datumVertretungsplan);
    editor.putString("aOderBWoche", aOderBWoche);
    editor.commit();

    intIndex = strHtml.indexOf("<tr>");
    int intIndex2 = strHtml.indexOf("</tr>");
    strHtml.delete(0, intIndex2 + 4);
    intIndex = strHtml.indexOf("<tr>");
    intIndex2 = strHtml.indexOf("</tr>");

    strHtml.delete(0, intIndex2 + 4);
    intIndex2 = strHtml.indexOf("</tr>");
    strHtml.delete(0, intIndex2 + 4);
    intIndex = strHtml.indexOf("<tr>");
    intIndex2 = strHtml.indexOf("</tr>");
    while (intIndex != -1) {
        StringBuffer strZeile = new StringBuffer(strHtml.substring(intIndex + 4, intIndex2));
        int intIndex4 = strZeile.indexOf("</t");
        strZeile.delete(0, intIndex4 + 5);
        int intIndex3 = strZeile.indexOf("<t");
        intIndex4 = strZeile.indexOf("</t");

        String stunde = strZeile.substring(intIndex3 + 4, intIndex4);
        hmEintrag.put("stunde", stunde + ((stunde.endsWith(".")) ? " Stunde" : ". Stunde"));

        strZeile.delete(intIndex3, intIndex4 + 4);
        intIndex3 = strZeile.indexOf("<t");
        intIndex4 = strZeile.indexOf("</t");
        hmEintrag.put("fach1", strZeile.substring(intIndex3 + 4, intIndex4));

        strZeile.delete(intIndex3, intIndex4 + 4);
        intIndex3 = strZeile.indexOf("<t");
        intIndex4 = strZeile.indexOf("</t");
        hmEintrag.put("vertreter", strZeile.substring(intIndex3 + 4, intIndex4));

        /*strZeile.delete(intIndex3, intIndex4 + 4);
        intIndex3 = strZeile.indexOf("<t");
        intIndex4 = strZeile.indexOf("</t");
        hmEintrag.put("fach2", strZeile.substring(intIndex3 + 4, intIndex4));*/

        strZeile.delete(intIndex3, intIndex4 + 4);
        intIndex3 = strZeile.indexOf("<t");
        intIndex4 = strZeile.indexOf("</t");
        hmEintrag.put("klassen", strZeile.substring(intIndex3 + 4, intIndex4));

        strZeile.delete(intIndex3, intIndex4 + 4);
        intIndex3 = strZeile.indexOf("<t");
        intIndex4 = strZeile.indexOf("</t");
        hmEintrag.put("raum", strZeile.substring(intIndex3 + 4, intIndex4));

        strZeile.delete(intIndex3, intIndex4 + 4);
        intIndex3 = strZeile.indexOf("<t");
        intIndex4 = strZeile.indexOf("</t");

        String strTemp = strZeile.substring(intIndex3 + 4, intIndex4);

        strZeile.delete(intIndex3, intIndex4 + 4);
        intIndex3 = strZeile.indexOf("<t");
        intIndex4 = strZeile.indexOf("</t");

        hmEintrag.put("text", strTemp + " " + strZeile.substring(intIndex3 + 4, intIndex4));

        lstEintraege.add(hmEintrag);

        hmEintrag = new HashMap<String, String>();

        strHtml.delete(0, intIndex2 + 2);
        intIndex = strHtml.indexOf("<tr>");
        intIndex2 = strHtml.indexOf("</tr>");
    }
    FileOutputStream fos = context.openFileOutput(context.getString(R.string.filename), Context.MODE_PRIVATE);
    ObjectOutputStream oos = new ObjectOutputStream(fos);

    int oldHash = mySharedPreferences.getInt(context.getString(R.string.v_plan_hash_value), 0);

    oos.writeObject(lstEintraege);
    oos.close();
    fos.close();
    int newHash = lstEintraege.hashCode();
    editor.putInt(context.getString(R.string.v_plan_hash_value), newHash);
    editor.commit();

    Log.d("HtmlWork", "oldHash: " + oldHash + "; newHash: " + newHash);
    if (oldHash != newHash) {
        onDataChange();
    }
}

From source file:org.androidpn.server.console.controller.OnlineStatusController.java

public ModelAndView getChart(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String username = request.getParameter("username");
    User user = null;/*w w w  . j  av a 2 s  .c o m*/
    try {
        user = userService.getUserByUsername(username);
    } catch (UserNotFoundException e) {
        e.printStackTrace();
        //         return ;
    }

    String startTimeStr = request.getParameter("start");
    String endTimeStr = request.getParameter("end");
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date endTime = endTimeStr == null ? new Date() : format.parse(endTimeStr);
    Date startTime = startTimeStr == null ? new Date() : format.parse(startTimeStr);

    List<OnlineRecord> list = this.getOnlineList(user, startTime, endTime);

    //   System.out.println(format.format(startTime)+"-"+format.format(endTime)+": find" + list.size());

    ModelAndView mav = new ModelAndView();
    mav.addObject("list", list);
    mav.setViewName("online/chart");
    return mav;
}

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

@SuppressWarnings("unused")
@Test//  ww w  .ja  va2 s.c o  m
public void testGetRelatedDiSCOS() {

    try {
        //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);
        requestAgent.setAgentKeyId(new java.net.URI("rmap:testkey"));
        ORMapEvent event = discomgr.createDiSCO(disco, requestAgent, triplestore);

        //get related discos
        IRI iri = ORAdapter.getValueFactory().createIRI("http://dx.doi.org/10.1109/ACCESS.2014.2332453");

        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");

        RMapSearchParams params = new RMapSearchParams();
        params.setDateRange(dateFrom, dateTo);
        params.setSystemAgents(sysAgents);

        Set<IRI> discoIris = resourcemgr.getResourceRelatedDiSCOS(iri, params, triplestore);

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

        Iterator<IRI> iter = discoIris.iterator();
        IRI matchingIri = iter.next();
        assertTrue(matchingIri.toString().equals(disco.getId().toString()));

        params.setStatusCode(RMapStatusFilter.ACTIVE);

        discomgr.updateDiSCO(matchingIri, null, requestAgent, true, triplestore);
        discoIris = resourcemgr.getResourceRelatedDiSCOS(iri, params, triplestore);
        assertTrue(discoIris.size() == 0);

        params.setStatusCode(RMapStatusFilter.INACTIVE);
        discoIris = resourcemgr.getResourceRelatedDiSCOS(iri, params, triplestore);
        assertTrue(discoIris.size() == 1);
        rmapService.deleteDiSCO(disco.getId().getIri(), requestAgent);

    } catch (Exception e) {
        e.printStackTrace();
        fail();
    } finally {
        rmapService.closeConnection();
    }
}

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

@Test
public void testGetRelatedEvents() {

    try {//from   ww  w  .ja  v a  2s.com
        //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);

        ORMapDiSCO disco2 = new ORMapDiSCO(stmts);

        requestAgent.setAgentKeyId(new java.net.URI("rmap:testkey"));
        ORMapEvent event = discomgr.createDiSCO(disco, requestAgent, triplestore);

        //get related events
        RMapIri eventId = event.getId();
        IRI discoId = ORAdapter.rMapIri2OpenRdfIri(disco.getId());
        RMapEvent updateEvent = discomgr.updateDiSCO(discoId, disco2, requestAgent, false, triplestore);
        IRI updateEventId = ORAdapter.rMapIri2OpenRdfIri(updateEvent.getId());

        IRI iri = ORAdapter.getValueFactory().createIRI("http://dx.doi.org/10.1109/ACCESS.2014.2332453");
        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");

        RMapSearchParams params = new RMapSearchParams();
        params.setDateRange(dateFrom, dateTo);
        params.setStatusCode(RMapStatusFilter.ALL);

        Set<IRI> eventIris = resourcemgr.getResourceRelatedEvents(iri, params, triplestore);

        assertTrue(eventIris.size() == 2);

        Set<String> sEventIris = new HashSet<String>();
        for (IRI eventIri : eventIris) {
            sEventIris.add(eventIri.toString());
        }

        assertTrue(sEventIris.contains(eventId.toString()));
        assertTrue(sEventIris.contains(updateEventId.toString()));
        rmapService.deleteDiSCO(disco.getId().getIri(), requestAgent);
        rmapService.deleteDiSCO(disco2.getId().getIri(), requestAgent);

    } catch (Exception e) {
        e.printStackTrace();
        fail();
    } finally {
        rmapService.closeConnection();
    }
}