Example usage for java.util HashMap clear

List of usage examples for java.util HashMap clear

Introduction

In this page you can find the example usage for java.util HashMap clear.

Prototype

public void clear() 

Source Link

Document

Removes all of the mappings from this map.

Usage

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncInterceptor.java

/**
 * Serializes and packages an intercepted change in object state.
 * <p>//from www  .  j a  va2  s  .c  o m
 * IMPORTANT serialization notes:
 * <p>
 * Transient Properties. Transients are not serialized/journalled. Marking an object property as
 * transient is the supported way of designating it as something not to be recorded into the
 * journal.
 * <p/>
 * Hibernate Identity property. A property designated in Hibernate as identity (i.e. primary
 * key) *is* not serialized. This is because sync does not enforce global uniqueness of database
 * primary keys. Instead, custom uuid property is used. This allows us to continue to use native
 * types for 'traditional' entity relationships.
 *
 * @param entity The object changed.
 * @param currentState Array containing data for each field in the object as they will be saved.
 * @param propertyNames Array containing name for each field in the object, corresponding to
 *            currentState.
 * @param types Array containing Type of the field in the object, corresponding to currentState.
 * @param state SyncItemState, e.g. NEW, UPDATED, DELETED
 * @param id Value of the identifier for this entity
 */
protected void packageObject(OpenmrsObject entity, Object[] currentState, String[] propertyNames, Type[] types,
        Serializable id, SyncItemState state) throws SyncException {

    String objectUuid = null;
    String originalRecordUuid = null;
    Set<String> transientProps = null;
    String infoMsg = null;

    ClassMetadata data = null;
    String idPropertyName = null;
    org.hibernate.tuple.IdentifierProperty idPropertyObj = null;

    // The container of values to be serialized:
    // Holds tuples of <property-name> -> {<property-type-name>,
    // <property-value as string>}
    HashMap<String, PropertyClassValue> values = new HashMap<String, PropertyClassValue>();

    try {
        objectUuid = entity.getUuid();

        // pull-out sync-network wide change id for the sync *record* (not the entity itself),
        // if one was already assigned (i.e. this change is coming from some other server)
        originalRecordUuid = getSyncRecord().getOriginalUuid();

        if (log.isDebugEnabled()) {
            // build up a starting msg for all logging:
            StringBuilder sb = new StringBuilder();
            sb.append("In PackageObject, entity type:");
            sb.append(entity.getClass().getName());
            sb.append(", entity uuid:");
            sb.append(objectUuid);
            sb.append(", originalUuid uuid:");
            sb.append(originalRecordUuid);
            log.debug(sb.toString());
        }

        // Transient properties are not serialized.
        transientProps = new HashSet<String>();
        for (Field f : entity.getClass().getDeclaredFields()) {
            if (Modifier.isTransient(f.getModifiers())) {
                transientProps.add(f.getName());
                if (log.isDebugEnabled())
                    log.debug("The field " + f.getName() + " is transient - so we won't serialize it");
            }
        }

        /*
         * Retrieve metadata for this type; we need to determine what is the
         * PK field for this type. We need to know this since PK values are
         * *not* journalled; values of primary keys are assigned where
         * physical DB records are created. This is so to avoid issues with
         * id collisions.
         *
         * In case of <generator class="assigned" />, the Identifier
         * property is already assigned value and needs to be journalled.
         * Also, the prop will *not* be part of currentState,thus we need to
         * pull it out with reflection/metadata.
         */
        data = getSessionFactory().getClassMetadata(entity.getClass());
        if (data.hasIdentifierProperty()) {
            idPropertyName = data.getIdentifierPropertyName();
            idPropertyObj = ((org.hibernate.persister.entity.AbstractEntityPersister) data).getEntityMetamodel()
                    .getIdentifierProperty();

            if (id != null && idPropertyObj.getIdentifierGenerator() != null
                    && (idPropertyObj.getIdentifierGenerator() instanceof org.hibernate.id.Assigned
                    //   || idPropertyObj.getIdentifierGenerator() instanceof org.openmrs.api.db.hibernate.NativeIfNotAssignedIdentityGenerator
                    )) {
                // serialize value as string
                values.put(idPropertyName, new PropertyClassValue(id.getClass().getName(), id.toString()));
            }
        } else if (data.getIdentifierType() instanceof EmbeddedComponentType) {
            // if we have a component identifier type (like AlertRecipient),
            // make
            // sure we include those properties
            EmbeddedComponentType type = (EmbeddedComponentType) data.getIdentifierType();
            for (int i = 0; i < type.getPropertyNames().length; i++) {
                String propertyName = type.getPropertyNames()[i];
                Object propertyValue = type.getPropertyValue(entity, i, org.hibernate.EntityMode.POJO);
                addProperty(values, entity, type.getSubtypes()[i], propertyName, propertyValue, infoMsg);
            }
        }

        /*
         * Loop through all the properties/values and put in a hash for
         * duplicate removal
         */
        for (int i = 0; i < types.length; i++) {
            String typeName = types[i].getName();
            if (log.isDebugEnabled())
                log.debug("Processing, type: " + typeName + " Field: " + propertyNames[i]);

            if (propertyNames[i].equals(idPropertyName) && log.isInfoEnabled())
                log.debug(infoMsg + ", Id for this class: " + idPropertyName + " , value:" + currentState[i]);

            if (currentState[i] != null) {
                // is this the primary key or transient? if so, we don't
                // want to serialize
                if (propertyNames[i].equals(idPropertyName)
                        || ("personId".equals(idPropertyName) && "patientId".equals(propertyNames[i]))
                        //|| ("personId".equals(idPropertyName) && "userId".equals(propertyNames[i]))
                        || transientProps.contains(propertyNames[i])) {
                    // if (log.isInfoEnabled())
                    log.debug("Skipping property (" + propertyNames[i]
                            + ") because it's either the primary key or it's transient.");

                } else {

                    addProperty(values, entity, types[i], propertyNames[i], currentState[i], infoMsg);
                }
            } else {
                // current state null -- skip
                if (log.isDebugEnabled())
                    log.debug("Field Type: " + typeName + " Field Name: " + propertyNames[i]
                            + " is null, skipped");
            }
        }

        /*
         * Now serialize the data identified and put in the value-map
         */
        // Setup the serialization data structures to hold the state
        Package pkg = new Package();
        String className = entity.getClass().getName();
        Record xml = pkg.createRecordForWrite(className);
        Item entityItem = xml.getRootItem();

        // loop through the map of the properties that need to be serialized
        for (Map.Entry<String, PropertyClassValue> me : values.entrySet()) {
            String property = me.getKey();

            // if we are processing onDelete event all we need is uuid
            if ((state == SyncItemState.DELETED) && (!"uuid".equals(property))) {
                continue;
            }

            try {
                PropertyClassValue pcv = me.getValue();
                appendRecord(xml, entity, entityItem, property, pcv.getClazz(), pcv.getValue());
            } catch (Exception e) {
                String msg = "Could not append attribute. Error while processing property: " + property + " - "
                        + e.getMessage();
                throw (new SyncException(msg, e));
            }
        }

        values.clear(); // Be nice to GC

        if (objectUuid == null)
            throw new SyncException("uuid is null for: " + className + " with id: " + id);

        /*
         * Create SyncItem and store change in SyncRecord kept in
         * ThreadLocal.
         */
        SyncItem syncItem = new SyncItem();
        syncItem.setKey(new SyncItemKey<String>(objectUuid, String.class));
        syncItem.setState(state);
        syncItem.setContent(xml.toStringAsDocumentFragment());
        syncItem.setContainedType(entity.getClass());

        if (log.isDebugEnabled())
            log.debug("Adding SyncItem to SyncRecord");

        getSyncRecord().addItem(syncItem);
        getSyncRecord().addContainedClass(entity.getClass().getName());

        // set the originating uuid for the record: do this once per Tx;
        // else we may end up with empty string
        if (getSyncRecord().getOriginalUuid() == null || "".equals(getSyncRecord().getOriginalUuid())) {
            getSyncRecord().setOriginalUuid(originalRecordUuid);
        }
    } catch (SyncException ex) {
        log.error("Journal error\n", ex);
        throw (ex);
    } catch (Exception e) {
        log.error("Journal error\n", e);
        throw (new SyncException("Error in interceptor, see log messages and callstack.", e));
    }

    return;
}

From source file:com.sonicle.webtop.calendar.CalendarManager.java

public void syncRemoteCalendar(int calendarId, boolean full) throws WTException {
    final UserProfile.Data udata = WT.getUserData(getTargetProfileId());
    final ICalendarInput icalInput = new ICalendarInput(udata.getTimeZone());
    final String PENDING_KEY = String.valueOf(calendarId);
    CalendarDAO calDao = CalendarDAO.getInstance();
    Connection con = null;// w w  w .  ja v  a2s  . c om

    if (pendingRemoteCalendarSyncs.putIfAbsent(PENDING_KEY, RunContext.getRunProfileId()) != null) {
        throw new ConcurrentSyncException("Sync activity is already running [{}, {}]", calendarId,
                RunContext.getRunProfileId());
    }

    try {
        //checkRightsOnCalendarFolder(calendarId, "READ");

        con = WT.getConnection(SERVICE_ID, false);
        Calendar cal = ManagerUtils.createCalendar(calDao.selectById(con, calendarId));
        if (cal == null)
            throw new WTException("Calendar not found [{0}]", calendarId);
        if (!Calendar.Provider.WEBCAL.equals(cal.getProvider())
                && !Calendar.Provider.CALDAV.equals(cal.getProvider())) {
            throw new WTException("Specified calendar is not remote (webcal or CalDAV) [{0}]", calendarId);
        }

        // Force a full update if last-sync date is null
        if (cal.getRemoteSyncTimestamp() == null)
            full = true;

        CalendarRemoteParameters params = LangUtils.deserialize(cal.getParameters(),
                CalendarRemoteParameters.class);
        if (params == null)
            throw new WTException("Unable to deserialize remote parameters");
        if (params.url == null)
            throw new WTException("Remote URL is undefined");

        if (Calendar.Provider.WEBCAL.equals(cal.getProvider())) {
            final String PREFIX = "webcal-";
            File tempFile = null;

            URIBuilder builder = new URIBuilder(params.url);
            if (StringUtils.equalsIgnoreCase(builder.getScheme(), "webcal")) {
                builder.setScheme("http"); // Force http scheme
            }
            if (!StringUtils.isBlank(params.username) && !StringUtils.isBlank(params.username)) {
                builder.setUserInfo(params.username, params.password);
            }
            URI newUrl = URIUtils.buildQuietly(builder);

            try {
                final DateTime newLastSync = DateTimeUtils.now();
                tempFile = WT.createTempFile(PREFIX, null);

                // Retrieve webcal content (iCalendar) from the specified URL 
                // and save it locally
                logger.debug("Downloading iCalendar file from URL [{}]", newUrl);
                HttpClient httpCli = null;
                FileOutputStream os = null;
                try {
                    httpCli = HttpClientUtils.createBasicHttpClient(HttpClientUtils.configureSSLAcceptAll(),
                            newUrl);
                    os = new FileOutputStream(tempFile);
                    HttpClientUtils.writeContent(httpCli, newUrl, os);

                } catch (IOException ex) {
                    throw new WTException(ex, "Unable to retrieve webcal [{0}]", newUrl);
                } finally {
                    IOUtils.closeQuietly(os);
                    HttpClientUtils.closeQuietly(httpCli);
                }
                logger.debug("Saved to temp file [{}]", tempFile.getName());

                // Parse downloaded iCalendar
                logger.debug("Parsing downloaded iCalendar file");
                net.fortuna.ical4j.model.Calendar ical = null;
                FileInputStream is = null;
                try {
                    is = new FileInputStream(tempFile);
                    ICalendarUtils.relaxParsingAndCompatibility();
                    ical = ICalendarUtils.parse(is);
                    //TODO: add support to FILENAME property (Google https://github.com/ical4j/ical4j/issues/69)
                } catch (IOException | ParserException ex) {
                    throw new WTException(ex, "Unable to read webcal");
                } finally {
                    IOUtils.closeQuietly(os);
                }

                icalInput.withIncludeVEventSourceInOutput(true);
                ArrayList<EventInput> input = icalInput.fromICalendarFile(ical, null);
                logger.debug("Found {} events", input.size());

                Map<String, VEventHrefSync> syncByHref = null;

                if (full) {
                    logger.debug("Cleaning up calendar [{}]", calendarId);
                    doEventsDeleteByCalendar(con, calendarId, false);
                } else {
                    EventDAO evtDao = EventDAO.getInstance();
                    syncByHref = evtDao.viewHrefSyncDataByCalendar(con, calendarId);
                }

                // Inserts/Updates data...
                logger.debug("Inserting/Updating events...");
                try {
                    String autoUidPrefix = DigestUtils.md5Hex(newUrl.toString()); // auto-gen base prefix in case of missing UID
                    HashSet<String> hrefs = new HashSet<>();
                    HashMap<String, OEvent> cache = new HashMap<>();
                    int i = 0;
                    for (EventInput ei : input) {
                        if (StringUtils.isBlank(ei.event.getPublicUid())) {
                            String autoUid = autoUidPrefix + "-" + i;
                            ei.event.setPublicUid(autoUid);
                            logger.trace("Missing UID: using auto-gen value. [{}]", autoUid);
                        }
                        String href = ManagerUtils.buildHref(ei.event.getPublicUid());

                        //if (logger.isTraceEnabled()) logger.trace("{}", ICalendarUtils.print(ICalendarUtils.getVEvent(devt.getCalendar())));
                        if (hrefs.contains(href)) {
                            logger.trace("Event duplicated. Skipped! [{}]", href);
                            continue;
                        }

                        boolean skip = false;
                        Integer matchingEventId = null;
                        String eiHash = DigestUtils.md5Hex(ei.sourceEvent.toString());

                        if (syncByHref != null) { // Only if... (!full) see above!
                            VEventHrefSync hrefSync = syncByHref.remove(href);
                            if (hrefSync != null) { // Href found -> maybe updated item
                                if (!StringUtils.equals(hrefSync.getEtag(), eiHash)) {
                                    matchingEventId = hrefSync.getEventId();
                                    logger.trace("Event updated [{}, {}]", href, eiHash);
                                } else {
                                    skip = true;
                                    logger.trace("Event not modified [{}, {}]", href, eiHash);
                                }
                            } else { // Href not found -> added item
                                logger.trace("Event newly added [{}, {}]", href, eiHash);
                            }
                        }

                        if (!skip) {
                            ei.event.setCalendarId(calendarId);
                            ei.event.setHref(href);
                            ei.event.setEtag(eiHash);

                            if (matchingEventId != null) {
                                ei.event.setEventId(matchingEventId);
                                boolean updated = doEventInputUpdate(con, cache, ei);
                                if (!updated)
                                    throw new WTException("Event not found [{}]", ei.event.getEventId());

                            } else {
                                doEventInputInsert(con, cache, ei);
                            }
                        }

                        hrefs.add(href); // Marks as processed!
                    }

                    if (syncByHref != null) { // Only if... (!full) see above!
                        // Remaining hrefs -> deleted items
                        for (VEventHrefSync hrefSync : syncByHref.values()) {
                            logger.trace("Event deleted [{}]", hrefSync.getHref());
                            doEventDelete(con, hrefSync.getEventId(), false);
                        }
                    }

                    cache.clear();
                    calDao.updateRemoteSyncById(con, calendarId, newLastSync, null);
                    DbUtils.commitQuietly(con);

                } catch (Exception ex) {
                    DbUtils.rollbackQuietly(con);
                    throw new WTException(ex, "Error importing iCalendar");
                }

            } finally {
                if (tempFile != null) {
                    logger.debug("Removing temp file [{}]", tempFile.getName());
                    WT.deleteTempFile(tempFile);
                }
            }

        } else if (Calendar.Provider.CALDAV.equals(cal.getProvider())) {
            CalDav dav = getCalDav(params.username, params.password);

            try {
                DavCalendar dcal = dav.getCalendarSyncToken(params.url.toString());
                if (dcal == null)
                    throw new WTException("DAV calendar not found");

                final boolean syncIsSupported = !StringUtils.isBlank(dcal.getSyncToken());
                final DateTime newLastSync = DateTimeUtils.now();

                if (!full && (syncIsSupported && !StringUtils.isBlank(cal.getRemoteSyncTag()))) { // Partial update using SYNC mode
                    String newSyncToken = dcal.getSyncToken();

                    logger.debug("Querying CalDAV endpoint for changes [{}, {}]", params.url.toString(),
                            cal.getRemoteSyncTag());
                    List<DavSyncStatus> changes = dav.getCalendarChanges(params.url.toString(),
                            cal.getRemoteSyncTag());
                    logger.debug("Returned {} items", changes.size());

                    try {
                        if (!changes.isEmpty()) {
                            EventDAO evtDao = EventDAO.getInstance();
                            Map<String, List<Integer>> eventIdsByHref = evtDao.selectHrefsByByCalendar(con,
                                    calendarId);

                            // Process changes...
                            logger.debug("Processing changes...");
                            HashSet<String> hrefs = new HashSet<>();
                            for (DavSyncStatus change : changes) {
                                String href = FilenameUtils.getName(change.getPath());
                                //String href = change.getPath();

                                if (DavUtil.HTTP_SC_TEXT_OK.equals(change.getResponseStatus())) {
                                    hrefs.add(href);

                                } else { // Event deleted
                                    List<Integer> eventIds = eventIdsByHref.get(href);
                                    Integer eventId = (eventIds != null) ? eventIds.get(eventIds.size() - 1)
                                            : null;
                                    if (eventId == null) {
                                        logger.warn("Deletion not possible. Event path not found [{}]",
                                                PathUtils.concatPaths(dcal.getPath(),
                                                        FilenameUtils.getName(href)));
                                        continue;
                                    }
                                    doEventDelete(con, eventId, false);
                                }
                            }

                            // Retrieves events list from DAV endpoint (using multiget)
                            logger.debug("Retrieving inserted/updated events [{}]", hrefs.size());
                            Collection<String> paths = hrefs.stream().map(
                                    href -> PathUtils.concatPaths(dcal.getPath(), FilenameUtils.getName(href)))
                                    .collect(Collectors.toList());
                            List<DavCalendarEvent> devts = dav.listCalendarEvents(params.url.toString(), paths);
                            //List<DavCalendarEvent> devts = dav.listCalendarEvents(params.url.toString(), hrefs);

                            // Inserts/Updates data...
                            logger.debug("Inserting/Updating events...");
                            HashMap<String, OEvent> cache = new HashMap<>();
                            for (DavCalendarEvent devt : devts) {
                                String href = FilenameUtils.getName(devt.getPath());
                                //String href = devt.getPath();

                                if (logger.isTraceEnabled())
                                    logger.trace("{}",
                                            ICalendarUtils.print(ICalendarUtils.getVEvent(devt.getCalendar())));
                                List<Integer> eventIds = eventIdsByHref.get(href);
                                Integer eventId = (eventIds != null) ? eventIds.get(eventIds.size() - 1) : null;

                                final ArrayList<EventInput> input = icalInput
                                        .fromICalendarFile(devt.getCalendar(), null);
                                if (input.size() != 1)
                                    throw new WTException("iCal must contain one event");
                                final EventInput ei = input.get(0);

                                if (eventId != null) {
                                    doEventDelete(con, eventId, false);
                                }

                                ei.event.setCalendarId(calendarId);
                                ei.event.setHref(href);
                                ei.event.setEtag(devt.geteTag());
                                doEventInputInsert(con, cache, ei);
                            }
                        }

                        calDao.updateRemoteSyncById(con, calendarId, newLastSync, newSyncToken);
                        DbUtils.commitQuietly(con);

                    } catch (Exception ex) {
                        DbUtils.rollbackQuietly(con);
                        throw new WTException(ex, "Error importing iCalendar");
                    }

                } else { // Full update or partial computing hashes
                    String newSyncToken = null;
                    if (syncIsSupported) { // If supported, saves last sync-token issued by the server
                        newSyncToken = dcal.getSyncToken();
                    }

                    // Retrieves cards from DAV endpoint
                    logger.debug("Querying CalDAV endpoint [{}]", params.url.toString());
                    List<DavCalendarEvent> devts = dav.listCalendarEvents(params.url.toString());
                    logger.debug("Returned {} items", devts.size());

                    // Handles data...
                    try {
                        Map<String, VEventHrefSync> syncByHref = null;

                        if (full) {
                            logger.debug("Cleaning up calendar [{}]", calendarId);
                            doEventsDeleteByCalendar(con, calendarId, false);
                        } else if (!full && !syncIsSupported) {
                            // This hash-map is only needed when syncing using hashes
                            EventDAO evtDao = EventDAO.getInstance();
                            syncByHref = evtDao.viewHrefSyncDataByCalendar(con, calendarId);
                        }

                        logger.debug("Processing results...");
                        // Define a simple map in order to check duplicates.
                        // eg. SOGo passes same card twice :(
                        HashSet<String> hrefs = new HashSet<>();
                        HashMap<String, OEvent> cache = new HashMap<>();
                        for (DavCalendarEvent devt : devts) {
                            String href = PathUtils.getFileName(devt.getPath());
                            //String href = devt.getPath();
                            String etag = devt.geteTag();

                            if (logger.isTraceEnabled())
                                logger.trace("{}",
                                        ICalendarUtils.print(ICalendarUtils.getVEvent(devt.getCalendar())));
                            if (hrefs.contains(href)) {
                                logger.trace("Card duplicated. Skipped! [{}]", href);
                                continue;
                            }

                            boolean skip = false;
                            Integer matchingEventId = null;

                            if (syncByHref != null) { // Only if... (!full && !syncIsSupported) see above!
                                //String prodId = ICalendarUtils.buildProdId(ManagerUtils.getProductName());
                                //String hash = DigestUtils.md5Hex(new ICalendarOutput(prodId, true).write(devt.getCalendar()));
                                String hash = DigestUtils
                                        .md5Hex(ICalendarUtils.getVEvent(devt.getCalendar()).toString());

                                VEventHrefSync hrefSync = syncByHref.remove(href);
                                if (hrefSync != null) { // Href found -> maybe updated item
                                    if (!StringUtils.equals(hrefSync.getEtag(), hash)) {
                                        matchingEventId = hrefSync.getEventId();
                                        etag = hash;
                                        logger.trace("Event updated [{}, {}]", href, hash);
                                    } else {
                                        skip = true;
                                        logger.trace("Event not modified [{}, {}]", href, hash);
                                    }
                                } else { // Href not found -> added item
                                    logger.trace("Event newly added [{}]", href);
                                    etag = hash;
                                }
                            }

                            if (!skip) {
                                final ArrayList<EventInput> input = icalInput
                                        .fromICalendarFile(devt.getCalendar(), null);
                                if (input.size() != 1)
                                    throw new WTException("iCal must contain one event");
                                final EventInput ei = input.get(0);
                                ei.event.setCalendarId(calendarId);
                                ei.event.setHref(href);
                                ei.event.setEtag(etag);

                                if (matchingEventId == null) {
                                    doEventInputInsert(con, cache, ei);
                                } else {
                                    ei.event.setEventId(matchingEventId);
                                    boolean updated = doEventInputUpdate(con, cache, ei);
                                    if (!updated)
                                        throw new WTException("Event not found [{}]", ei.event.getEventId());
                                }
                            }

                            hrefs.add(href); // Marks as processed!
                        }

                        if (syncByHref != null) { // Only if... (!full && !syncIsSupported) see above!
                            // Remaining hrefs -> deleted items
                            for (VEventHrefSync hrefSync : syncByHref.values()) {
                                logger.trace("Event deleted [{}]", hrefSync.getHref());
                                doEventDelete(con, hrefSync.getEventId(), false);
                            }
                        }

                        calDao.updateRemoteSyncById(con, calendarId, newLastSync, newSyncToken);
                        DbUtils.commitQuietly(con);

                    } catch (Exception ex) {
                        DbUtils.rollbackQuietly(con);
                        throw new WTException(ex, "Error importing iCalendar");
                    }
                }

            } catch (DavException ex) {
                throw new WTException(ex, "CalDAV error");
            }
        }

    } catch (SQLException | DAOException ex) {
        throw wrapException(ex);
    } finally {
        DbUtils.closeQuietly(con);
        pendingRemoteCalendarSyncs.remove(PENDING_KEY);
    }
}

From source file:com.krawler.spring.hrms.rec.job.hrmsRecJobController.java

public ModelAndView getAllUserDetails(HttpServletRequest request, HttpServletResponse response)
        throws JSONException {
    JSONObject jobj = new JSONObject();
    int count;//  w  ww .  ja va2s  .  c  o  m
    HashMap<String, Object> requestParams = new HashMap<String, Object>();
    KwlReturnObject result = null;
    try {

        ArrayList params = new ArrayList();
        ArrayList filter_names = new ArrayList();
        ArrayList order_by = new ArrayList();
        ArrayList order_type = new ArrayList();
        filter_names.add("ua.user.company.companyID");
        filter_names.add("ua.user.deleteflag");
        params.add(sessionHandlerImplObj.getCompanyid(request));
        params.add(0);

        // @@ useraccount

        //            if(!StringUtil.isNullOrEmpty(request.getParameter("combo"))){
        //
        //                order_by.add("u.firstName");
        //                order_type.add("asc");
        //            }else{
        //
        //                order_by.add("u.employeeid");
        //                order_type.add("asc");
        //            }
        requestParams.put("filter_names", filter_names);
        requestParams.put("filter_values", params);
        requestParams.put("order_by", order_by);
        requestParams.put("order_type", order_type);
        requestParams.put("ss", request.getParameter("ss"));
        requestParams.put("searchcol", new String[] { "u.firstName", "u.lastName" });
        //            requestParams.put("start", Integer.valueOf(request.getParameter("start")));
        //            requestParams.put("limit", Integer.valueOf(request.getParameter("limit")));
        result = hrmsCommonDAOObj.getEmpprofileuser(requestParams);
        List list = result.getEntityList();
        count = result.getRecordTotalCount();
        for (int ctr = 0; ctr < count; ctr++) {
            Object[] row = (Object[]) list.get(ctr);
            JSONObject obj = new JSONObject();
            Empprofile e = null;
            Useraccount ua = (Useraccount) row[1];
            User u = ua.getUser();
            if (row[0] != null) {
                e = (Empprofile) row[0];
                if (!StringUtil.isNullOrEmpty(e.getStatus())) {
                    obj.put("status", e.getStatus());
                } else {
                    obj.put("status", "Pending");
                }
            } else {
                obj.put("status", "Incomplete");
            }
            obj.put("department", (ua.getDepartment() == null ? "" : ua.getDepartment().getId()));
            obj.put("departmentname", (ua.getDepartment() == null ? "" : ua.getDepartment().getValue()));
            obj.put("role", (ua.getRole() == null ? "" : ua.getRole().getID()));
            String name = "";
            if (ua.getRole() != null && ua.getRole().getCompany() != null) {
                name = ua.getRole().getName();
            } else {
                name = messageSource.getMessage("hrms.common.role." + ua.getRole().getID(), null,
                        ua.getRole().getName(), RequestContextUtils.getLocale(request));
            }
            obj.put("rolename", (ua.getRole() == null ? "" : name));
            obj.put("userid", u.getUserID());
            obj.put("username", u.getUserLogin().getUserName());
            obj.put("fname", u.getFirstName());
            obj.put("lname", u.getLastName());
            obj.put("fullname", u.getFirstName() + " " + (u.getLastName() == null ? "" : u.getLastName()));
            obj.put("image", u.getImage());
            obj.put("emailid", u.getEmailID());
            obj.put("lastlogin",
                    (u.getUserLogin().getLastActivityDate() == null ? ""
                            : sessionHandlerImplObj.getDateFormatter(request)
                                    .format(u.getUserLogin().getLastActivityDate())));
            obj.put("aboutuser", u.getAboutUser());
            obj.put("address", u.getAddress());
            obj.put("contactno", u.getContactNumber());
            obj.put("designation", ua.getDesignationid() == null ? "" : ua.getDesignationid().getValue());
            obj.put("designationid", ua.getDesignationid() == null ? "" : ua.getDesignationid().getId());
            obj.put("salary", ua.getSalary());
            obj.put("accno", ua.getAccno());
            obj.put("templateid", ua.getTemplateid() != null ? ua.getTemplateid() : "");
            requestParams.clear();
            requestParams.put("companyid", sessionHandlerImplObj.getCompanyid(request));
            requestParams.put("empid", ua.getEmployeeid());
            //                result = profileHandlerDAOObj.getEmpidFormatEdit(requestParams);
            obj.put("employeeid", ua.getEmployeeid() == null ? ""
                    : profileHandlerDAOObj.getEmpidFormatEdit(requestParams).getEntityList().get(0));

            //                List lst1 = HibernateUtil.executeQuery(session, "from  Assignmanager where assignemp.userID=? and managerstatus=1", u.getUserID());
            //                Iterator itr1 = lst1.iterator();
            requestParams.clear();
            //                requestParams.put("userid", u.getUserID());
            //                requestParams.put("managerstatus", 1);
            filter_names.clear();
            params.clear();
            filter_names.add("assignemp.userID");
            params.add(u.getUserID());

            filter_names.add("managerstatus");
            params.add(1);

            requestParams.put("filter_names", filter_names);
            requestParams.put("filter_values", params);

            result = hrmsCommonDAOObj.getAssignmanager(requestParams);
            List lst1 = result.getEntityList();
            for (int cnt = 0; cnt < lst1.size(); cnt++) {
                Assignmanager asm = (Assignmanager) lst1.get(cnt);
                if (asm.getAssignman() != null) {
                    obj.append("managerid", asm.getAssignman().getUserID());
                    obj.append("manager",
                            asm.getAssignman().getFirstName() + " " + asm.getAssignman().getLastName());
                }
            }
            if (lst1.size() == 0) {
                obj.put("manager", " ");
                obj.put("managerid", " ");
            }
            jobj.append("data", obj);
            //                jArr.put(obj);
            //                lst1 = HibernateUtil.executeQuery(session, "from  Assignreviewer where employee.userID=? and reviewerstatus=1", u.getUserID());
            //                itr1 = lst1.iterator();
            requestParams.clear();
            requestParams.put("userid", u.getUserID());
            requestParams.put("reviewerstatus", 1);
            result = hrmsCommonDAOObj.getAssignreviewer(requestParams);
            lst1 = result.getEntityList();
            for (int cnt1 = 0; cnt1 < lst1.size(); cnt1++) {
                Assignreviewer rev = (Assignreviewer) lst1.get(cnt1);
                if (rev.getReviewer() != null) {
                    obj.append("reviewerid", rev.getReviewer().getUserID());
                    obj.append("reviewer",
                            rev.getReviewer().getFirstName() + " " + rev.getReviewer().getLastName());
                }
            }
            if (lst1.size() == 0) {
                obj.put("reviewer", " ");
                obj.put("reviewerid", " ");
            }
            jobj.append("data", obj);
        }
        jobj.put("count", count);

    } catch (Exception e) {
        System.out.print(e);

    } finally {
        if (!jobj.has("data")) {
            jobj.put("count", 0);
            jobj.put("data", "");
        }
        JSONObject jobj1 = new JSONObject();
        jobj1.put("valid", true);
        jobj1.put("data", jobj);
        return new ModelAndView("jsonView", "model", jobj1.toString());
    }
}

From source file:carnero.cgeo.original.libs.Base.java

public int postLog(App app, String geocode, String cacheid, String viewstate, String viewstate1, int logType,
        int year, int month, int day, String log, ArrayList<TrackableLog> trackables) {
    if (viewstate == null || viewstate.length() == 0) {
        Log.e(Settings.tag, "cgeoBase.postLog: No viewstate given");
        return 1000;
    }// w  w w.  j  av a  2 s .c  o  m

    if (logTypes2.containsKey(logType) == false) {
        Log.e(Settings.tag, "cgeoBase.postLog: Unknown logtype");
        return 1000;
    }

    if (log == null || log.length() == 0) {
        Log.e(Settings.tag, "cgeoBase.postLog: No log text given");
        return 1001;
    }

    // fix log (non-Latin characters converted to HTML entities)
    final int logLen = log.length();
    final StringBuilder logUpdated = new StringBuilder();

    for (int i = 0; i < logLen; i++) {
        char c = log.charAt(i);

        if (c > 300) {
            logUpdated.append("&#");
            logUpdated.append(Integer.toString((int) c));
            logUpdated.append(";");
        } else {
            logUpdated.append(c);
        }
    }
    log = logUpdated.toString();

    log = log.replace("\n", "\r\n"); // windows' eol

    if (trackables != null) {
        Log.i(Settings.tag, "Trying to post log for cache #" + cacheid + " - action: " + logType + "; date: "
                + year + "." + month + "." + day + ", log: " + log + "; trackables: " + trackables.size());
    } else {
        Log.i(Settings.tag, "Trying to post log for cache #" + cacheid + " - action: " + logType + "; date: "
                + year + "." + month + "." + day + ", log: " + log + "; trackables: 0");
    }

    final String host = "www.geocaching.com";
    final String path = "/seek/log.aspx?ID=" + cacheid;
    final String method = "POST";
    final HashMap<String, String> params = new HashMap<String, String>();

    params.put("__VIEWSTATE", viewstate);
    if (viewstate1 != null) {
        params.put("__VIEWSTATE1", viewstate1);
        params.put("__VIEWSTATEFIELDCOUNT", "2");
    }
    params.put("__EVENTTARGET", "");
    params.put("__EVENTARGUMENT", "");
    params.put("__LASTFOCUS", "");
    params.put("ctl00$ContentBody$LogBookPanel1$ddLogType", Integer.toString(logType));
    params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged", String.format("%02d", month) + "/"
            + String.format("%02d", day) + "/" + String.format("%04d", year));
    params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Month", Integer.toString(month));
    params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Day", Integer.toString(day));
    params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Year", Integer.toString(year));
    params.put("ctl00$ContentBody$LogBookPanel1$uxLogInfo", log);
    params.put("ctl00$ContentBody$LogBookPanel1$LogButton", "Submit Log Entry");
    params.put("ctl00$ContentBody$uxVistOtherListingGC", "");
    if (trackables != null && trackables.isEmpty() == false) { //  we have some trackables to proceed
        final StringBuilder hdnSelected = new StringBuilder();

        for (TrackableLog tb : trackables) {
            final String action = Integer.toString(tb.id) + logTypesTrackableAction.get(tb.action);

            if (tb.action > 0) {
                hdnSelected.append(action);
                hdnSelected.append(",");
            }
        }

        params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnSelectedActions", hdnSelected.toString()); // selected trackables
        params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnCurrentFilter", "");
    }

    String page = request(false, host, path, method, params, false, false, false).getData();
    if (checkLogin(page) == false) {
        int loginState = login();
        if (loginState == 1) {
            page = request(false, host, path, method, params, false, false, false).getData();
        } else {
            Log.e(Settings.tag, "cgeoBase.postLog: Can not log in geocaching (error: " + loginState + ")");
            return loginState;
        }
    }

    if (page == null || page.length() == 0) {
        Log.e(Settings.tag, "cgeoBase.postLog: No data from server");
        return 1002;
    }

    // maintenance, archived needs to be confirmed
    final Pattern pattern = Pattern.compile(
            "<span id=\"ctl00_ContentBody_LogBookPanel1_lbConfirm\"[^>]*>([^<]*<font[^>]*>)?([^<]+)(</font>[^<]*)?</span>",
            Pattern.CASE_INSENSITIVE);
    final Matcher matcher = pattern.matcher(page);

    try {
        if (matcher.find() == true && matcher.groupCount() > 0) {
            final String viewstateConfirm = findViewstate(page, 0);
            final String viewstate1Confirm = findViewstate(page, 1);

            if (viewstateConfirm == null || viewstateConfirm.length() == 0) {
                Log.e(Settings.tag, "cgeoBase.postLog: No viewstate for confirm log");
                return 1000;
            }

            params.clear();
            params.put("__VIEWSTATE", viewstateConfirm);
            if (viewstate1 != null) {
                params.put("__VIEWSTATE1", viewstate1Confirm);
                params.put("__VIEWSTATEFIELDCOUNT", "2");
            }
            params.put("__EVENTTARGET", "");
            params.put("__EVENTARGUMENT", "");
            params.put("__LASTFOCUS", "");
            params.put("ctl00$ContentBody$LogBookPanel1$btnConfirm", "Yes");
            params.put("ctl00$ContentBody$LogBookPanel1$uxLogInfo", log);
            params.put("ctl00$ContentBody$uxVistOtherListingGC", "");
            if (trackables != null && trackables.isEmpty() == false) { //  we have some trackables to proceed
                final StringBuilder hdnSelected = new StringBuilder();

                for (TrackableLog tb : trackables) {
                    String ctl = null;
                    final String action = Integer.toString(tb.id) + logTypesTrackableAction.get(tb.action);

                    if (tb.ctl < 10) {
                        ctl = "0" + Integer.toString(tb.ctl);
                    } else {
                        ctl = Integer.toString(tb.ctl);
                    }

                    params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$repTravelBugs$ctl" + ctl
                            + "$ddlAction", action);
                    if (tb.action > 0) {
                        hdnSelected.append(action);
                        hdnSelected.append(",");
                    }
                }

                params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnSelectedActions",
                        hdnSelected.toString()); // selected trackables
                params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnCurrentFilter", "");
            }

            page = request(false, host, path, method, params, false, false, false).getData();
        }
    } catch (Exception e) {
        Log.e(Settings.tag, "cgeoBase.postLog.confim: " + e.toString());
    }

    try {
        final Pattern patternOk = Pattern.compile(
                "<h2[^>]*>[^<]*<span id=\"ctl00_ContentBody_lbHeading\"[^>]*>[^<]*</span>[^<]*</h2>",
                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        final Matcher matcherOk = patternOk.matcher(page);
        if (matcherOk.find() == true) {
            Log.i(Settings.tag, "Log successfully posted to cache #" + cacheid);

            if (app != null && geocode != null) {
                app.saveVisitDate(geocode);
            }

            return 1;
        }
    } catch (Exception e) {
        Log.e(Settings.tag, "cgeoBase.postLog.check: " + e.toString());
    }

    Log.e(Settings.tag, "cgeoBase.postLog: Failed to post log because of unknown error");
    return 1000;
}

From source file:carnero.cgeo.cgBase.java

public int postLog(cgeoapplication app, String geocode, String cacheid, String viewstate, String viewstate1,
        int logType, int year, int month, int day, String log, ArrayList<cgTrackableLog> trackables) {
    if (viewstate == null || viewstate.length() == 0) {
        Log.e(cgSettings.tag, "cgeoBase.postLog: No viewstate given");
        return 1000;
    }//from www  . ja va  2s.  com

    if (logTypes2.containsKey(logType) == false) {
        Log.e(cgSettings.tag, "cgeoBase.postLog: Unknown logtype");
        return 1000;
    }

    if (log == null || log.length() == 0) {
        Log.e(cgSettings.tag, "cgeoBase.postLog: No log text given");
        return 1001;
    }

    // fix log (non-Latin characters converted to HTML entities)
    final int logLen = log.length();
    final StringBuilder logUpdated = new StringBuilder();

    for (int i = 0; i < logLen; i++) {
        char c = log.charAt(i);

        if (c > 300) {
            logUpdated.append("&#");
            logUpdated.append(Integer.toString((int) c));
            logUpdated.append(";");
        } else {
            logUpdated.append(c);
        }
    }
    log = logUpdated.toString();

    log = log.replace("\n", "\r\n"); // windows' eol

    if (trackables != null) {
        Log.i(cgSettings.tag, "Trying to post log for cache #" + cacheid + " - action: " + logType + "; date: "
                + year + "." + month + "." + day + ", log: " + log + "; trackables: " + trackables.size());
    } else {
        Log.i(cgSettings.tag, "Trying to post log for cache #" + cacheid + " - action: " + logType + "; date: "
                + year + "." + month + "." + day + ", log: " + log + "; trackables: 0");
    }

    final String host = "www.geocaching.com";
    final String path = "/seek/log.aspx?ID=" + cacheid;
    final String method = "POST";
    final HashMap<String, String> params = new HashMap<String, String>();

    params.put("__VIEWSTATE", viewstate);
    if (viewstate1 != null) {
        params.put("__VIEWSTATE1", viewstate1);
        params.put("__VIEWSTATEFIELDCOUNT", "2");
    }
    params.put("__EVENTTARGET", "");
    params.put("__EVENTARGUMENT", "");
    params.put("__LASTFOCUS", "");
    params.put("ctl00$ContentBody$LogBookPanel1$ddLogType", Integer.toString(logType));
    params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged", String.format("%02d", month) + "/"
            + String.format("%02d", day) + "/" + String.format("%04d", year));
    params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Month", Integer.toString(month));
    params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Day", Integer.toString(day));
    params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Year", Integer.toString(year));
    params.put("ctl00$ContentBody$LogBookPanel1$uxLogInfo", log);
    params.put("ctl00$ContentBody$LogBookPanel1$LogButton", "Submit Log Entry");
    params.put("ctl00$ContentBody$uxVistOtherListingGC", "");
    if (trackables != null && trackables.isEmpty() == false) { //  we have some trackables to proceed
        final StringBuilder hdnSelected = new StringBuilder();

        for (cgTrackableLog tb : trackables) {
            final String action = Integer.toString(tb.id) + logTypesTrackableAction.get(tb.action);

            if (tb.action > 0) {
                hdnSelected.append(action);
                hdnSelected.append(",");
            }
        }

        params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnSelectedActions", hdnSelected.toString()); // selected trackables
        params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnCurrentFilter", "");
    }

    String page = request(false, host, path, method, params, false, false, false).getData();
    if (checkLogin(page) == false) {
        int loginState = login();
        if (loginState == 1) {
            page = request(false, host, path, method, params, false, false, false).getData();
        } else {
            Log.e(cgSettings.tag, "cgeoBase.postLog: Can not log in geocaching (error: " + loginState + ")");
            return loginState;
        }
    }

    if (page == null || page.length() == 0) {
        Log.e(cgSettings.tag, "cgeoBase.postLog: No data from server");
        return 1002;
    }

    // maintenance, archived needs to be confirmed
    final Pattern pattern = Pattern.compile(
            "<span id=\"ctl00_ContentBody_LogBookPanel1_lbConfirm\"[^>]*>([^<]*<font[^>]*>)?([^<]+)(</font>[^<]*)?</span>",
            Pattern.CASE_INSENSITIVE);
    final Matcher matcher = pattern.matcher(page);

    try {
        if (matcher.find() == true && matcher.groupCount() > 0) {
            final String viewstateConfirm = findViewstate(page, 0);
            final String viewstate1Confirm = findViewstate(page, 1);

            if (viewstateConfirm == null || viewstateConfirm.length() == 0) {
                Log.e(cgSettings.tag, "cgeoBase.postLog: No viewstate for confirm log");
                return 1000;
            }

            params.clear();
            params.put("__VIEWSTATE", viewstateConfirm);
            if (viewstate1 != null) {
                params.put("__VIEWSTATE1", viewstate1Confirm);
                params.put("__VIEWSTATEFIELDCOUNT", "2");
            }
            params.put("__EVENTTARGET", "");
            params.put("__EVENTARGUMENT", "");
            params.put("__LASTFOCUS", "");
            params.put("ctl00$ContentBody$LogBookPanel1$btnConfirm", "Yes");
            params.put("ctl00$ContentBody$LogBookPanel1$uxLogInfo", log);
            params.put("ctl00$ContentBody$uxVistOtherListingGC", "");
            if (trackables != null && trackables.isEmpty() == false) { //  we have some trackables to proceed
                final StringBuilder hdnSelected = new StringBuilder();

                for (cgTrackableLog tb : trackables) {
                    String ctl = null;
                    final String action = Integer.toString(tb.id) + logTypesTrackableAction.get(tb.action);

                    if (tb.ctl < 10) {
                        ctl = "0" + Integer.toString(tb.ctl);
                    } else {
                        ctl = Integer.toString(tb.ctl);
                    }

                    params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$repTravelBugs$ctl" + ctl
                            + "$ddlAction", action);
                    if (tb.action > 0) {
                        hdnSelected.append(action);
                        hdnSelected.append(",");
                    }
                }

                params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnSelectedActions",
                        hdnSelected.toString()); // selected trackables
                params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnCurrentFilter", "");
            }

            page = request(false, host, path, method, params, false, false, false).getData();
        }
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgeoBase.postLog.confim: " + e.toString());
    }

    try {
        final Pattern patternOk = Pattern.compile(
                "<h2[^>]*>[^<]*<span id=\"ctl00_ContentBody_lbHeading\"[^>]*>[^<]*</span>[^<]*</h2>",
                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        final Matcher matcherOk = patternOk.matcher(page);
        if (matcherOk.find() == true) {
            Log.i(cgSettings.tag, "Log successfully posted to cache #" + cacheid);

            if (app != null && geocode != null) {
                app.saveVisitDate(geocode);
            }

            return 1;
        }
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgeoBase.postLog.check: " + e.toString());
    }

    Log.e(cgSettings.tag, "cgeoBase.postLog: Failed to post log because of unknown error");
    return 1000;
}

From source file:me.ryanhamshire.PopulationDensity.DataStore.java

private void loadMessages() {
    Messages[] messageIDs = Messages.values();
    this.messages = new String[Messages.values().length];

    HashMap<String, CustomizableMessage> defaults = new HashMap<String, CustomizableMessage>();

    //initialize defaults
    this.addDefault(defaults, Messages.NoManagedWorld,
            "The PopulationDensity plugin has not been properly configured.  Please update your config.yml to specify a world to manage.",
            null);/*from w w w. j  a v  a2  s  .  c  o m*/
    this.addDefault(defaults, Messages.NoBreakPost, "You can't break blocks this close to the region post.",
            null);
    this.addDefault(defaults, Messages.NoBreakSpawn,
            "You can't break blocks this close to a player spawn point.", null);
    this.addDefault(defaults, Messages.NoBuildPost, "You can't place blocks this close to the region post.",
            null);
    this.addDefault(defaults, Messages.NoBuildSpawn,
            "You can't place blocks this close to a player spawn point.", null);
    this.addDefault(defaults, Messages.HelpMessage1, "Region post help and commands: {0} ", "0: Help URL");
    this.addDefault(defaults, Messages.BuildingAwayFromHome,
            "You're building outside of your home region.  If you'd like to make this region your new home to help you return here later, use /MoveIn.",
            null);
    this.addDefault(defaults, Messages.NoTeleportThisWorld, "You can't teleport from this world.", null);
    this.addDefault(defaults, Messages.OnlyHomeCityHere, "You're limited to /HomeRegion and /CityRegion here.",
            null);
    this.addDefault(defaults, Messages.NoTeleportHere, "Sorry, you can't teleport from here.", null);
    this.addDefault(defaults, Messages.NotCloseToPost, "You're not close enough to a region post to teleport.",
            null);
    this.addDefault(defaults, Messages.InvitationNeeded,
            "{0} lives in the wilderness.  He or she will have to /invite you.", "0: target player");
    this.addDefault(defaults, Messages.VisitConfirmation, "Teleported to {0}'s home region.",
            "0: target player");
    this.addDefault(defaults, Messages.DestinationNotFound,
            "There's no region or online player named \"{0}\".  Use /ListRegions to list possible destinations.",
            "0: specified destination");
    this.addDefault(defaults, Messages.NeedNewestRegionPermission,
            "You don't have permission to use that command.", null);
    this.addDefault(defaults, Messages.NewestRegionConfirmation, "Teleported to the current new player area.",
            null);
    this.addDefault(defaults, Messages.NotInRegion, "You're not in a region!", null);
    this.addDefault(defaults, Messages.UnnamedRegion,
            "You're in the wilderness!  This region doesn't have a name.", null);
    this.addDefault(defaults, Messages.WhichRegion, "You're in the {0} region.", null);
    this.addDefault(defaults, Messages.RegionNamesNoSpaces, "Region names may not include spaces.", null);
    this.addDefault(defaults, Messages.RegionNameLength, "Region names must be at most {0} letters long.",
            "0: maximum length specified in config.yml");
    this.addDefault(defaults, Messages.RegionNamesOnlyLettersAndNumbers,
            "Region names may not include symbols or punctuation.", null);
    this.addDefault(defaults, Messages.RegionNameConflict, "There's already a region by that name.", null);
    this.addDefault(defaults, Messages.NoMoreRegions,
            "Sorry, you're in the only region.  Over time, more regions will open.", null);
    this.addDefault(defaults, Messages.InviteAlreadySent,
            "{0} may now use /visit {1} to teleport to your home post.",
            "0: invitee's name, 1: inviter's name");
    this.addDefault(defaults, Messages.InviteConfirmation,
            "{0} may now use /visit {1} to teleport to your home post.",
            "0: invitee's name, 1: inviter's name");
    this.addDefault(defaults, Messages.InviteNotification, "{0} has invited you to visit!",
            "0: inviter's name");
    this.addDefault(defaults, Messages.InviteInstruction, "Use /visit {0} to teleport there.",
            "0: inviter's name");
    this.addDefault(defaults, Messages.PlayerNotFound, "There's no player named \"{0}\" online right now.",
            "0: specified name");
    this.addDefault(defaults, Messages.SetHomeConfirmation, "Home set to the nearest region post!", null);
    this.addDefault(defaults, Messages.SetHomeInstruction1,
            "Use /Home from any region post to teleport to your home post.", null);
    this.addDefault(defaults, Messages.SetHomeInstruction2,
            "Use /Invite to invite other players to teleport to your home post.", null);
    this.addDefault(defaults, Messages.AddRegionConfirmation,
            "Opened a new region and started a resource scan.  See console or server logs for details.", null);
    this.addDefault(defaults, Messages.ScanStartConfirmation,
            "Started scan.  Check console or server logs for results.", null);
    this.addDefault(defaults, Messages.LoginPriorityCheck, "{0}'s login priority: {1}.",
            "0: player name, 1: current priority");
    this.addDefault(defaults, Messages.LoginPriorityUpdate, "Set {0}'s priority to {1}.",
            "0: target player, 1: new priority");
    this.addDefault(defaults, Messages.ThinningConfirmation,
            "Thinning running.  Check logs for detailed results.", null);
    this.addDefault(defaults, Messages.PerformanceScore, "Current server performance score is {0}%.",
            "0: performance score");
    this.addDefault(defaults, Messages.PerformanceScore_Lag,
            "  The server is actively working to reduce lag - please be patient while automatic lag reduction takes effect.",
            null);
    this.addDefault(defaults, Messages.PerformanceScore_NoLag,
            "The server is running at normal speed.  If you're experiencing lag, check your graphics settings and internet connection.  ",
            null);
    this.addDefault(defaults, Messages.PlayerMoved, "Player moved.", null);
    this.addDefault(defaults, Messages.Lag, "lag", null);
    this.addDefault(defaults, Messages.RegionAlreadyNamed,
            "This region already has a name.  To REname, use /RenameRegion.", null);
    this.addDefault(defaults, Messages.HopperLimitReached,
            "To prevent server lag, hoppers are limited to {0} per chunk.", "0: maximum hoppers per chunk");
    this.addDefault(defaults, Messages.OutsideWorldBorder,
            "The region you are attempting to teleport to is outside the world border.", null);
    this.addDefault(defaults, Messages.Wilderness, "Wilderness", null);

    //load the config file
    FileConfiguration config = YamlConfiguration.loadConfiguration(new File(messagesFilePath));

    //for each message ID
    for (int i = 0; i < messageIDs.length; i++) {
        //get default for this message
        Messages messageID = messageIDs[i];
        CustomizableMessage messageData = defaults.get(messageID.name());

        //if default is missing, log an error and use some fake data for now so that the plugin can run
        if (messageData == null) {
            PopulationDensity.AddLogEntry(
                    "Missing message for " + messageID.name() + ".  Please contact the developer.");
            messageData = new CustomizableMessage(messageID,
                    "Missing message!  ID: " + messageID.name() + ".  Please contact a server admin.", null);
        }

        //read the message from the file, use default if necessary
        this.messages[messageID.ordinal()] = config.getString("Messages." + messageID.name() + ".Text",
                messageData.text);
        config.set("Messages." + messageID.name() + ".Text", this.messages[messageID.ordinal()]);

        if (messageData.notes != null) {
            messageData.notes = config.getString("Messages." + messageID.name() + ".Notes", messageData.notes);
            config.set("Messages." + messageID.name() + ".Notes", messageData.notes);
        }
    }

    //save any changes
    try {
        config.save(DataStore.messagesFilePath);
    } catch (IOException exception) {
        PopulationDensity.AddLogEntry(
                "Unable to write to the configuration file at \"" + DataStore.messagesFilePath + "\"");
    }

    defaults.clear();
    System.gc();
}

From source file:org.jasig.portal.layout.simple.RDBMUserLayoutStore.java

protected Document getPersonalUserLayout(final IPerson person, final IUserProfile profile) {
    final LocaleManager localeManager = profile.getLocaleManager();

    return jdbcOperations.execute(new ConnectionCallback<Document>() {
        @Override// w ww .j av  a 2 s . c o  m
        public Document doInConnection(Connection con) throws SQLException, DataAccessException {

            ResultSet rs;
            int userId = person.getID();
            final int realUserId = userId;
            Document doc = DocumentFactory.getThreadDocument();
            Element root = doc.createElement("layout");
            final Statement stmt = con.createStatement();
            // A separate statement is needed so as not to interfere with ResultSet
            // of statements used for queries
            Statement insertStmt = con.createStatement();
            try {
                long startTime = System.currentTimeMillis();
                // eventually, we need to fix template layout implementations so you can just do this:
                //        int layoutId=profile.getLayoutId();
                // but for now:
                int layoutId = getLayoutID(userId, profile.getProfileId());

                if (layoutId == 0) { // First time, grab the default layout for this user
                    final Tuple<Integer, Integer> userLayoutIds = transactionOperations
                            .execute(new TransactionCallback<Tuple<Integer, Integer>>() {
                                @Override
                                public Tuple<Integer, Integer> doInTransaction(TransactionStatus status) {
                                    return jdbcOperations
                                            .execute(new ConnectionCallback<Tuple<Integer, Integer>>() {
                                                @Override
                                                public Tuple<Integer, Integer> doInConnection(Connection con)
                                                        throws SQLException, DataAccessException {

                                                    int newLayoutId;
                                                    int newUserId;

                                                    String sQuery = "SELECT USER_DFLT_USR_ID, USER_DFLT_LAY_ID FROM UP_USER WHERE USER_ID="
                                                            + realUserId;
                                                    if (log.isDebugEnabled())
                                                        log.debug("RDBMUserLayoutStore::getUserLayout(): "
                                                                + sQuery);
                                                    ResultSet rs = stmt.executeQuery(sQuery);
                                                    try {
                                                        boolean hasRow = rs.next();
                                                        newUserId = rs.getInt(1);
                                                        newLayoutId = rs.getInt(2);
                                                    } finally {
                                                        rs.close();
                                                    }

                                                    // Make sure the next struct id is set in case the user adds a channel
                                                    sQuery = "SELECT NEXT_STRUCT_ID FROM UP_USER WHERE USER_ID="
                                                            + newUserId;
                                                    if (log.isDebugEnabled())
                                                        log.debug("RDBMUserLayoutStore::getUserLayout(): "
                                                                + sQuery);
                                                    int nextStructId;
                                                    rs = stmt.executeQuery(sQuery);
                                                    try {
                                                        boolean hasRow = rs.next();
                                                        nextStructId = rs.getInt(1);
                                                    } finally {
                                                        rs.close();
                                                    }

                                                    int realNextStructId = 0;

                                                    if (realUserId != newUserId) {
                                                        // But never make the existing value SMALLER, change it only to make it LARGER
                                                        // (so, get existing value)
                                                        sQuery = "SELECT NEXT_STRUCT_ID FROM UP_USER WHERE USER_ID="
                                                                + realUserId;
                                                        if (log.isDebugEnabled())
                                                            log.debug("RDBMUserLayoutStore::getUserLayout(): "
                                                                    + sQuery);
                                                        rs = stmt.executeQuery(sQuery);
                                                        try {
                                                            boolean hasRow = rs.next();
                                                            realNextStructId = rs.getInt(1);
                                                        } finally {
                                                            rs.close();
                                                        }
                                                    }

                                                    if (nextStructId > realNextStructId) {
                                                        sQuery = "UPDATE UP_USER SET NEXT_STRUCT_ID="
                                                                + nextStructId + " WHERE USER_ID=" + realUserId;
                                                        if (log.isDebugEnabled())
                                                            log.debug("RDBMUserLayoutStore::getUserLayout(): "
                                                                    + sQuery);
                                                        stmt.executeUpdate(sQuery);
                                                    }

                                                    return new Tuple<Integer, Integer>(newUserId, newLayoutId);

                                                }
                                            });
                                }
                            });

                    userId = userLayoutIds.first;
                    layoutId = userLayoutIds.second;
                }

                int firstStructId = -1;

                //Flags to enable a default layout lookup if it's needed
                boolean foundLayout = false;
                boolean triedDefault = false;

                //This loop is used to ensure a layout is found for a user. It tries
                //looking up the layout for the current userID. If one isn't found
                //the userID is replaced with the template user ID for this user and
                //the layout is searched for again. This loop should only ever loop once.
                do {
                    String sQuery = "SELECT INIT_STRUCT_ID FROM UP_USER_LAYOUT WHERE USER_ID=" + userId
                            + " AND LAYOUT_ID = " + layoutId;
                    if (log.isDebugEnabled())
                        log.debug("RDBMUserLayoutStore::getUserLayout(): " + sQuery);
                    rs = stmt.executeQuery(sQuery);
                    try {
                        if (rs.next()) {
                            firstStructId = rs.getInt(1);
                        } else {
                            throw new RuntimeException(
                                    "RDBMUserLayoutStore::getUserLayout(): No INIT_STRUCT_ID in UP_USER_LAYOUT for USER_ID: "
                                            + userId + " and LAYOUT_ID: " + layoutId);
                        }
                    } finally {
                        rs.close();
                    }

                    String sql;
                    if (localeAware) {
                        // This needs to be changed to get the localized strings
                        sql = "SELECT ULS.STRUCT_ID,ULS.NEXT_STRUCT_ID,ULS.CHLD_STRUCT_ID,ULS.CHAN_ID,ULS.NAME,ULS.TYPE,ULS.HIDDEN,"
                                + "ULS.UNREMOVABLE,ULS.IMMUTABLE";
                    } else {
                        sql = "SELECT ULS.STRUCT_ID,ULS.NEXT_STRUCT_ID,ULS.CHLD_STRUCT_ID,ULS.CHAN_ID,ULS.NAME,ULS.TYPE,ULS.HIDDEN,"
                                + "ULS.UNREMOVABLE,ULS.IMMUTABLE";
                    }
                    if (databaseMetadata.supportsOuterJoins()) {
                        sql += ",USP.STRUCT_PARM_NM,USP.STRUCT_PARM_VAL FROM "
                                + databaseMetadata.getJoinQuery().getQuery("layout");
                    } else {
                        sql += " FROM UP_LAYOUT_STRUCT ULS WHERE ";
                    }
                    sql += " ULS.USER_ID=" + userId + " AND ULS.LAYOUT_ID=" + layoutId
                            + " ORDER BY ULS.STRUCT_ID";
                    if (log.isDebugEnabled())
                        log.debug("RDBMUserLayoutStore::getUserLayout(): " + sql);
                    rs = stmt.executeQuery(sql);

                    //check for rows in the result set
                    foundLayout = rs.next();

                    if (!foundLayout && !triedDefault && userId == realUserId) {
                        //If we didn't find any rows and we haven't tried the default user yet
                        triedDefault = true;
                        rs.close();

                        //Get the default user ID and layout ID
                        sQuery = "SELECT USER_DFLT_USR_ID, USER_DFLT_LAY_ID FROM UP_USER WHERE USER_ID="
                                + userId;
                        if (log.isDebugEnabled())
                            log.debug("RDBMUserLayoutStore::getUserLayout(): " + sQuery);
                        rs = stmt.executeQuery(sQuery);
                        try {
                            rs.next();
                            userId = rs.getInt(1);
                            layoutId = rs.getInt(2);
                        } finally {
                            rs.close();
                        }
                    } else {
                        //We tried the default or actually found a layout
                        break;
                    }
                } while (!foundLayout);

                HashMap layoutStructure = new HashMap();
                StringBuffer structChanIds = new StringBuffer();

                try {
                    int lastStructId = 0;
                    LayoutStructure ls = null;
                    String sepChar = "";
                    if (foundLayout) {
                        int structId = rs.getInt(1);
                        // Result Set returns 0 by default if structId was null
                        // Except if you are using poolman 2.0.4 in which case you get -1 back
                        if (rs.wasNull()) {
                            structId = 0;
                        }
                        readLayout: while (true) {

                            int nextId = rs.getInt(2);
                            if (rs.wasNull()) {
                                nextId = 0;
                            }
                            int childId = rs.getInt(3);
                            if (rs.wasNull()) {
                                childId = 0;
                            }
                            int chanId = rs.getInt(4);
                            if (rs.wasNull()) {
                                chanId = 0;
                            }
                            String temp5 = rs.getString(5); // Some JDBC drivers require columns accessed in order
                            String temp6 = rs.getString(6); // Access 5 and 6 now, save till needed.

                            // uPortal i18n
                            int name_index, value_index;
                            if (localeAware) {
                                Locale[] locales = localeManager.getLocales();
                                String locale = locales[0].toString();
                                ls = new LayoutStructure(structId, nextId, childId, chanId, rs.getString(7),
                                        rs.getString(8), rs.getString(9), locale);
                                name_index = 10;
                                value_index = 11;
                            } else {
                                ls = new LayoutStructure(structId, nextId, childId, chanId, rs.getString(7),
                                        rs.getString(8), rs.getString(9));
                                name_index = 10;
                                value_index = 11;
                            }
                            layoutStructure.put(new Integer(structId), ls);
                            lastStructId = structId;
                            if (!ls.isChannel()) {
                                ls.addFolderData(temp5, temp6); // Plug in saved column values
                            }
                            if (databaseMetadata.supportsOuterJoins()) {
                                do {
                                    String name = rs.getString(name_index);
                                    String value = rs.getString(value_index); // Oracle JDBC requires us to do this for longs
                                    if (name != null) { // may not be there because of the join
                                        ls.addParameter(name, value);
                                    }
                                    if (!rs.next()) {
                                        break readLayout;
                                    }
                                    structId = rs.getInt(1);
                                    if (rs.wasNull()) {
                                        structId = 0;
                                    }
                                } while (structId == lastStructId);
                            } else { // Do second SELECT later on for structure parameters
                                if (ls.isChannel()) {
                                    structChanIds.append(sepChar + ls.getChanId());
                                    sepChar = ",";
                                }
                                if (rs.next()) {
                                    structId = rs.getInt(1);
                                    if (rs.wasNull()) {
                                        structId = 0;
                                    }
                                } else {
                                    break readLayout;
                                }
                            }
                        } // while
                    }
                } finally {
                    rs.close();
                }

                if (!databaseMetadata.supportsOuterJoins() && structChanIds.length() > 0) { // Pick up structure parameters
                    // first, get the struct ids for the channels
                    String sql = "SELECT STRUCT_ID FROM UP_LAYOUT_STRUCT WHERE USER_ID=" + userId
                            + " AND LAYOUT_ID=" + layoutId + " AND CHAN_ID IN (" + structChanIds.toString()
                            + ") ORDER BY STRUCT_ID";

                    if (log.isDebugEnabled())
                        log.debug("RDBMUserLayoutStore::getUserLayout(): " + sql);
                    StringBuffer structIdsSB = new StringBuffer("");
                    String sep = "";
                    rs = stmt.executeQuery(sql);
                    try {
                        // use the results to build a correct list of struct ids to look for
                        while (rs.next()) {
                            structIdsSB.append(sep + rs.getString(1));
                            sep = ",";
                        } // while
                    } finally {
                        rs.close();
                    } // be a good doobie

                    sql = "SELECT STRUCT_ID, STRUCT_PARM_NM,STRUCT_PARM_VAL FROM UP_LAYOUT_PARAM WHERE USER_ID="
                            + userId + " AND LAYOUT_ID=" + layoutId + " AND STRUCT_ID IN ("
                            + structIdsSB.toString() + ") ORDER BY STRUCT_ID";
                    if (log.isDebugEnabled())
                        log.debug("RDBMUserLayoutStore::getUserLayout(): " + sql);
                    rs = stmt.executeQuery(sql);
                    try {
                        if (rs.next()) {
                            int structId = rs.getInt(1);
                            readParm: while (true) {
                                LayoutStructure ls = (LayoutStructure) layoutStructure
                                        .get(new Integer(structId));
                                int lastStructId = structId;
                                do {
                                    ls.addParameter(rs.getString(2), rs.getString(3));
                                    if (!rs.next()) {
                                        break readParm;
                                    }
                                } while ((structId = rs.getInt(1)) == lastStructId);
                            }
                        }
                    } finally {
                        rs.close();
                    }
                }

                if (layoutStructure.size() > 0) { // We have a layout to work with
                    createLayout(layoutStructure, doc, root, firstStructId);
                    layoutStructure.clear();

                    if (log.isDebugEnabled()) {
                        long stopTime = System.currentTimeMillis();
                        log.debug("RDBMUserLayoutStore::getUserLayout(): Layout document for user " + userId
                                + " took " + (stopTime - startTime) + " milliseconds to create");
                    }

                    doc.appendChild(root);
                }
            } finally {
                stmt.close();
                insertStmt.close();
            }
            return doc;
        }
    });
}

From source file:sce.RESTCheckSLAJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    Connection conn = null;/*from w  ww  .j  a v  a  2s  . co  m*/
    try {
        //required parameters #url, #slaId, #slaTimestamp
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String url1 = jobDataMap.getString("#url"); // e.g. http://kb-read:icaro@192.168.0.106:8080/IcaroKB/sparql
        if (url1 == null) {
            throw new JobExecutionException("#url parameter must be not null");
        }
        String slaId = jobDataMap.getString("#slaId");
        if (slaId == null) {
            throw new JobExecutionException("#slaId parameter must be not null");
        }
        String slaTimestamp = jobDataMap.getString("#slaTimestamp"); // e.g. 2014-09-10T16:30:00
        //if timestamp is not defined, use current
        if (slaTimestamp == null) {
            //throw new JobExecutionException("#slaTimestamp parameter must be not null");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            slaTimestamp = sdf.format(new Date());
        }
        //first SPARQL query to retrieve services, metrics and thresholds in the SLA
        String url = url1 + "?query=" + URLEncoder.encode(getSPARQLQuery(slaId), "UTF-8");
        URL u = new URL(url);
        final String usernamePassword = u.getUserInfo();
        if (usernamePassword != null) {
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(usernamePassword.split(":")[0],
                            usernamePassword.split(":")[1].toCharArray());
                }
            });
        }
        this.urlConnection = u.openConnection();
        this.urlConnection.setRequestProperty("Accept", "application/sparql-results+json");
        HashMap<String, Object> res = new ObjectMapper().readValue(urlConnection.getInputStream(),
                HashMap.class);
        HashMap<String, Object> r = (HashMap<String, Object>) res.get("results");
        ArrayList<Object> list = (ArrayList<Object>) r.get("bindings");
        int bindings = list.size();
        ArrayList<String[]> lst = new ArrayList<>();
        for (Object obj : list) {
            HashMap<String, Object> o = (HashMap<String, Object>) obj;
            String mn = (String) ((HashMap<String, Object>) o.get("mn")).get("value");
            String v = (String) ((HashMap<String, Object>) o.get("v")).get("value");
            String sm = (String) ((HashMap<String, Object>) o.get("sm")).get("value");
            String p = (String) ((HashMap<String, Object>) o.get("p")).get("value");
            String callUrl = (String) ((HashMap<String, Object>) o.get("act")).get("value");
            String bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value");
            lst.add(new String[] { mn, v, sm, p, callUrl, bc });
        }

        //second SPARQL query to retrieve alerts for SLA
        url = url1 + "?query=" + URLEncoder.encode(getAlertsForSLA(lst, slaTimestamp), "UTF-8");
        u = new URL(url);
        //java.io.FileWriter fstream = new java.io.FileWriter("/var/www/html/sce/log.txt", false);
        //java.io.BufferedWriter out = new java.io.BufferedWriter(fstream);
        //out.write(getAlertsForSLA(lst, slaTimestamp));
        //out.close();
        this.urlConnection = u.openConnection();
        this.urlConnection.setRequestProperty("Accept", "application/sparql-results+json");

        //format the result
        HashMap<String, Object> alerts = new ObjectMapper().readValue(urlConnection.getInputStream(),
                HashMap.class);
        HashMap<String, Object> r1 = (HashMap<String, Object>) alerts.get("results");
        ArrayList<Object> list1 = (ArrayList<Object>) r1.get("bindings");
        //ArrayList<String[]> lst1 = new ArrayList<>();
        //int counter = 0;
        String vv_temp;
        String result = "";

        //LOAD QUARTZ PROPERTIES
        Properties prop = new Properties();
        prop.load(this.getClass().getResourceAsStream("quartz.properties"));

        //MYSQL CONNECTION
        conn = Main.getConnection();
        // conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); // use for transactions and at the end call conn.commit() conn.close()
        int counter = 0;

        //SET timestamp FOR MYSQL ROW
        Date dt = new java.util.Date();
        SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = sdf.format(dt);

        //Hashmap to store callUrls to be called in case of alarm
        HashMap<String, Integer> callUrlMap = new HashMap<>();

        // JSON to be sent to the SM
        JSONArray jsonArray = new JSONArray();
        boolean notify = false; // whether notify the SM or not

        // Business Configuration
        String bc = "";

        for (Object obj : list1) {
            //JSON to insert into database
            //JSONArray jsonArray = new JSONArray();
            boolean alarm; //set to true if there is an alarm on sla

            HashMap<String, Object> o = (HashMap<String, Object>) obj;
            String y = (String) ((HashMap<String, Object>) o.get("y")).get("value"); //metric
            String mn = (String) ((HashMap<String, Object>) o.get("mn")).get("value"); //metric_name
            String mu = (String) ((HashMap<String, Object>) o.get("mu")).get("value"); //metric_unit
            String mt = (String) ((HashMap<String, Object>) o.get("mt")).get("value"); //timestamp
            //String sm = (String) ((HashMap<String, Object>) o.get("sm")).get("value");
            String vm = (String) ((HashMap<String, Object>) o.get("vm")).get("value"); //virtual_machine
            String vmn = (String) ((HashMap<String, Object>) o.get("vmn")).get("value"); //virtual_machine_name
            String hm = o.get("hm") != null ? (String) ((HashMap<String, Object>) o.get("hm")).get("value")
                    : ""; //host_machine
            //String na = (String) ((HashMap<String, Object>) o.get("na")).get("value");
            //String ip = (String) ((HashMap<String, Object>) o.get("ip")).get("value");
            String v = (String) ((HashMap<String, Object>) o.get("v")).get("value"); //threshold
            String p = (String) ((HashMap<String, Object>) o.get("p")).get("value"); //relation (<,>,=)
            vv_temp = (String) ((HashMap<String, Object>) o.get("vv")).get("value"); //value
            String callUrl = (String) ((HashMap<String, Object>) o.get("callUrl")).get("value"); //call url
            bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value"); //business configuration

            /*JSONObject object = new JSONObject();
             object.put("metric", y);
             object.put("metric_name", mn);
             object.put("metric_unit", mu);
             object.put("timestamp", mt);
             //object.put("service", sm);
             object.put("virtual_machine", vm);
             object.put("virtual_machine_name", vmn);
             object.put("host_machine", hm);
             object.put("value", vv_temp);
             object.put("relation", getProperty(p));
             object.put("threshold", v);
             jsonArray.add(object);*/
            //CHECK IF THE SLA IS VIOLATED
            alarm = checkSLA(Double.parseDouble(vv_temp), Double.parseDouble(v), p);

            // if alarm is true, then put the callUrl in a HashMap
            // and build the json object to be added to the json array to be sent to the SM
            if (alarm) {
                callUrlMap.put(callUrl, 1);

                notify = true;
                JSONObject object = new JSONObject();
                object.put("sla", slaId);
                object.put("metric", y);
                object.put("metric_name", mn);
                object.put("metric_unit", mu);
                object.put("metric_timestamp", mt);
                object.put("virtual_machine", vm);
                object.put("virtual_machine_name", vmn);
                object.put("host_machine", hm);
                object.put("value", vv_temp);
                object.put("relation", p.substring(p.lastIndexOf("#") + 1));
                object.put("threshold", v);
                object.put("call_url", callUrl);
                jsonArray.add(object);
            }

            //INSERT THE DATA INTO DATABASE
            PreparedStatement preparedStatement = conn.prepareStatement(
                    "INSERT INTO quartz.QRTZ_SPARQL (timestamp, sla, alarm, metric, metric_name, metric_unit, metric_timestamp, virtual_machine, virtual_machine_name, host_machine, value, relation, threshold, call_url, business_configuration) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE timestamp=?");
            preparedStatement.setString(1, timestamp); // date
            preparedStatement.setString(2, slaId); // sla
            preparedStatement.setInt(3, alarm ? 1 : 0); // alarm
            preparedStatement.setString(4, y); // metric
            preparedStatement.setString(5, mn); // metric_name
            preparedStatement.setString(6, mu); // metric_unit
            preparedStatement.setString(7, mt); // metric_timestamp (e.g., 2014-12-01T16:14:00)
            preparedStatement.setString(8, vm); // virtual_machine
            preparedStatement.setString(9, vmn); // virtual_machine_name
            preparedStatement.setString(10, hm); // host_machine
            preparedStatement.setString(11, vv_temp); // value
            preparedStatement.setString(12, p.substring(p.lastIndexOf("#") + 1)); //relation (e.g., http://www.cloudicaro.it/cloud_ontology/core#hasMetricValueLessThan)
            preparedStatement.setString(13, v); // threshold
            preparedStatement.setString(14, callUrl); // callUrl
            preparedStatement.setString(15, bc); // business configuration
            preparedStatement.setString(16, timestamp); // date
            preparedStatement.executeUpdate();
            preparedStatement.close();

            //lst1.add(new String[]{y, mt, vv_temp});
            result += "\nService Metric: " + y + "\n";
            result += "\nMetric Name: " + mn + "\n";
            result += "\nMetric Unit: " + mu + "\n";
            result += "Timestamp: " + mt + "\n";
            //result += "Service: " + sm + "\n";
            result += "Virtual Machine: " + vm + "\n";
            result += "Virtual Machine Name: " + vmn + "\n";
            result += "Host Machine: " + hm + "\n";
            //result += "Network Adapter: " + na + "\n";
            //result += "IP: " + ip + "\n";
            result += "Value" + (counter + 1) + ": " + vv_temp + "\n";
            result += "Threshold: " + getProperty(lst.get(counter)[3]) + " " + lst.get(counter)[1] + "\n";
            result += "Call Url: " + callUrl + "\n";
            result += "Business Configuration: " + bc + "\n";

            counter++;
        }

        // if the notify is true, then send the JSON to the SM
        if (notify) {
            JSONObject object = new JSONObject();
            object.put("metric", jsonArray);
            object.put("business_configuration", bc);
            object.put("timestamp", timestamp);
            object.put("sla", slaId);
            sendPostRequest(object.toJSONString());
        }

        //call the callUrls in the HashMap
        Iterator it = callUrlMap.entrySet().iterator();
        while (it.hasNext()) {
            try {
                Map.Entry pairs = (Map.Entry) it.next();
                URL u_callUrl = new URL((String) pairs.getKey());
                //get user credentials from URL, if present
                final String usernamePasswordCallUrl = u_callUrl.getUserInfo();
                //set the basic authentication credentials for the connection
                if (usernamePasswordCallUrl != null) {
                    Authenticator.setDefault(new Authenticator() {
                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(usernamePasswordCallUrl.split(":")[0],
                                    usernamePasswordCallUrl.split(":")[1].toCharArray());
                        }
                    });
                }
                //call the callUrl
                URLConnection connection = u_callUrl.openConnection();
                getUrlContents(connection);
            } catch (Exception e) {
            }
            it.remove(); // avoids a ConcurrentModificationException

        }

        //clean the callUrl map
        callUrlMap.clear();

        //set the result to the job execution context, to be able to retrieve it later (e.g., with a job listener)
        context.setResult(result);

        if (jobDataMap.containsKey("#notificationEmail")) {
            sendEmail(context, jobDataMap.getString("#notificationEmail"));
        }
        jobChain(context);
    } catch (MalformedURLException ex) {
        Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (IOException | SQLException ex) {
        Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (!conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.krawler.spring.hrms.common.hrmsCommonController.java

public ModelAndView exportUserInfo(HttpServletRequest request, HttpServletResponse response) {
    KwlReturnObject kmsg = null;/*from w  w  w .j  a  v a2s  .  c o  m*/
    JSONObject jobj = new JSONObject();
    JSONArray jarr = new JSONArray();
    JSONObject countobj = new JSONObject();
    JSONObject jobj1 = new JSONObject();
    try {
        String Searchjson = request.getParameter("searchJson");
        String appendCase = "and";
        String companyid = sessionHandlerImplObj.getCompanyid(request);
        String lid = StringUtil.checkForNull(request.getParameter("lid"));
        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        ArrayList filter_names = new ArrayList(
                Arrays.asList("ua.user.company.companyID", "ua.user.deleteflag"));
        ArrayList filter_values = new ArrayList(Arrays.asList(companyid, 0));
        requestParams.put("ss", StringUtil.checkForNull(request.getParameter("ss")));
        requestParams.put("allflag", true);
        requestParams.put("searchcol", new String[] { "u.firstName", "u.lastName", "ua.department.value",
                "ua.designationid.value", "ua.role.name", "u.emailID" });
        if (request.getParameter("combo") != null) {
            requestParams.put("combo", request.getParameter("combo"));
        } else {
            requestParams.put("combo", "");
        }
        StringUtil.checkpaging(requestParams, request);
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        if (!StringUtil.isNullOrEmpty(request.getParameter("stdate"))) {
            filter_names.add(">=emp.joindate");
            filter_values.add(new Date(df.format(new Date(request.getParameter("stdate")))));
            filter_names.add("<=emp.joindate");
            filter_values.add(new Date(df.format(new Date(request.getParameter("enddate")))));
        }

        if (!StringUtil.isNullOrEmpty(Searchjson)) {
            getMyAdvanceSearchparams(Searchjson, filter_names);
            insertParamAdvanceSearchString(filter_values, Searchjson);
        }
        requestParams.put("filter_names", filter_names);
        requestParams.put("filter_values", filter_values);

        kmsg = hrmsCommonDAOObj.getUserDetailsHrms(requestParams);
        List lst = kmsg.getEntityList();
        jarr = kwlCommonTablesDAOObj.getDetailsJson(lst, 0, "com.krawler.common.admin.User");

        int count = 0;
        for (int ctr = 0; ctr < jarr.length(); ctr++) {
            jobj = jarr.getJSONObject(ctr);
            Object[] row = (Object[]) lst.get(ctr);
            User u = (User) jobj.get("instance");
            Useraccount ua = (Useraccount) kwlCommonTablesDAOObj
                    .getObject("com.krawler.common.admin.Useraccount", row[0].toString());
            if (row[1] != null) {
                Empprofile e = (Empprofile) kwlCommonTablesDAOObj.getObject("com.krawler.hrms.ess.Empprofile",
                        row[1].toString());
                if (!StringUtil.isNullOrEmpty(e.getStatus())) {
                    jobj.put("status", messageSource.getMessage("hrms.administration." + e.getStatus(), null,
                            e.getStatus(), RequestContextUtils.getLocale(request)));
                } else {
                    jobj.put("status", messageSource.getMessage("hrms.administration.Pending", null, "Pending",
                            RequestContextUtils.getLocale(request)));
                }
                jobj.put("dob", e.getDoB() == null ? "" : e.getDoB());
                jobj.put("gender", e.getGender() == null ? "" : e.getGender());
                jobj.put("bloodgrp", e.getBloodgrp() == null ? "" : e.getBloodgrp());
                jobj.put("fathername", e.getFathername() == null ? "" : e.getFathername());
                jobj.put("mothername", e.getMothername() == null ? "" : e.getMothername());
                jobj.put("passportno", e.getPassportno() == null ? "" : e.getPassportno());
                jobj.put("joindate", e.getJoindate() == null ? "" : e.getJoindate());
                jobj.put("confirmdate", e.getConfirmdate() == null ? "" : e.getConfirmdate());
                jobj.put("middlename", e.getMiddlename() == null ? "" : e.getMiddlename());
                jobj.put("keyskills", e.getKeyskills() == null ? "" : e.getKeyskills());
                jobj.put("wkstarttime", e.getWkstarttime() == null ? "" : e.getWkstarttime());
                jobj.put("wkendtime", e.getWkendtime() == null ? "" : e.getWkendtime());
                jobj.put("weekoff", e.getWeekoff() == null ? "" : e.getWeekoff());
                jobj.put("pannumber", e.getPanno() == null ? "" : e.getPanno());
                jobj.put("updatedon", e.getUpdated_on() == null ? "" : e.getUpdated_on());
            } else {
                jobj.put("status", messageSource.getMessage("hrms.recruitment.InComplete", null, "Incomplete",
                        RequestContextUtils.getLocale(request)));
                jobj.put("dob", "");
                jobj.put("gender", "");
                jobj.put("bloodgrp", "");
                jobj.put("fathername", "");
                jobj.put("mothername", "");
                jobj.put("passportno", "");
                jobj.put("joindate", "");
                jobj.put("confirmdate", "");
                jobj.put("middlename", "");
                jobj.put("keyskills", "");
                jobj.put("wkstarttime", "");
                jobj.put("wkendtime", "");
                jobj.put("weekoff", "");
            }
            jobj.put("department", (ua.getDepartment() == null ? "" : ua.getDepartment().getId()));
            jobj.put("departmentname", (ua.getDepartment() == null ? "" : ua.getDepartment().getValue()));
            jobj.put("role", (ua.getRole() == null ? "" : ua.getRole().getID()));
            String name = "";
            if (ua.getRole() != null && ua.getRole().getCompany() != null) {
                name = ua.getRole().getName();
            } else {
                name = messageSource.getMessage("hrms.common.role." + ua.getRole().getID(), null,
                        ua.getRole().getName(), RequestContextUtils.getLocale(request));
            }
            jobj.put("rolename", (ua.getRole() == null ? "" : name));
            jobj.put("username", u.getUserLogin().getUserName());
            jobj.put("fullname", u.getFirstName() + " " + (u.getLastName() == null ? "" : u.getLastName()));
            jobj.put("lastlogin",
                    (u.getUserLogin().getLastActivityDate() == null ? ""
                            : sessionHandlerImplObj.getDateFormatter(request)
                                    .format(u.getUserLogin().getLastActivityDate())));
            jobj.put("designation", ua.getDesignationid() == null ? "" : ua.getDesignationid().getValue());
            jobj.put("designationid", ua.getDesignationid() == null ? "" : ua.getDesignationid().getId());
            jobj.put("templateid", ua.getTemplateid() != null ? ua.getTemplateid() : "");
            jobj.put("salary", ua.getSalary() != null ? ua.getSalary() : "");
            jobj.put("accno", ua.getAccno() != null ? ua.getAccno() : "");
            jobj.put("createdon", ua.getUser().getCreatedon() != null ? ua.getUser().getCreatedon() : "");
            requestParams.clear();
            requestParams.put("companyid", sessionHandlerImplObj.getCompanyid(request));
            requestParams.put("empid", ua.getEmployeeid());
            KwlReturnObject result;
            //                KwlReturnObject result = profileHandlerDAOObj.getEmpidFormatEdit(requestParams);
            if (ua.getEmployeeIdFormat() == null) {
                jobj.put("employeeid", ua.getEmployeeid() == null ? ""
                        : profileHandlerDAOObj.getEmpidFormatEdit(requestParams).getEntityList().get(0));
            } else {
                requestParams.put("standardEmpId", profileHandlerDAOObj.getEmpidFormatEdit(requestParams)
                        .getEntityList().get(0).toString());
                requestParams.put("employeeIdFormat", ua.getEmployeeIdFormat());
                jobj.put("employeeid", profileHandlerDAOObj.getNewEmployeeIdFormat(requestParams));
            }
            requestParams.clear();
            filter_names.add("assignemp.userID");
            filter_values.add(u.getUserID());

            filter_names.add("managerstatus");
            filter_values.add(1);

            requestParams.put("filter_names",
                    Arrays.asList("assignemp.userID", "managerstatus", "assignman.deleteflag"));
            requestParams.put("filter_values", Arrays.asList(u.getUserID(), 1, 0));

            result = hrmsCommonDAOObj.getAssignmanager(requestParams);
            List lst1 = result.getEntityList();
            Iterator itr1 = lst1.iterator();

            if (itr1.hasNext()) {
                String manager = "";
                while (itr1.hasNext()) {
                    Assignmanager asm = (Assignmanager) itr1.next();
                    if (asm.getAssignman() != null) {
                        jobj.append("managerid", asm.getAssignman().getUserID());
                        manager += asm.getAssignman().getFirstName() + " " + asm.getAssignman().getLastName()
                                + ",";
                    }
                }
                jobj.put("manager", manager.substring(0, manager.length() - 1));
            } else {
                jobj.put("manager", " ");
                jobj.put("managerid", " ");
            }

            requestParams.clear();
            filter_names.clear();
            filter_values.clear();
            filter_names.add("employee.userID");
            filter_values.add(u.getUserID());

            filter_names.add("reviewer.deleteflag");
            filter_values.add(0);

            filter_names.add("reviewerstatus");
            filter_values.add(1);

            requestParams.put("filter_names", filter_names);
            requestParams.put("filter_values", filter_values);

            result = hrmsCommonDAOObj.getAssignreviewer(requestParams);
            lst1 = result.getEntityList();
            itr1 = lst1.iterator();
            if (itr1.hasNext()) {
                String reviewer = "";
                while (itr1.hasNext()) {
                    Assignreviewer rev = (Assignreviewer) itr1.next();
                    if (rev.getReviewer() != null) {
                        jobj.append("reviewerid", rev.getReviewer().getUserID());
                        reviewer += rev.getReviewer().getFirstName() + " " + rev.getReviewer().getLastName()
                                + ",";
                    }
                }
                jobj.put("reviewer", reviewer.substring(0, reviewer.length() - 1));
            } else {
                jobj.put("reviewer", " ");
                jobj.put("reviewerid", " ");
            }

            jarr.put(ctr, jobj);
            count++;
        }

        countobj.put("data", jarr);
        countobj.put("count", kmsg.getRecordTotalCount());
        exportDAOImplObj.processRequest(request, response, countobj);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new ModelAndView("jsonView", "model", jobj.toString());
}