Example usage for java.time LocalDateTime parse

List of usage examples for java.time LocalDateTime parse

Introduction

In this page you can find the example usage for java.time LocalDateTime parse.

Prototype

public static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter) 

Source Link

Document

Obtains an instance of LocalDateTime from a text string using a specific formatter.

Usage

From source file:net.owl_black.vmgparser.VmgParser.java

private VmgBodyExtended vmg_body_extended() {
    VmgProperty vP = null;//from w ww.j ava  2 s  .  c  om

    VmgBodyExtended vBe = new VmgBodyExtended();
    List<VmgProperty> properties = vBe.getvProp();
    QuotedPrintableCodec decoder = new QuotedPrintableCodec();

    while ((vP = vmg_property(true)) != null) {

        if ((vP.params != null) && (vP.params.quoted_printable)) {
            //Process quoted printable:
            try {
                vP.value = decoder.decode(vP.value);
            } catch (DecoderException e) {
                // TODO Auto-generated catch block
                log.warning("Impossible to decode the property containing quoted printable text.");
            }
        }

        if (vP.name.equalsIgnoreCase("TEXT")) //Retrieve text from the VMG
        {
            vBe.setContent(vP.value);
        } else if (vP.name.equalsIgnoreCase("DATE")) //Retrieve date from the VMG.
        {
            boolean date_parse_suceed = false;
            for (DateTimeFormatter dtf : date_patterns) {
                try {
                    LocalDateTime lDate = LocalDateTime.parse(vP.value, dtf);
                    vBe.setDate(lDate);
                    date_parse_suceed = true;
                    break;
                } catch (DateTimeParseException e) {
                }
            }

            if (!date_parse_suceed) {
                log.warning("Can't parse date.");
            }

        }

        properties.add(vP);
        //System.out.println(vP.toString());
    }

    return vBe;
}

From source file:io.stallion.dataAccess.file.TextFilePersister.java

protected void setProperty(TextItem item, String key, Object value) {
    if (key.equals("slug")) {
        item.setSlug(value.toString());//from  www  .  java 2 s  .  c  o m
    } else if (key.equals("title")) {
        item.setTitle(value.toString());
    } else if (key.equals("publishDate")) {
        for (DateTimeFormatter formatter : localDateFormats) {
            if (item.getSlug().equals("/future-dated")) {
                Log.info("future");
            }
            try {
                LocalDateTime dt = LocalDateTime.parse(value.toString(), formatter);
                ZoneId zoneId = ZoneId.systemDefault();
                if (Context.getSettings() != null && Context.getSettings().getTimeZoneId() != null) {
                    zoneId = Context.getSettings().getTimeZoneId();
                }
                item.setPublishDate(ZonedDateTime.of(dt, zoneId));
                return;
            } catch (DateTimeParseException e) {

            }
        }
        for (DateTimeFormatter formatter : zonedDateFormats) {
            try {
                ZonedDateTime dt = ZonedDateTime.parse(value.toString(), formatter);
                item.setPublishDate(dt);
                return;
            } catch (DateTimeParseException e) {

            }
        }

    } else if (key.equals("draft")) {
        item.setDraft(value.equals("true"));
    } else if (key.equals("template")) {
        item.setTemplate(value.toString());
    } else if (key.equals("author")) {
        item.setAuthor(value.toString());
    } else if (key.equals("tags")) {
        if (value instanceof List) {
            item.setTags((List<String>) value);
        } else {
            ArrayList<String> tags = new ArrayList<String>();
            for (String tag : value.toString().split("(;|,)")) {
                tags.add(tag.trim());
            }
            item.setTags(tags);

        }
    } else if (key.equals("contentType")) {
        item.setContentType(value.toString());
    } else {
        item.put(key, value);
    }

}

From source file:org.codelibs.fess.service.SearchLogService.java

public void importCsv(final Reader reader) {
    final CsvReader csvReader = new CsvReader(reader, new CsvConfig());
    final DateTimeFormatter formatter = DateTimeFormatter
            .ofPattern(CoreLibConstants.DATE_FORMAT_ISO_8601_EXTEND);
    try {//from  w  w w . j  a  v a  2 s . c om
        List<String> list;
        csvReader.readValues(); // ignore header
        while ((list = csvReader.readValues()) != null) {
            try {
                final SearchLog entity = new SearchLog();
                entity.setSearchWord(list.get(0));
                entity.setSearchQuery(list.get(1));
                entity.setSolrQuery(list.get(2));
                entity.setRequestedTime(LocalDateTime.parse(list.get(3), formatter));
                entity.setResponseTime(Integer.parseInt(list.get(4)));
                entity.setHitCount(Long.parseLong(list.get(5)));
                entity.setQueryOffset(Integer.parseInt(list.get(6)));
                entity.setQueryPageSize(Integer.parseInt(list.get(7)));
                entity.setUserAgent(list.get(8));
                entity.setReferer(list.get(9));
                entity.setClientIp(list.get(10));
                entity.setUserSessionId(list.get(11));
                entity.setAccessTypeAsAccessType(AccessType.valueOf(list.get(12)));
                if (list.size() >= 14) {
                    final String jsonStr = list.get(13);
                    @SuppressWarnings("rawtypes")
                    final List objList = JSON.decode(jsonStr);
                    for (final Object obj : objList) {
                        @SuppressWarnings("rawtypes")
                        final Map objMap = (Map) obj;
                        entity.addSearchFieldLogValue((String) objMap.get(Constants.ITEM_NAME),
                                (String) objMap.get(Constants.ITEM_VALUE));
                    }
                }
                searchLogBhv.insert(entity);
            } catch (final Exception e) {
                log.warn("Failed to read a search log: " + list, e);
            }
        }
    } catch (final IOException e) {
        log.warn("Failed to read a search log.", e);
    }
}

From source file:org.onosproject.drivers.ciena.waveserver.rest.CienaRestDevice.java

private long parseAlarmTime(String time) {
    /*/*from   w  w  w. j  av  a2s. c  o m*/
     * expecting WaveServer time to be set to UTC.
     */
    try {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT);
        LocalDateTime localDateTime = LocalDateTime.parse(time, formatter);
        return localDateTime.atZone(ZoneId.of(UTC)).toInstant().toEpochMilli();
    } catch (DateTimeParseException e2) {
        log.error("unable to parse time {}, using system time", time);
        return System.currentTimeMillis();
    }
}

From source file:de.steilerdev.myVerein.server.controller.admin.EventManagementController.java

/**
 * This function saves an event. The function is invoked by POSTint the parameters to the URI /api/admin/event.
 * @param eventFlag This flag either stores the ID of the event, or true, if a new event is created.
 * @param eventName The name of the event.
 * @param eventDescription The description of the event.
 * @param startDate The start date, formatted according to the pattern d/MM/y, defined within the Java 8 DateTimeFormatter.
 * @param startTime The start time, formatted according to the pattern H:m, defined within the Java 8 DateTimeFormatter.
 * @param endDate The end date, formatted according to the pattern d/MM/y, defined within the Java 8 DateTimeFormatter.
 * @param endTime The end time, formatted according to the pattern H:m, defined within the Java 8 DateTimeFormatter.
 * @param location The name of the location of the event.
 * @param locationLat The latitude of the location of the event.
 * @param locationLng The longitude of the location of the event.
 * @param invitedDivisions A comma separated list of invited divisions.
 * @param currentUser The currently logged in user.
 * @return An HTTP response with a status code together with a JSON map object, containing an 'errorMessage', or a 'successMessage' respectively. If the operation was successful the id of the event is accessible via 'eventID'.
 */// w w w .ja  v a  2s .  co  m
@RequestMapping(method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<Map<String, String>> saveEvent(@RequestParam String eventFlag,
        @RequestParam String eventName, @RequestParam String eventDescription, @RequestParam String startDate,
        @RequestParam String startTime, @RequestParam String endDate, @RequestParam String endTime,
        @RequestParam String location, @RequestParam String locationLat, @RequestParam String locationLng,
        @RequestParam String invitedDivisions, @CurrentUser User currentUser) {
    logger.trace("[" + currentUser + "] Saving event");
    Map<String, String> responseMap = new HashMap<>();
    Event event;
    if (eventFlag.isEmpty()) {
        logger.warn("[" + currentUser + "] The event flag is empty");
        responseMap.put("errorMessage", "The event flag is not allowed to be empty");
        return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST);
    } else if (eventFlag.equals("true")) {
        logger.debug("[" + currentUser + "] A new event is created");
        event = new Event();
    } else {
        logger.debug("[" + currentUser + "] The event with id " + eventFlag + " is altered");
        event = eventRepository.findEventById(eventFlag);
        if (event == null) {
            logger.warn("[" + currentUser + "] Unable to find the specified event with id " + eventFlag);
            responseMap.put("errorMessage", "Unable to find the specified event");
            return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST);
        } else if (!currentUser.isAllowedToAdministrate(event)) {
            logger.warn(
                    "[" + currentUser + "] The user is not allowed to alter the selected event " + eventFlag);
            responseMap.put("errorMessage", "You are not allowed to edit the selected event");
            return new ResponseEntity<>(responseMap, HttpStatus.FORBIDDEN);
        }
    }

    event.setName(eventName);
    event.setDescription(eventDescription);

    if (startDate.isEmpty() || startTime.isEmpty() || endDate.isEmpty() || endTime.isEmpty()) {
        logger.warn("[" + currentUser + "] The date and times defining the event (ID " + eventFlag
                + ") are not allowed to be empty.");
        responseMap.put("errorMessage", "The date and times defining the event are not allowed to be empty");
        return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST);
    } else {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/y'T'H:m");
        try {
            event.setStartDateTime(LocalDateTime.parse(startDate + "T" + startTime, formatter));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format " + startDate + "T" + startTime);
            responseMap.put("errorMessage", "Unrecognized date or time format within start time");
            return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST);
        }

        try {
            event.setEndDateTime(LocalDateTime.parse(endDate + "T" + endTime, formatter));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format " + endDate + "T" + endTime);
            responseMap.put("errorMessage", "Unrecognized date or time format within end time");
            return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST);
        }
    }

    event.setLocation(location);

    if (!locationLat.isEmpty()) {
        try {
            event.setLocationLat(Double.parseDouble(locationLat));
        } catch (NumberFormatException e) {
            logger.warn("[" + currentUser + "] Unable to paste lat " + locationLat);
            responseMap.put("errorMessage", "Unable to parse latitude coordinate");
            return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST);
        }
    }

    if (!locationLng.isEmpty()) {
        try {
            event.setLocationLng(Double.parseDouble(locationLng));
        } catch (NumberFormatException e) {
            logger.warn("[" + currentUser + "] Unable to paste lng " + locationLng);
            responseMap.put("errorMessage", "Unable to parse longitude coordinate");
            return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST);
        }
    }

    if (!invitedDivisions.isEmpty()) {
        String[] divArray = invitedDivisions.split(",");
        for (String division : divArray) {
            Division div = divisionRepository.findByName(division);
            if (div == null) {
                logger.warn("[" + currentUser + "] Unrecognized division (" + division + ")");
                responseMap.put("errorMessage", "Division " + division + " does not exist");
                return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST);
            }
            event.addDivision(div);
        }
        event.updateInvitedUser(divisionRepository);
    } else if (event.getInvitedDivision() != null && !event.getInvitedDivision().isEmpty()) {
        event.updateInvitedUser(divisionRepository);
    }

    //Updating several fields.
    event.setEventAdmin(currentUser);
    event.setLastChanged(LocalDateTime.now());
    event.updateMultiDate();
    try {
        eventRepository.save(event);
        logger.info("[" + currentUser + "] Successfully saved event " + eventFlag);
        responseMap.put("successMessage", "Successfully saved the event");
        responseMap.put("eventID", event.getId());
        return new ResponseEntity<>(responseMap, HttpStatus.OK);
    } catch (ConstraintViolationException e) {
        logger.warn(
                "[" + currentUser + "] A database constraint was violated while saving the event " + eventFlag);
        responseMap.put("errorMessage", "A database constraint was violated while saving the event");
        return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST);
    }
}

From source file:com.thinkbiganalytics.nifi.v2.ingest.GetTableData.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = null;//  w w  w. ja  v  a 2  s  .  c  o m
    if (context.hasIncomingConnection()) {
        flowFile = session.get();

        // If we have no FlowFile, and all incoming connections are self-loops then we can continue on.
        // However, if we have no FlowFile and we have connections coming from other Processors, then
        // we know that we should run only if we have a FlowFile.
        if (flowFile == null && context.hasNonLoopConnection()) {
            return;
        }
    }

    final FlowFile incoming = flowFile;
    final ComponentLog logger = getLog();

    final DBCPService dbcpService = context.getProperty(JDBC_SERVICE).asControllerService(DBCPService.class);
    final MetadataProviderService metadataService = context.getProperty(METADATA_SERVICE)
            .asControllerService(MetadataProviderService.class);
    final String loadStrategy = context.getProperty(LOAD_STRATEGY).getValue();
    final String categoryName = context.getProperty(FEED_CATEGORY).evaluateAttributeExpressions(incoming)
            .getValue();
    final String feedName = context.getProperty(FEED_NAME).evaluateAttributeExpressions(incoming).getValue();
    final String tableName = context.getProperty(TABLE_NAME).evaluateAttributeExpressions(incoming).getValue();
    final String fieldSpecs = context.getProperty(TABLE_SPECS).evaluateAttributeExpressions(incoming)
            .getValue();
    final String dateField = context.getProperty(DATE_FIELD).evaluateAttributeExpressions(incoming).getValue();
    final Integer queryTimeout = context.getProperty(QUERY_TIMEOUT).asTimePeriod(TimeUnit.SECONDS).intValue();
    final Integer overlapTime = context.getProperty(OVERLAP_TIME).evaluateAttributeExpressions(incoming)
            .asTimePeriod(TimeUnit.SECONDS).intValue();
    final Integer backoffTime = context.getProperty(BACKOFF_PERIOD).asTimePeriod(TimeUnit.SECONDS).intValue();
    final String unitSize = context.getProperty(UNIT_SIZE).getValue();
    final String outputType = context.getProperty(OUTPUT_TYPE).getValue();
    String outputDelimiter = context.getProperty(OUTPUT_DELIMITER).evaluateAttributeExpressions(incoming)
            .getValue();
    final String delimiter = StringUtils.isBlank(outputDelimiter) ? "," : outputDelimiter;

    final PropertyValue waterMarkPropName = context.getProperty(HIGH_WATER_MARK_PROP)
            .evaluateAttributeExpressions(incoming);

    final String[] selectFields = parseFields(fieldSpecs);

    final LoadStrategy strategy = LoadStrategy.valueOf(loadStrategy);
    final StopWatch stopWatch = new StopWatch(true);

    try (final Connection conn = dbcpService.getConnection()) {

        FlowFile outgoing = (incoming == null ? session.create() : incoming);
        final AtomicLong nrOfRows = new AtomicLong(0L);
        final LastFieldVisitor visitor = new LastFieldVisitor(dateField, null);
        final FlowFile current = outgoing;

        outgoing = session.write(outgoing, new OutputStreamCallback() {
            @Override
            public void process(final OutputStream out) throws IOException {
                ResultSet rs = null;
                try {
                    GetTableDataSupport support = new GetTableDataSupport(conn, queryTimeout);
                    if (strategy == LoadStrategy.FULL_LOAD) {
                        rs = support.selectFullLoad(tableName, selectFields);
                    } else if (strategy == LoadStrategy.INCREMENTAL) {
                        String waterMarkValue = getIncrementalWaterMarkValue(current, waterMarkPropName);
                        LocalDateTime waterMarkTime = LocalDateTime.parse(waterMarkValue, DATE_TIME_FORMAT);
                        Date lastLoadDate = toDate(waterMarkTime);
                        visitor.setLastModifyDate(lastLoadDate);
                        rs = support.selectIncremental(tableName, selectFields, dateField, overlapTime,
                                lastLoadDate, backoffTime, GetTableDataSupport.UnitSizes.valueOf(unitSize));
                    } else {
                        throw new RuntimeException("Unsupported loadStrategy [" + loadStrategy + "]");
                    }

                    if (GetTableDataSupport.OutputType.DELIMITED
                            .equals(GetTableDataSupport.OutputType.valueOf(outputType))) {
                        nrOfRows.set(JdbcCommon.convertToDelimitedStream(rs, out,
                                (strategy == LoadStrategy.INCREMENTAL ? visitor : null), delimiter));
                    } else if (GetTableDataSupport.OutputType.AVRO
                            .equals(GetTableDataSupport.OutputType.valueOf(outputType))) {
                        avroSchema = JdbcCommon.createSchema(rs);
                        nrOfRows.set(JdbcCommon.convertToAvroStream(rs, out,
                                (strategy == LoadStrategy.INCREMENTAL ? visitor : null), avroSchema));
                    } else {
                        throw new RuntimeException("Unsupported output format type [" + outputType + "]");
                    }
                } catch (final SQLException e) {
                    throw new IOException("SQL execution failure", e);
                } finally {
                    if (rs != null) {
                        try {
                            if (rs.getStatement() != null) {
                                rs.getStatement().close();
                            }
                            rs.close();
                        } catch (SQLException e) {
                            getLog().error("Error closing sql statement and resultset");
                        }
                    }
                }
            }
        });

        // set attribute how many rows were selected
        outgoing = session.putAttribute(outgoing, RESULT_ROW_COUNT, Long.toString(nrOfRows.get()));

        //set output format type and avro schema for feed setup, if available
        outgoing = session.putAttribute(outgoing, "db.table.output.format", outputType);
        String avroSchemaForFeedSetup = (avroSchema != null) ? JdbcCommon.getAvroSchemaForFeedSetup(avroSchema)
                : EMPTY_STRING;
        outgoing = session.putAttribute(outgoing, "db.table.avro.schema", avroSchemaForFeedSetup);

        session.getProvenanceReporter().modifyContent(outgoing, "Retrieved " + nrOfRows.get() + " rows",
                stopWatch.getElapsed(TimeUnit.MILLISECONDS));

        // Terminate flow file if no work
        Long rowcount = nrOfRows.get();
        outgoing = session.putAttribute(outgoing, ComponentAttributes.NUM_SOURCE_RECORDS.key(),
                String.valueOf(rowcount));

        if (nrOfRows.get() == 0L) {
            logger.info("{} contains no data; transferring to 'nodata'", new Object[] { outgoing });
            session.transfer(outgoing, REL_NO_DATA);
        } else {

            logger.info("{} contains {} records; transferring to 'success'",
                    new Object[] { outgoing, nrOfRows.get() });

            if (strategy == LoadStrategy.INCREMENTAL) {
                String newWaterMarkStr = format(visitor.getLastModifyDate());
                outgoing = setIncrementalWaterMarkValue(session, outgoing, waterMarkPropName, newWaterMarkStr);

                logger.info("Recorded load status feed {} date {}", new Object[] { feedName, newWaterMarkStr });
            }
            session.transfer(outgoing, REL_SUCCESS);
        }
    } catch (final Exception e) {
        if (incoming == null) {
            logger.error(
                    "Unable to execute SQL select from table due to {}. No incoming flow file to route to failure",
                    new Object[] { e });
        } else {
            logger.error("Unable to execute SQL select from table due to {}; routing to failure",
                    new Object[] { incoming, e });
            session.transfer(incoming, REL_FAILURE);
        }
    }
}

From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java

/**
 * Gets a List of ElectionHeaders from the Bulletin Board and returns it. Fetched list depends on the given ElectionFilterTyp
 * @param filter//from   w w w .  ja  va  2 s. c  o m
 * The filter can be set to All, Open or Closed
 * @return returns a list of election headers
 */
public List<ElectionHeader> getElectionHeaders(ElectionFilterTyp filter) {
    List<ElectionHeader> electionHeaderlist = new ArrayList<ElectionHeader>();

    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime actualDateTime = LocalDateTime.now();
    String dateTimeString = actualDateTime.format(format);

    URL url = null;
    //depending on the filter a different request is sent to the bulletin board
    switch (filter) {
    // if the filter is set to ALL, all the electionheaders on the bulletin board are requested
    case ALL: {
        try {
            url = new URL(bulletinBoardUrl + "/elections");
        } catch (MalformedURLException ex) {
            Logger.getLogger(CommunicationController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
        break;

    // if the filter is set to OPEN only ElectionHeaders where the VotingPeriod is still going are requested from the bulletin board
    case OPEN: {
        try {
            url = new URL(bulletinBoardUrl + "/elections/open?date="
                    + URLEncoder.encode(dateTimeString, "UTF-8").replace("+", "%20"));
        } catch (UnsupportedEncodingException | MalformedURLException ex) {
            System.err.println(ex);
        }
    }
        break;
    // if the filter is set to CLOSED only ElectionHeaders where the VotingPeriod is already over are requested from the bulletin board
    case CLOSED: {
        try {
            url = new URL(bulletinBoardUrl + "/elections/closed?date="
                    + URLEncoder.encode(dateTimeString, "UTF-8").replace("+", "%20"));
        } catch (UnsupportedEncodingException | MalformedURLException ex) {
            System.err.println(ex);
        }
    }
        break;
    }

    try {

        InputStream urlInputStream = url.openStream();
        JsonReader jsonReader = Json.createReader(urlInputStream);
        JsonArray obj = jsonReader.readArray();
        //Recieved Json String is transformed into a list of ElectionHeader objects
        for (JsonObject result : obj.getValuesAs(JsonObject.class)) {

            int id = Integer.parseInt(result.getString("id"));
            String title = result.getString("electionTitle");
            LocalDateTime beginDate = LocalDateTime.parse(result.getString("beginDate"), format);
            LocalDateTime endDate = LocalDateTime.parse(result.getString("endDate"), format);

            ElectionHeader electionHeader = new ElectionHeader(id, title, beginDate, endDate);
            electionHeaderlist.add(electionHeader);
        }
    } catch (IOException x) {
        System.err.println(x);
    }

    return electionHeaderlist;
}

From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java

/**
 * Gets the information for the given ElectionID from the bulletin board and returns it as a election object
 * @param electionId/*from  w ww . j ava 2  s.co m*/
 * the identifier (id) for the desired election
 * @return returns tje election object for a given id
 */
public Election getElectionById(int electionId) {
    Election election = null;
    try {

        URL url = new URL(bulletinBoardUrl + "/elections/" + electionId);

        InputStream urlInputStream = url.openStream();
        JsonReader jsonReader = Json.createReader(urlInputStream);
        JsonObject obj = jsonReader.readObject();
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Parameters parameters = this.getParameters();

        //gets the json string and transforms it into a election object

        //translates the header information of the election
        String title = obj.getString("electionTitle");
        LocalDateTime beginDate = LocalDateTime.parse(obj.getString("beginDate"), format);
        LocalDateTime endDate = LocalDateTime.parse(obj.getString("endDate"), format);
        String appVersion = obj.getString("appVersion");
        String coefficientsString = obj.getString("coefficients");
        String h_HatString = obj.getString("electionGenerator");
        List<Voter> voterlist = new ArrayList<Voter>();

        //get th list of voters
        for (JsonObject result : obj.getJsonArray("voters").getValuesAs(JsonObject.class)) {

            String voterEmail = result.getString("email");
            String voterPublicCredential = result.getString("publicCredential");
            String voterAppVersion = result.getString("appVersion");

            Voter voter = new Voter(voterEmail, voterPublicCredential, voterAppVersion);
            voterlist.add(voter);
        }
        //get the votingTopic
        JsonObject electionTopicObj = obj.getJsonObject("votingTopic");

        String topic = electionTopicObj.getString("topic");
        int pick = electionTopicObj.getInt("pick");

        ElectionTopic electionTopic = new ElectionTopic(topic, pick);
        JsonArray optionsArray = electionTopicObj.getJsonArray("options");
        for (int i = 0; i < optionsArray.size(); i++) {
            electionTopic.addOption(optionsArray.getString(i));
        }

        election = new Election(electionId, title, voterlist, parameters, beginDate, endDate, electionTopic,
                appVersion, h_HatString, coefficientsString);

    } catch (IOException x) {
        System.err.println(x);
    }
    return election;
}

From source file:org.codelibs.fess.service.SearchLogService.java

private void buildSearchCondition(final SearchLogPager searchLogPager, final SearchLogCB cb1,
        final ClickLogCB cb2) {
    if (StringUtil.isNotBlank(searchLogPager.searchWord)) {
        cb1.query().setSearchWord_LikeSearch(searchLogPager.searchWord, op -> op.likeContain());
        if (cb2 != null) {
            cb2.query().querySearchLog().setSearchWord_LikeSearch(searchLogPager.searchWord,
                    op -> op.likeContain());
        }// w w  w  . j a v a2  s .c o m
    }

    if (StringUtil.isNotBlank(searchLogPager.userCode)) {
        cb1.setupSelect_UserInfo();
        cb1.query().queryUserInfo().setCode_Equal(searchLogPager.userCode);
    }

    if (StringUtil.isNotBlank(searchLogPager.startDate)) {
        final StringBuilder buf = new StringBuilder(20);
        buf.append(searchLogPager.startDate);
        buf.append('+');
        if (StringUtil.isNotBlank(searchLogPager.startHour)) {
            buf.append(searchLogPager.startHour);
        } else {
            buf.append("00");
        }
        buf.append(':');
        if (StringUtil.isNotBlank(searchLogPager.startMin)) {
            buf.append(searchLogPager.startMin);
        } else {
            buf.append("00");
        }

        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd+HH:mm");
        try {
            final LocalDateTime startDate = LocalDateTime.parse(buf.toString(), formatter);
            cb1.query().setRequestedTime_GreaterEqual(startDate);
            if (cb2 != null) {
                cb2.query().querySearchLog().setRequestedTime_GreaterEqual(startDate);
            }
        } catch (final DateTimeParseException e) {
            searchLogPager.startDate = null;
            searchLogPager.startHour = null;
            searchLogPager.startMin = null;
        }
    }

    if (StringUtil.isNotBlank(searchLogPager.endDate)) {
        final StringBuilder buf = new StringBuilder(20);
        buf.append(searchLogPager.endDate);
        buf.append('+');
        if (StringUtil.isNotBlank(searchLogPager.endHour)) {
            buf.append(searchLogPager.endHour);
        } else {
            buf.append("00");
        }
        buf.append(':');
        if (StringUtil.isNotBlank(searchLogPager.endMin)) {
            buf.append(searchLogPager.endMin);
        } else {
            buf.append("00");
        }

        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd+HH:mm");
        try {
            final LocalDateTime endDate = LocalDateTime.parse(buf.toString(), formatter);
            cb1.query().setRequestedTime_LessThan(endDate);
            if (cb2 != null) {
                cb2.query().querySearchLog().setRequestedTime_LessThan(endDate);
            }
        } catch (final DateTimeParseException e) {
            searchLogPager.endDate = null;
            searchLogPager.endHour = null;
            searchLogPager.endMin = null;
        }
    }

    if (StringUtil.isNotBlank(searchLogPager.startPage)) {
        cb1.query().setQueryOffset_Equal(0);
        if (cb2 != null) {
            cb2.query().querySearchLog().setQueryOffset_Equal(0);
        }
    }
}

From source file:org.talend.dataprep.transformation.actions.date.ComputeTimeSinceTest.java

/**
 * Compute time since ./*w ww. j a  v  a 2 s.  co m*/
 *
 * @param date      the date to compute from.
 * @param pattern   the pattern to use.
 * @param unit      the unit for the result.
 * @param sinceWhen the date to calculate since when
 * @return time since now in the wanted unit.
 */
String computeTimeSince(String date, String pattern, ChronoUnit unit, String sinceWhen) {

    DateTimeFormatter format = DateTimeFormatter.ofPattern(pattern);
    Temporal since;
    if (sinceWhen == null) {
        since = LocalDateTime.now();
    } else {
        since = LocalDateTime.parse(sinceWhen, format);
    }

    LocalDateTime start;
    try {
        start = LocalDateTime.parse(date, format);
    } catch (Exception e) {
        start = null;
    }

    if (start == null) {
        LocalDate temp = LocalDate.parse(date, format);
        start = temp.atStartOfDay();
    }

    Temporal result = LocalDateTime.from(start);
    return String.valueOf(unit.between(result, since));
}