Example usage for java.util GregorianCalendar getTime

List of usage examples for java.util GregorianCalendar getTime

Introduction

In this page you can find the example usage for java.util GregorianCalendar getTime.

Prototype

public final Date getTime() 

Source Link

Document

Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").

Usage

From source file:com.aerospike.examples.timeseries.TimeSeriesManipulator.java

public void run() throws ParseException, FileNotFoundException, IOException, InterruptedException {
    GregorianCalendar cal = new GregorianCalendar();
    //String formattedDate = new String();
    String[] tokens;//from   w ww  . j  av a 2  s.  c o  m
    String[] ticker;
    if (tickerList != null) {
        ticker = timeParser.parse(tickerList);
    } else {
        ticker = new String[0];
    }
    long token;
    if (this.operation.contains("L")) {
        System.out.println("****************************************");
        System.out.println("Loading Data");
        System.out.println("****************************************");
        if (this.days != null) {
            if (ticker != null) {
                for (int i = 0; i < ticker.length; i++) {
                    this.sum = 0;
                    try (BufferedReader br = getStocks(this.days, ticker[i])) {
                        String line;
                        while ((line = br.readLine()) != null) {
                            if (line.startsWith("a")) {
                                this.sum = 0;
                                tokens = timeParser.parse(line);
                                token = new Long(tokens[0].substring(1)).longValue() * 1000L;
                                cal.setTimeInMillis(token);
                                //formattedDate = dateOp.dateFormatter(cal.getTime());
                                this.updateTimeSeries(ticker[i], cal.getTime(), line);
                                Date insertDate = dateOp.getDate(cal.getTime());
                                this.dateList.add(insertDate.getTime());
                            } else if ((!line.startsWith("EXCHANGE")) && (!line.startsWith("MARKET"))
                                    && (!line.startsWith("INTERVAL")) && (!line.startsWith("COLUMNS"))
                                    && (!line.startsWith("DATA")) && (!line.startsWith("TIMEZONE"))) {
                                this.updateTimeSeries(ticker[i], cal.getTime(), line);

                            }
                        }
                    }
                }
            }
        } else {
            try (BufferedReader br = new BufferedReader(new FileReader("stocktick.txt"))) {
                String line;
                while ((line = br.readLine()) != null) {
                    if (line.startsWith("a")) {
                        tokens = timeParser.parse(line);
                        token = new Long(tokens[0].substring(1)).longValue() * 1000L;
                        cal.setTimeInMillis(token);
                        //formattedDate = dateOp.dateFormatter(cal.getTime());
                        Date insertDate = dateOp.getDate(cal.getTime());
                        this.updateTimeSeries(ticker[0], cal.getTime(), line);
                        this.dateList.add(insertDate.getTime());
                    } else if ((!line.startsWith("EXCHANGE")) && (!line.startsWith("MARKET"))
                            && (!line.startsWith("INTERVAL")) && (!line.startsWith("COLUMNS"))
                            && (!line.startsWith("DATA")) && (!line.startsWith("TIMEZONE"))) {
                        if (ticker != null)
                            this.updateTimeSeries(ticker[0], cal.getTime(), line);

                    }
                }
            }
        }
        System.out.println("****************************************");
        System.out.println("Loading Complete");
        System.out.println("****************************************");
    }
    Calendar startCal = Calendar.getInstance();
    Calendar endCal = Calendar.getInstance();
    int count = 0;
    if (this.operation.contains("R")) {
        //if (this.startString.equals(null) && this.endString.equals(null)) {
        if (this.operation.contains("L")) {
            count++;
            this.retrieveResult(ticker, this.dateList);
        } else {
            count++;

            int[] startList = timeParser.getCalDate(this.startString);
            if (startList[0] > 0 && startList[1] > 0 && startList[2] > 0) {
                startCal = new GregorianCalendar(startList[2], startList[1] - 1, startList[0]);
            } else {
                System.out.println("Invalid Start Date Format. Specify as dd/MM/yyyy");
                System.exit(0);
            }
            int[] endList = timeParser.getCalDate(this.endString);
            if (endList[0] > 0 && endList[1] > 0 && endList[2] > 0) {
                endCal = new GregorianCalendar(endList[2], endList[1] - 1, endList[0]);
            } else {
                System.out.println("Invalid End Date Format. Specify as dd/MM/yyyy");
                System.exit(0);
            }
            if (!endCal.before(startCal))
                this.retrieveResult(ticker, startCal.getTime(), endCal.getTime());
            else
                System.out.println("Invalid Dates. Start Date is greater than End Date");
        }

    }
    if (this.operation.contains("R") && count == 0)
        System.out.println("Invalid Operation. Use L or R");

}

From source file:com.collabnet.ccf.teamforge.TFWriter.java

/**
 * Creates the artifact represented by the GenericArtifact object on the
 * target TF system/*from  w ww . jav a  2  s  . c  om*/
 * 
 * @param ga
 * @param tracker
 * @param forceOverride
 * @param connection
 * @return - returns the updated artifact's ArtifactSoapDO object
 */
private ArtifactDO updateArtifact(GenericArtifact ga, String tracker, Connection connection) {
    String id = ga.getTargetArtifactId();
    ArrayList<String> flexFieldNames = new ArrayList<String>();
    ArrayList<String> flexFieldTypes = new ArrayList<String>();
    ArrayList<Object> flexFieldValues = new ArrayList<Object>();
    Set<String> overriddenFlexFields = new HashSet<String>();
    List<GenericArtifactField> gaFields = ga
            .getAllGenericArtifactFieldsWithSameFieldType(GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
    String targetSystemTimezone = ga.getTargetSystemTimezone();
    if (gaFields != null) {
        for (GenericArtifactField gaField : gaFields) {
            String fieldName = gaField.getFieldName();
            if (COMMENT_TEXT.equals(fieldName)) {
                continue;
            }
            if (gaField.getFieldValueHasChanged()) {
                overriddenFlexFields.add(fieldName);
            } else {
                continue;
            }
            String trackerFieldValueType = TFArtifactMetaData
                    .getTFFieldValueTypeForGAFieldType(gaField.getFieldValueType());
            flexFieldNames.add(fieldName);
            flexFieldTypes.add(trackerFieldValueType);
            Object value = null;
            FieldValueTypeValue fieldType = gaField.getFieldValueType();
            if (trackerFieldValueType.equals(TrackerFieldSoapDO.FIELD_VALUE_TYPE_DATE)) {
                if (fieldType == FieldValueTypeValue.DATE) {
                    GregorianCalendar gc = (GregorianCalendar) gaField.getFieldValue();
                    if (gc != null) {
                        Date dateValue = gc.getTime();
                        if (DateUtil.isAbsoluteDateInTimezone(dateValue, "GMT")) {
                            value = DateUtil.convertGMTToTimezoneAbsoluteDate(dateValue, targetSystemTimezone);
                        } else {
                            value = dateValue;
                        }
                    }
                } else if (fieldType == FieldValueTypeValue.DATETIME) {
                    value = gaField.getFieldValue();
                }
            } else {
                value = gaField.getFieldValue();
            }
            flexFieldValues.add(value);
        }
    }

    GenericArtifactField folderId = GenericArtifactHelper
            .getMandatoryGAField(TFArtifactMetaData.TFFields.folderId.getFieldName(), ga);
    GenericArtifactField description = GenericArtifactHelper
            .getMandatoryGAField(TFArtifactMetaData.TFFields.description.getFieldName(), ga);
    GenericArtifactField category = GenericArtifactHelper
            .getMandatoryGAField(TFArtifactMetaData.TFFields.category.getFieldName(), ga);
    GenericArtifactField group = GenericArtifactHelper
            .getMandatoryGAField(TFArtifactMetaData.TFFields.group.getFieldName(), ga);
    GenericArtifactField status = GenericArtifactHelper
            .getMandatoryGAField(TFArtifactMetaData.TFFields.status.getFieldName(), ga);
    GenericArtifactField statusClass = GenericArtifactHelper
            .getMandatoryGAField(TFArtifactMetaData.TFFields.statusClass.getFieldName(), ga);
    GenericArtifactField customer = GenericArtifactHelper
            .getMandatoryGAField(TFArtifactMetaData.TFFields.customer.getFieldName(), ga);
    GenericArtifactField priority = GenericArtifactHelper
            .getMandatoryGAField(TFArtifactMetaData.TFFields.priority.getFieldName(), ga);

    GenericArtifactField estimatedEffort = null;
    GenericArtifactField actualEffort = null;
    GenericArtifactField remainingEffort = null;
    GenericArtifactField planningFolder = null;
    GenericArtifactField autosumming = null;

    estimatedEffort = GenericArtifactHelper
            .getMandatoryGAField(TFArtifactMetaData.TFFields.estimatedHours.getFieldName(), ga);
    actualEffort = GenericArtifactHelper
            .getMandatoryGAField(TFArtifactMetaData.TFFields.actualHours.getFieldName(), ga);

    if (connection.supports53()) {
        remainingEffort = GenericArtifactHelper
                .getMandatoryGAField(TFArtifactMetaData.TFFields.remainingEffort.getFieldName(), ga);
        planningFolder = GenericArtifactHelper
                .getMandatoryGAField(TFArtifactMetaData.TFFields.planningFolder.getFieldName(), ga);
        autosumming = GenericArtifactHelper
                .getMandatoryGAField(TFArtifactMetaData.TFFields.autosumming.getFieldName(), ga);
    }

    GenericArtifactField storyPoints = null;
    if (connection.supports54()) {
        storyPoints = GenericArtifactHelper
                .getMandatoryGAField(TFArtifactMetaData.TFFields.points.getFieldName(), ga);
    }

    GenericArtifactField closeDate = GenericArtifactHelper
            .getMandatoryGAField(TFArtifactMetaData.TFFields.closeDate.getFieldName(), ga);
    GenericArtifactField assignedTo = GenericArtifactHelper
            .getMandatoryGAField(TFArtifactMetaData.TFFields.assignedTo.getFieldName(), ga);
    GenericArtifactField reportedReleaseId = GenericArtifactHelper
            .getMandatoryGAField(TFArtifactMetaData.TFFields.reportedReleaseId.getFieldName(), ga);
    GenericArtifactField resolvedReleaseId = GenericArtifactHelper
            .getMandatoryGAField(TFArtifactMetaData.TFFields.resolvedReleaseId.getFieldName(), ga);
    GenericArtifactField title = GenericArtifactHelper
            .getMandatoryGAField(TFArtifactMetaData.TFFields.title.getFieldName(), ga);

    String[] comments = this.getComments(ga);
    ArtifactDO result = null;
    try {
        // now we have to deal with the parent dependencies
        String newParentId = ga.getDepParentTargetArtifactId();
        boolean associateWithParent = false;
        boolean deleteOldParentAssociation = false;
        String currentParentId = null;

        if (newParentId != null && !newParentId.equals(GenericArtifact.VALUE_UNKNOWN)) {
            // now find out current parent id
            ArtifactDependencyRow[] parents = trackerHandler.getArtifactParentDependencies(connection, id);
            if (parents.length != 0) {
                // only take first entry of this record
                ArtifactDependencyRow parent = parents[0];
                currentParentId = parent.getOriginId();
            }

            if (newParentId.equals(GenericArtifact.VALUE_NONE)) {
                // we have to set the planning folder to null
                planningFolder = TFToGenericArtifactConverter.createGenericArtifactField(
                        TFArtifactMetaData.TFFields.planningFolder, null, ga, null, false);

                // we have to deassociate the old parent
                if (currentParentId != null) {
                    deleteOldParentAssociation = true;
                }
            }

            else if (newParentId.startsWith("plan")) {
                // we have to set the planning folder to the new parent
                planningFolder = TFToGenericArtifactConverter.createGenericArtifactField(
                        TFArtifactMetaData.TFFields.planningFolder, newParentId, ga, null, false);

                // we have to deassociate the old parent
                if (currentParentId != null) {
                    deleteOldParentAssociation = true;
                }
            }

            else if (!newParentId.equals(currentParentId)) {
                // new parent is a tracker item
                // we have to deassociate the old parent
                if (currentParentId != null) {
                    deleteOldParentAssociation = true;
                }
                associateWithParent = true;
                // we have to change the planning folder if there was no
                // special value requested for this
                if (connection.supports53()
                        && (planningFolder == null || !planningFolder.getFieldValueHasChanged())) {
                    ArtifactDO parentArtifact = trackerHandler.getTrackerItem(connection, newParentId);
                    planningFolder = TFToGenericArtifactConverter.createGenericArtifactField(
                            TFArtifactMetaData.TFFields.planningFolder, parentArtifact.getPlanningFolderId(),
                            ga, null, false);
                }
            }
        }

        result = trackerHandler.updateArtifact(ga, connection, folderId, description, category, group, status,
                statusClass, customer, priority, estimatedEffort, actualEffort, closeDate, assignedTo,
                reportedReleaseId, resolvedReleaseId, flexFieldNames, flexFieldValues, flexFieldTypes,
                overriddenFlexFields, title, id, comments, translateTechnicalReleaseIds, remainingEffort,
                autosumming, storyPoints, planningFolder, deleteOldParentAssociation, currentParentId,
                associateWithParent, newParentId,
                isReleaseIdFieldsContainFileReleasePackageName() ? getPackageReleaseSeparatorString() : null);

        if (result != null) {
            log.info("Artifact " + id + " is updated successfully");
        }
    } catch (RemoteException e) {
        String cause = "While trying to update an artifact within TF, an error occured";
        log.error(cause, e);
        ga.setErrorCode(GenericArtifact.ERROR_EXTERNAL_SYSTEM_WRITE);
        throw new CCFRuntimeException(cause, e);
    } catch (PlanningFolderRuleViolationException e) {
        String cause = "While trying to update an artifact within TF, a planning folder rule violation occured: "
                + e.getMessage();
        log.error(cause, e);
        ga.setErrorCode(GenericArtifact.ERROR_EXTERNAL_SYSTEM_WRITE);
        throw new CCFRuntimeException(cause, e);
    }
    return result;
}

From source file:net.darkmist.clf.LogParser.java

private Date parseDate(String[] parts) throws LogFormatException {
    /*//from w ww  . jav a2s . c  o  m
    dateStr = matcher.group(4);
    try
    {
       return dateFormat.parse(dateStr);
    }
    catch(ParseException e)
    {
       throw new LogFormatException("Unable to parse date: " + dateStr, e);
    }
    */
    int year;
    int mon;
    int day;
    int hour;
    int min;
    int sec;
    TimeZone tz;
    GregorianCalendar cal;
    String dateStr;
    Date ret;

    dateStr = parts[PART_TIME];
    /*
    if((ret = dateCache.get(dateStr))!=null)
       return ret;
    */
    if (lastDateStr != null && dateStr.equals(lastDateStr) && lastDate != null)
        return lastDate;
    if (cachedDateMatcher == null)
        cachedDateMatcher = PATTERN_DATE.matcher(dateStr);
    else
        cachedDateMatcher.reset(dateStr);
    if (!cachedDateMatcher.matches())
        throw new LogFormatException("Time stamp " + dateStr + " does not match regex.");
    day = parse2DigitInt(cachedDateMatcher.group(1));
    mon = parseMonth(cachedDateMatcher.group(2));
    year = parse4DigitInt(cachedDateMatcher.group(3));
    hour = parse2DigitInt(cachedDateMatcher.group(4));
    min = parse2DigitInt(cachedDateMatcher.group(5));
    sec = parse2DigitInt(cachedDateMatcher.group(6));
    tz = parseTimeZone(cachedDateMatcher.group(7));

    /*
    year = parse4DigitInt(parts[PART_YEAR]);
    mon = parseMonth(parts[PART_MON]);
    day = parse2DigitInt(parts[PART_DAY]);
    hour = parse2DigitInt(parts[PART_HOUR]);
    min = parse2DigitInt(parts[PART_MIN]);
    sec = parse2DigitInt(parts[PART_SEC]);
    tz = parseTimeZone(parts[PART_TZ]);
    */

    // build
    cal = new GregorianCalendar(year, mon, day, hour, min, sec);
    cal.setTimeZone(tz);
    ret = cal.getTime();
    //dateCache.put(dateStr, ret);
    lastDateStr = dateStr;
    lastDate = ret;
    return ret;
}

From source file:org.sakaiproject.sdata.tool.JCRHandler.java

/**
 * Perform a mime multipart upload into the JCR repository based on a location specified
 * by the rp parameter. The parts of the multipart upload are relative to the current
 * request path/*from  w  w w  . j  av  a2 s.  c o m*/
 *
 * @param request
 *          the request object of the current request.
 * @param response
 *          the response object of the current request
 * @param rp
 *          the resource definition for the current request
 * @throws ServletException
 * @throws IOException
 */
private void doMumtipartUpload(HttpServletRequest request, HttpServletResponse response, ResourceDefinition rp)
        throws ServletException, IOException {
    try {
        try {
            Node n = jcrNodeFactory.createFolder(rp.getRepositoryPath());
            if (n == null) {
                response.reset();
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Unable to uplaod to location " + rp.getRepositoryPath());
                return;
            }
        } catch (Exception ex) {
            sendError(request, response, ex);
            snoopRequest(request);
            LOG.error("Failed  TO service Request ", ex);
            return;
        }

        // Check that we have a file upload request

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();
        List<String> errors = new ArrayList<String>();

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(request);
        Map<String, Object> responseMap = new HashMap<String, Object>();
        Map<String, Object> uploads = new HashMap<String, Object>();
        Map<String, List<String>> values = new HashMap<String, List<String>>();
        int uploadNumber = 0;
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            LOG.debug("Got Upload through Uploads");
            String name = item.getName();
            String fieldName = item.getFieldName();
            LOG.info("    Name is " + name + " field Name " + fieldName);
            for (String headerName : item.getHeaderNames()) {
                LOG.info("Header " + headerName + " is " + item.getHeader(headerName));
            }
            InputStream stream = item.openStream();
            if (!item.isFormField()) {
                try {
                    if (name != null && name.trim().length() > 0) {

                        List<String> realNames = values.get(REAL_UPLOAD_NAME);
                        String finalName = name;
                        if (realNames != null && realNames.size() > uploadNumber) {
                            finalName = realNames.get(uploadNumber);
                        }

                        String path = rp.convertToAbsoluteRepositoryPath(finalName);
                        // pooled uploads never overwrite.
                        List<String> pooled = values.get(POOLED);
                        if (pooled != null && pooled.size() > 0 && "1".equals(pooled.get(0))) {
                            path = rp.convertToAbsoluteRepositoryPath(PathUtils.getPoolPrefix(finalName));
                            int i = 0;
                            String basePath = path;
                            try {
                                while (true) {
                                    Node n = jcrNodeFactory.getNode(path);
                                    if (n == null) {
                                        break;
                                    }
                                    int lastStop = basePath.lastIndexOf('.');
                                    path = basePath.substring(0, lastStop) + "_" + i
                                            + basePath.substring(lastStop);
                                    i++;
                                }
                            } catch (JCRNodeFactoryServiceException ex) {
                                // the path does not exist which is good.
                            }
                        }

                        String mimeType = ContentTypes.getContentType(finalName, item.getContentType());
                        Node target = jcrNodeFactory.createFile(path, mimeType);
                        GregorianCalendar lastModified = new GregorianCalendar();
                        lastModified.setTime(new Date());
                        long size = saveStream(target, stream, mimeType, "UTF-8", lastModified);
                        Map<String, Object> uploadMap = new HashMap<String, Object>();
                        if (size > Integer.MAX_VALUE) {
                            uploadMap.put("contentLength", String.valueOf(size));
                        } else {
                            uploadMap.put("contentLength", (int) size);
                        }
                        uploadMap.put("name", finalName);
                        uploadMap.put("url", rp.convertToExternalPath(path));
                        uploadMap.put("mimeType", mimeType);
                        uploadMap.put("lastModified", lastModified.getTime());
                        uploadMap.put("status", "ok");

                        uploads.put(fieldName, uploadMap);
                    }
                } catch (Exception ex) {
                    LOG.error("Failed to Upload Content", ex);
                    Map<String, Object> uploadMap = new HashMap<String, Object>();
                    uploadMap.put("mimeType", "text/plain");
                    uploadMap.put("encoding", "UTF-8");
                    uploadMap.put("contentLength", -1);
                    uploadMap.put("lastModified", 0);
                    uploadMap.put("status", "Failed");
                    uploadMap.put("cause", ex.getMessage());
                    List<String> stackTrace = new ArrayList<String>();
                    for (StackTraceElement ste : ex.getStackTrace()) {
                        stackTrace.add(ste.toString());
                    }
                    uploadMap.put("stacktrace", stackTrace);
                    uploads.put(fieldName, uploadMap);
                    uploadMap = null;

                }

            } else {
                String value = Streams.asString(stream);
                List<String> valueList = values.get(name);
                if (valueList == null) {
                    valueList = new ArrayList<String>();
                    values.put(name, valueList);

                }
                valueList.add(value);
            }
        }

        responseMap.put("success", true);
        responseMap.put("errors", errors.toArray(new String[1]));
        responseMap.put("uploads", uploads);
        sendMap(request, response, responseMap);
        LOG.info("Response Complete Saved to " + rp.getRepositoryPath());
    } catch (Throwable ex) {
        LOG.error("Failed  TO service Request ", ex);
        sendError(request, response, ex);
        return;
    }
}

From source file:org.eclipse.uomo.util.impl.Iso8601Date.java

/**
 * get the date specified as a Date.// w w  w. j a  va 2  s.  co  m
 * 
 * @param timezone
 *            - REQUIRED, IF_PRESENT or IGNORE
 * @throws OHFException
 */
public Date getAsDate(int timezone) throws UOMoException {
    GregorianCalendar cal = new GregorianCalendar();
    cal.clear();
    if (year != -1)
        cal.set(Calendar.YEAR, year);
    if (month != -1)
        cal.set(Calendar.MONTH, month - 1); // Calendar month start with 0
    if (day != -1)
        cal.set(Calendar.DAY_OF_MONTH, day);
    if (hour != -1)
        cal.set(Calendar.HOUR_OF_DAY, hour);
    if (minute != -1)
        cal.set(Calendar.MINUTE, minute);
    if (second != -1)
        cal.set(Calendar.SECOND, second);
    if (milli != -1)
        cal.set(Calendar.MILLISECOND, milli);

    if (timezone == REQUIRED || timezone == IF_PRESENT || timezone == OPTIONAL) {
        if (timezone == REQUIRED && tzNegative == null)
            throw new UOMoException(Messages.Iso8601Date_TZ_NOT_DEFINED);
        if (tzNegative != null) {
            TimeZone tzMsg = TimeZone.getTimeZone(Messages.Iso8601Date_GMT + prepTimezone());
            cal.setTimeZone(tzMsg);
        }
    }
    return cal.getTime();
}

From source file:org.motechproject.mobile.omp.manager.intellivr.IntellIVRBeanTest.java

private Date addToDate(Date start, int field, int amount) {

    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(start);/*from   www . jav a 2  s. co  m*/
    cal.add(field, amount);
    return cal.getTime();

}

From source file:org.apache.unomi.persistence.elasticsearch.ElasticSearchPersistenceServiceImpl.java

public void start() throws Exception {

    loadPredefinedMappings(bundleContext, false);

    // on startup
    new InClassLoaderExecute<Object>() {
        public Object execute(Object... args) throws Exception {
            logger.info("Connecting to ElasticSearch persistence backend using cluster name " + clusterName
                    + " and index name " + indexName + "...");

            bulkProcessorName = System.getProperty(BULK_PROCESSOR_NAME, bulkProcessorName);
            bulkProcessorConcurrentRequests = System.getProperty(BULK_PROCESSOR_CONCURRENT_REQUESTS,
                    bulkProcessorConcurrentRequests);
            bulkProcessorBulkActions = System.getProperty(BULK_PROCESSOR_BULK_ACTIONS,
                    bulkProcessorBulkActions);
            bulkProcessorBulkSize = System.getProperty(BULK_PROCESSOR_BULK_SIZE, bulkProcessorBulkSize);
            bulkProcessorFlushInterval = System.getProperty(BULK_PROCESSOR_FLUSH_INTERVAL,
                    bulkProcessorFlushInterval);
            bulkProcessorBackoffPolicy = System.getProperty(BULK_PROCESSOR_BACKOFF_POLICY,
                    bulkProcessorBackoffPolicy);

            Settings transportSettings = Settings.builder().put(CLUSTER_NAME, clusterName).build();
            client = new PreBuiltTransportClient(transportSettings);
            for (String elasticSearchAddress : elasticSearchAddressList) {
                String[] elasticSearchAddressParts = elasticSearchAddress.split(":");
                String elasticSearchHostName = elasticSearchAddressParts[0];
                int elasticSearchPort = Integer.parseInt(elasticSearchAddressParts[1]);
                try {
                    client.addTransportAddress(new InetSocketTransportAddress(
                            InetAddress.getByName(elasticSearchHostName), elasticSearchPort));
                } catch (UnknownHostException e) {
                    String message = "Error resolving address " + elasticSearchAddress
                            + " ElasticSearch transport client not connected";
                    throw new Exception(message, e);
                }// w w  w.  j  a  va  2s.co m
            }

            // let's now check the versions of all the nodes in the cluster, to make sure they are as expected.
            try {
                NodesInfoResponse nodesInfoResponse = client.admin().cluster().prepareNodesInfo().all()
                        .execute().get();

                org.elasticsearch.Version minimalVersion = org.elasticsearch.Version
                        .fromString(minimalElasticSearchVersion);
                org.elasticsearch.Version maximalVersion = org.elasticsearch.Version
                        .fromString(maximalElasticSearchVersion);
                for (NodeInfo nodeInfo : nodesInfoResponse.getNodes()) {
                    org.elasticsearch.Version version = nodeInfo.getVersion();
                    if (version.before(minimalVersion) || version.equals(maximalVersion)
                            || version.after(maximalVersion)) {
                        throw new Exception(
                                "ElasticSearch version on node " + nodeInfo.getHostname() + " is not within ["
                                        + minimalVersion + "," + maximalVersion + "), aborting startup !");
                    }
                }
            } catch (InterruptedException e) {
                throw new Exception("Error checking ElasticSearch versions", e);
            } catch (ExecutionException e) {
                throw new Exception("Error checking ElasticSearch versions", e);
            }

            // @todo is there a better way to detect index existence than to wait for it to startup ?
            boolean indexExists = false;
            int tries = 0;

            while (!indexExists && tries < 20) {

                IndicesExistsResponse indicesExistsResponse = client.admin().indices().prepareExists(indexName)
                        .execute().actionGet();
                indexExists = indicesExistsResponse.isExists();
                tries++;
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    logger.error("Interrupted", e);
                }
            }
            if (!indexExists) {
                logger.info("{} index doesn't exist yet, creating it...", indexName);
                Map<String, String> indexMappings = new HashMap<String, String>();
                indexMappings.put("_default_", mappings.get("_default_"));
                for (Map.Entry<String, String> entry : mappings.entrySet()) {
                    if (!itemsMonthlyIndexed.contains(entry.getKey())
                            && !indexNames.containsKey(entry.getKey())) {
                        indexMappings.put(entry.getKey(), entry.getValue());
                    }
                }

                internalCreateIndex(indexName, indexMappings);
            } else {
                logger.info("Found index {}, ElasticSearch started successfully.", indexName);
                for (Map.Entry<String, String> entry : mappings.entrySet()) {
                    createMapping(entry.getKey(), entry.getValue());
                }
            }

            client.admin().indices().preparePutTemplate(indexName + "_monthlyindex")
                    .setTemplate(indexName + "-*").setOrder(1)
                    .setSettings(Settings.builder()
                            .put(NUMBER_OF_SHARDS, Integer.parseInt(monthlyIndexNumberOfShards))
                            .put(NUMBER_OF_REPLICAS, Integer.parseInt(monthlyIndexNumberOfReplicas)).build())
                    .execute().actionGet();

            getMonthlyIndex(new Date(), true);

            if (client != null && bulkProcessor == null) {
                bulkProcessor = getBulkProcessor();
            }

            refreshExistingIndexNames();

            logger.info("Waiting for GREEN cluster status...");

            client.admin().cluster().prepareHealth().setWaitForGreenStatus().get();

            logger.info("Cluster status is GREEN");

            return true;
        }
    }.executeInClassLoader();

    bundleContext.addBundleListener(this);

    timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            GregorianCalendar gc = new GregorianCalendar();
            int thisMonth = gc.get(Calendar.MONTH);
            gc.add(Calendar.DAY_OF_MONTH, 1);
            if (gc.get(Calendar.MONTH) != thisMonth) {
                String monthlyIndex = getMonthlyIndex(gc.getTime(), true);
                existingIndexNames.add(monthlyIndex);
            }
        }
    }, 10000L, 24L * 60L * 60L * 1000L);

    // load predefined mappings and condition dispatchers of any bundles that were started before this one.
    for (Bundle existingBundle : bundleContext.getBundles()) {
        if (existingBundle.getBundleContext() != null) {
            loadPredefinedMappings(existingBundle.getBundleContext(), true);
        }
    }

    logger.info(this.getClass().getName() + " service started successfully.");
}

From source file:edu.stanford.muse.util.Util.java

public static List<Date> getYearlyIntervals(Date start, Date end) {
    List<Date> intervals = new ArrayList<Date>();
    GregorianCalendar c = new GregorianCalendar();
    c.setTime(start);/*from  w w w .jav a 2s .c o  m*/
    int startYear = c.get(Calendar.YEAR);
    int year = startYear;

    intervals.add(start);
    while (true) {
        year++;
        c = new GregorianCalendar(year, 0, 1, 0, 0, 0);
        intervals.add(c.getTime());
        if (c.getTime().after(end))
            break;
    }
    return intervals;
}

From source file:org.socraticgrid.docmgr.DocumentManagerImpl.java

/**
 * Store document.// ww w . ja v a 2 s .c  o m
 * 
 * Perform the actual store.  A unique Id is inserted if one hasn't already
 * been created.
 *
 * Before we do, we ensure a valid repository Id is in the request.  This will tell the
 * repository to store the request appropriately.  Unfortunately, this
 * isn't how a real XDS Registry behaves.  So when/if we use one, there will
 * need to be a rework done here.
 *
 * @param body
 * @return
 */
public oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType documentManagerStoreDocument(
        ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType body) {
    log.debug("Storing document.");

    oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType result = null;

    try { // Call Web Service Operation

        //Insert doc unique id if one does not exist
        if (!createDocumentUniqueId(body)) {
            throw new Exception("Failed to create document unique Id");
        }

        //Ensure valid repository id in query
        String repositoryId = pullRepositoryId(body);
        if (!getValidRepositories().contains(repositoryId)) {
            throw new Exception("Repository id not valid: " + repositoryId);
        }

        //Send to mirth if destination is Inbound Repository
        String inboundRepositoryId = PropertyAccessor.getProperty(REPOSITORY_PROPERTY_FILE,
                INBOUND_DOCUMENT_REPOSITORY_ID_PROP);
        if (repositoryId.equals(inboundRepositoryId)) {
            try {
                String mirthWSDL = PropertyAccessor.getProperty(REPOSITORY_PROPERTY_FILE,
                        INBOUND_DOCUMENT_MIRTH_WSDL);
                if ((mirthWSDL != null) && !mirthWSDL.isEmpty()) {
                    String msgBody = null;
                    if ((body.getDocument() != null) && (body.getDocument().size() > 0)) {
                        msgBody = new String(body.getDocument().get(0).getValue());
                    }

                    if (msgBody == null) {
                        throw new Exception("Message body not found in request.");
                    }

                    MirthMessage msg = new MirthMessage();
                    msg.setWsdl(mirthWSDL);
                    msg.setBody(msgBody);

                    String msgResult[] = startBackgroundJob(msg);

                    if (msgResult[0].equals(JOB_FAILURE_ID)) {
                        throw new Exception(msgResult[1]);
                    } else {
                        log.debug("Passed document for mirth handling, ticket: " + msgResult[0]);
                    }
                }
            } catch (Exception e) {
                log.error("Error sending inbound document to Mirth channel", e);
                //continue to store locally
            }
        }

        try {
            //Add store date
            for (JAXBElement<? extends IdentifiableType> object : body.getSubmitObjectsRequest()
                    .getRegistryObjectList().getIdentifiable()) {
                IdentifiableType identifiableType = object.getValue();
                if (identifiableType instanceof ExtrinsicObjectType) {
                    ExtrinsicObjectType extrinsic = (ExtrinsicObjectType) identifiableType;
                    boolean found = false;
                    for (SlotType1 slot : extrinsic.getSlot()) {
                        if (XDS_KMR_STOREDATE.equals(slot.getName())) {
                            found = true;
                        }
                    }

                    if (!found) {
                        GregorianCalendar cal = new GregorianCalendar();
                        addSlot(extrinsic, XDS_KMR_STOREDATE,
                                new String[] { formatXDSDate(cal.getTime(), XDS_DATE_QUERY_TO_PRECISION) });
                    }
                }
            }
        } catch (Exception e) {
            log.error("Unable to add document metadata: " + XDS_KMR_STOREDATE, e);
        }

        result = new DocumentRepositoryHelper().documentRepositoryProvideAndRegisterDocumentSet(body);
    } catch (Exception e) {
        result = new oasis.names.tc.ebxml_regrep.xsd.rs._3.ObjectFactory().createRegistryResponseType();
        result.setStatus(XDS_FAILED_STATUS);
        RegistryErrorList errorList = new oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryErrorList();
        RegistryError error = new oasis.names.tc.ebxml_regrep.xsd.rs._3.ObjectFactory().createRegistryError();
        error.setValue(e.getMessage());
        error.setErrorCode(XDS_ERROR_CODE);
        error.setSeverity(XDS_ERROR_SEVERITY);
        error.setCodeContext("Could not store document.");
        error.setLocation("DocumentManagerImpl.storeDocument");
        errorList.getRegistryError().add(error);
        result.setRegistryErrorList(errorList);

        log.error("Error storing document.", e);
    }

    return result;
}

From source file:edu.stanford.muse.util.Util.java

public static List<Date> getMonthlyIntervals(Date start, Date end) {
    List<Date> intervals = new ArrayList<Date>();
    GregorianCalendar c = new GregorianCalendar();
    c.setTime(start);//from  www . j av  a2  s.  com
    int startMonth = c.get(Calendar.MONTH);
    int year = c.get(Calendar.YEAR);
    int month = startMonth;

    intervals.add(start);
    while (true) {
        month++;
        if (month == 12) {
            month = 0;
            year++;
        }

        c = new GregorianCalendar(year, month, 1, 0, 0, 0);
        intervals.add(c.getTime());
        if (c.getTime().after(end))
            break;
    }
    return intervals;
}