Example usage for java.util Map containsValue

List of usage examples for java.util Map containsValue

Introduction

In this page you can find the example usage for java.util Map containsValue.

Prototype

boolean containsValue(Object value);

Source Link

Document

Returns true if this map maps one or more keys to the specified value.

Usage

From source file:org.exist.xquery.xproc.XProcRunner.java

protected static boolean run(URI staticBaseURI, InputStream defaultIn, ByteArrayOutputStream byteStream,
        UserArgs userArgs, XProcConfiguration config)
        throws SaxonApiException, IOException, URISyntaxException {
    XProcRuntime runtime = new XProcRuntime(config);

    if (staticBaseURI != null) {
        runtime.setURIResolver(new ExternalResolver(staticBaseURI.toString()));
        //            runtime.setStaticBaseURI(staticBaseURI);
        //            runtime.setBaseURI(staticBaseURI);
    }//from w ww.  j  a  va2  s .c o m

    boolean debug = config.debug;

    XPipeline pipeline = null;

    if (userArgs.getPipeline() != null) {
        pipeline = runtime.load(userArgs.getPipeline());
    } else if (userArgs.hasImplicitPipeline()) {
        XdmNode implicitPipeline = userArgs.getImplicitPipeline(runtime);

        if (debug) {
            System.err.println("Implicit pipeline:");

            Serializer serializer = new Serializer();

            serializer.setOutputProperty(Serializer.Property.INDENT, "yes");
            serializer.setOutputProperty(Serializer.Property.METHOD, "xml");

            serializer.setOutputStream(System.err);

            S9apiUtils.serialize(runtime, implicitPipeline, serializer);
        }

        pipeline = runtime.use(implicitPipeline);
    } else if (config.pipeline != null) {
        XdmNode doc = config.pipeline.read();
        pipeline = runtime.use(doc);
    } else {
        throw new UnsupportedOperationException("Either a pipeline or libraries and / or steps must be given");
    }

    // Process parameters from the configuration...
    for (String port : config.params.keySet()) {
        Map<QName, String> parameters = config.params.get(port);
        setParametersOnPipeline(pipeline, port, parameters);
    }

    // Now process parameters from the command line...
    for (String port : userArgs.getParameterPorts()) {
        Map<QName, String> parameters = userArgs.getParameters(port);
        setParametersOnPipeline(pipeline, port, parameters);
    }

    Set<String> ports = pipeline.getInputs();
    Set<String> userArgsInputPorts = userArgs.getInputPorts();
    Set<String> cfgInputPorts = config.inputs.keySet();
    Set<String> allPorts = new HashSet<String>();
    allPorts.addAll(userArgsInputPorts);
    allPorts.addAll(cfgInputPorts);

    // map a given input without port specification to the primary non-parameter input implicitly
    for (String port : ports) {
        if (!allPorts.contains(port) && allPorts.contains(null)
                && pipeline.getDeclareStep().getInput(port).getPrimary()
                && !pipeline.getDeclareStep().getInput(port).getParameterInput()) {

            if (userArgsInputPorts.contains(null)) {
                userArgs.setDefaultInputPort(port);
                allPorts.remove(null);
                allPorts.add(port);
            }
            break;
        }
    }

    for (String port : allPorts) {
        if (!ports.contains(port)) {
            throw new XProcException(
                    "There is a binding for the port '" + port + "' but the pipeline declares no such port.");
        }

        pipeline.clearInputs(port);

        if (userArgsInputPorts.contains(port)) {
            XdmNode doc = null;
            for (Input input : userArgs.getInputs(port)) {
                switch (input.getType()) {
                case XML:
                    switch (input.getKind()) {
                    case URI:
                        String uri = input.getUri();
                        if ("-".equals(uri)) {
                            throw new IOException("unsupported '-'");
                            //                                        doc = runtime.parse(new InputSource(System.in));
                        } else {
                            doc = runtime.parse(uri, staticBaseURI.toASCIIString());
                        }
                        break;

                    case INPUT_STREAM:
                        InputStream inputStream = input.getInputStream();
                        doc = runtime.parse(new InputSource(inputStream));
                        inputStream.close();
                        break;

                    default:
                        throw new UnsupportedOperationException(
                                format("Unsupported input kind '%s'", input.getKind()));
                    }
                    break;

                case DATA:
                    ReadableData rd;
                    switch (input.getKind()) {
                    case URI:
                        rd = new ReadableData(runtime, c_data, input.getUri(), input.getContentType());
                        doc = rd.read();
                        break;

                    case INPUT_STREAM:
                        InputStream inputStream = input.getInputStream();
                        rd = new ReadableData(runtime, c_data, inputStream, input.getContentType());
                        doc = rd.read();
                        inputStream.close();
                        break;

                    default:
                        throw new UnsupportedOperationException(
                                format("Unsupported input kind '%s'", input.getKind()));
                    }
                    break;

                default:
                    throw new UnsupportedOperationException(
                            format("Unsupported input type '%s'", input.getType()));
                }

                pipeline.writeTo(port, doc);
            }
        } else {
            for (ReadablePipe pipe : config.inputs.get(port)) {
                XdmNode doc = pipe.read();
                pipeline.writeTo(port, doc);
            }
        }
    }

    // Implicit binding for stdin?
    String implicitPort = null;
    for (String port : ports) {
        if (!allPorts.contains(port)) {
            if (pipeline.getDeclareStep().getInput(port).getPrimary()
                    && !pipeline.getDeclareStep().getInput(port).getParameterInput()) {
                implicitPort = port;
            }
        }
    }

    if (implicitPort != null && !pipeline.hasReadablePipes(implicitPort) && defaultIn != null) {
        //            throw new XProcException("no implicitPort or it is not readable.");
        XdmNode doc = runtime.parse(new InputSource(defaultIn));
        pipeline.writeTo(implicitPort, doc);
    }

    Map<String, Output> portOutputs = new HashMap<String, Output>();

    Map<String, Output> userArgsOutputs = userArgs.getOutputs();
    for (String port : pipeline.getOutputs()) {
        // Bind to "-" implicitly
        Output output = null;

        if (userArgsOutputs.containsKey(port)) {
            output = userArgsOutputs.get(port);
        } else if (config.outputs.containsKey(port)) {
            output = new Output(config.outputs.get(port));
        } else if (userArgsOutputs.containsKey(null)
                && pipeline.getDeclareStep().getOutput(port).getPrimary()) {
            // Bind unnamed port to primary output port
            output = userArgsOutputs.get(null);
        }

        // Look for explicit binding to "-"
        if ((output != null) && (output.getKind() == Kind.URI) && "-".equals(output.getUri())) {
            output = null;
        }

        portOutputs.put(port, output);
    }

    for (QName optname : config.options.keySet()) {
        RuntimeValue value = new RuntimeValue(config.options.get(optname), null, null);
        pipeline.passOption(optname, value);
    }

    for (QName optname : userArgs.getOptionNames()) {
        RuntimeValue value = new RuntimeValue(userArgs.getOption(optname), null, null);
        pipeline.passOption(optname, value);
    }

    pipeline.run();

    for (String port : pipeline.getOutputs()) {
        Output output;
        if (portOutputs.containsKey(port)) {
            output = portOutputs.get(port);
        } else {
            // You didn't bind it, and it isn't going to stdout, so it's going into the bit bucket.
            continue;
        }

        if ((output == null)
                || ((output.getKind() == OUTPUT_STREAM) && System.out.equals(output.getOutputStream()))) {
            finest(logger, null, "Copy output from " + port + " to stdout");
        } else {
            switch (output.getKind()) {
            case URI:
                finest(logger, null, "Copy output from " + port + " to " + output.getUri());
                break;

            case OUTPUT_STREAM:
                String outputStreamClassName = output.getOutputStream().getClass().getName();
                finest(logger, null, "Copy output from " + port + " to " + outputStreamClassName + " stream");
                break;

            default:
                throw new UnsupportedOperationException(
                        format("Unsupported output kind '%s'", output.getKind()));
            }
        }

        Serialization serial = pipeline.getSerialization(port);

        if (serial == null) {
            // Use the configuration options
            // FIXME: should each of these be considered separately?
            // FIXME: should there be command-line options to override these settings?
            serial = new Serialization(runtime, pipeline.getNode()); // The node's a hack
            for (String name : config.serializationOptions.keySet()) {
                String value = config.serializationOptions.get(name);

                if ("byte-order-mark".equals(name))
                    serial.setByteOrderMark("true".equals(value));
                if ("escape-uri-attributes".equals(name))
                    serial.setEscapeURIAttributes("true".equals(value));
                if ("include-content-type".equals(name))
                    serial.setIncludeContentType("true".equals(value));
                if ("indent".equals(name))
                    serial.setIndent("true".equals(value));
                if ("omit-xml-declaration".equals(name))
                    serial.setOmitXMLDeclaration("true".equals(value));
                if ("undeclare-prefixes".equals(name))
                    serial.setUndeclarePrefixes("true".equals(value));
                if ("method".equals(name))
                    serial.setMethod(new QName("", value));

                // FIXME: if ("cdata-section-elements".equals(name)) serial.setCdataSectionElements();
                if ("doctype-public".equals(name))
                    serial.setDoctypePublic(value);
                if ("doctype-system".equals(name))
                    serial.setDoctypeSystem(value);
                if ("encoding".equals(name))
                    serial.setEncoding(value);
                if ("media-type".equals(name))
                    serial.setMediaType(value);
                if ("normalization-form".equals(name))
                    serial.setNormalizationForm(value);
                if ("standalone".equals(name))
                    serial.setStandalone(value);
                if ("version".equals(name))
                    serial.setVersion(value);
            }
        }

        // I wonder if there's a better way...
        WritableDocument wd = null;
        if (output == null) {
            //wd = new EXistDocument(runtime, null, serial);
            wd = new WritableDocument(runtime, null, serial, byteStream);
        } else {
            switch (output.getKind()) {
            case URI:
                URI uri = new URI(output.getUri());

                String filename = uri.getPath();

                Resource resource = new Resource(filename);
                OutputStream outfile = resource.getOutputStream();

                //                        URI furi = new URI(output.getUri());
                //                        String filename = furi.getPath();
                //                        FileOutputStream outfile = new FileOutputStream(filename);

                wd = new WritableDocument(runtime, filename, serial, outfile);
                break;

            case OUTPUT_STREAM:
                OutputStream outputStream = output.getOutputStream();
                wd = new WritableDocument(runtime, null, serial, outputStream);
                break;

            default:
                throw new UnsupportedOperationException(
                        format("Unsupported output kind '%s'", output.getKind()));
            }
        }

        ReadablePipe rpipe = pipeline.readFrom(port);
        while (rpipe.moreDocuments()) {
            wd.write(rpipe.read());
        }

        if (output != null) {
            wd.close();
        }
    }

    return portOutputs.containsValue(null);
}

From source file:org.egov.egf.commons.EgovCommon.java

/**
 * @description -This method returns the number of payments, the total payment amount made, department wise as on a particular
 * date for a list of ProjectCode ids that is passed. NOTE - ASSUMPTION IS EJVs don't have partial payments and CJVs have only
 * 1 project code on debit side.// w  ww . java  2  s. c  o  m
 * @param entityList - Integer list containing ProjectCode ids.
 * @param asOnDate - The payments are considered from the beginning to asOnDate. Only fully approved payments are considered.
 * (including asOnDate)
 * @return -A Map containing the total count and total amount department wise. keys are 'count' , 'amount', 'department'
 * @throws ApplicationException - If anyone of the parameters is null or the ProjectCode ids list passed is empty. - If any id
 * passed is wrong.
 */
public Map<String, String> getPaymentInfoforProjectCodeByDepartment(final List<Long> projectCodeIdList,
        final Date asOnDate) throws ApplicationException {
    if (projectCodeIdList == null || projectCodeIdList.size() == 0)
        throw new ApplicationException("ProjectCode Id list is null or empty");
    if (asOnDate == null)
        throw new ApplicationException("asOnDate is null");
    final String strAsOnDate = Constants.DDMMYYYYFORMAT1.format(asOnDate);
    final Map<String, String> result = new HashMap<String, String>();

    final List<String> commaSeperatedEntitiesList = new ArrayList<String>();
    final List<List<Long>> limitedEntityList = new ArrayList<List<Long>>();
    String commaSeperatedEntities = "";
    List<Long> tempEntityIdList = new ArrayList<Long>();
    if (LOGGER.isDebugEnabled())
        LOGGER.debug(" Size of entityIdList-" + projectCodeIdList.size() + " asOnDate - " + asOnDate);
    Long entityId;
    // In sql query, if in list contains more than 1000 elements, it may
    // fail.Hence, we start splitting the list passed into smaller lists of sizes less than 1000.
    for (int i = 0; i < projectCodeIdList.size(); i++) {
        entityId = projectCodeIdList.get(i);
        commaSeperatedEntities = commaSeperatedEntities + entityId + ",";
        tempEntityIdList.add(entityId);
        if (i != 0 && i % 998 == 0 || i == projectCodeIdList.size() - 1) {
            commaSeperatedEntitiesList
                    .add(commaSeperatedEntities.substring(0, commaSeperatedEntities.length() - 1));
            limitedEntityList.add(tempEntityIdList);
            commaSeperatedEntities = "";
            tempEntityIdList = new ArrayList<Long>();
        }
    }

    /*
     * String validationQuery =
     * "SELECT detailkey FROM accountdetailkey WHERE detailtypeid= (SELECT id FROM accountdetailtype " +
     * "WHERE name ='PROJECTCODE' AND description='PROJECTCODE' ) and ( detailkey in ("; List<BigDecimal> dbEntIdList = new
     * ArrayList<BigDecimal>(); boolean isPresent; List<Long> incorrectEntityIds = new ArrayList<Long>(); String
     * dbEntIdQuery=""; if(LOGGER.isDebugEnabled()) LOGGER.debug(" Validation Starts "); for (int i = 0; i <
     * commaSeperatedEntitiesList.size(); i++) { isPresent = false; dbEntIdQuery = validationQuery +
     * commaSeperatedEntitiesList.get(i); if(i!=0) dbEntIdQuery=dbEntIdQuery+ ") or detailkey in(";
     * if(LOGGER.isDebugEnabled()) LOGGER.debug(i + ":dbEntIdQuery- " + dbEntIdQuery);
     * if(i==commaSeperatedEntitiesList.size()-1) dbEntIdQuery=dbEntIdQuery+ ")) order by detailkey "; }
     * if(LOGGER.isDebugEnabled()) LOGGER.debug("Final Query- " + dbEntIdQuery); dbEntIdList = (List<BigDecimal>)
     * persistenceService.getSession().createSQLQuery(dbEntIdQuery).list(); if (dbEntIdList != null && dbEntIdList.size() !=
     * limitedEntityList.size()) { for (int i = 0; i < commaSeperatedEntitiesList.size(); i++) { for (Long entId :
     * limitedEntityList.get(i)) { isPresent = false; for (BigDecimal dbEntId : dbEntIdList) { if (dbEntId.longValue() ==
     * entId.longValue()) { isPresent = true; break; } } if (!isPresent) { incorrectEntityIds.add(entId); } } } } if
     * (incorrectEntityIds.size() != 0) throw new ApplicationException("Incorrect detail key Ids - "+ incorrectEntityIds);
     * if(LOGGER.isDebugEnabled()) LOGGER.debug(" Validation Succeded in method..");
     */
    String qryForExpense = "";
    String qryForNonExpense = "";
    final BigDecimal totalExpensePaymentAmount = BigDecimal.ZERO;
    String deptName = null;
    List<Object[]> objForExpense;
    List<Object[]> objForNonExpense;
    BigDecimal tempAmountObj = BigDecimal.ZERO;

    boolean ifDeptExist = false;
    for (int i = 0; i < commaSeperatedEntitiesList.size(); i++) {
        qryForExpense = getPaymentAmountByDept(commaSeperatedEntitiesList.get(i), strAsOnDate, true);
        qryForNonExpense = getPaymentAmountByDept(commaSeperatedEntitiesList.get(i), strAsOnDate, false);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug(i + ": qryForExpense- " + qryForExpense);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug(i + ": qryForNonExpense- " + qryForNonExpense);
        objForExpense = persistenceService.getSession().createSQLQuery(qryForExpense).list();
        objForNonExpense = persistenceService.getSession().createSQLQuery(qryForNonExpense).list();
        if (objForExpense != null && objForExpense.size() != 0) {
            tempAmountObj = new BigDecimal(objForExpense.get(0)[0].toString());
            deptName = objForExpense.get(0)[1].toString();
            ifDeptExist = result.containsValue(deptName);
            if (ifDeptExist) {
                result.put(deptName, totalExpensePaymentAmount.add(tempAmountObj).toString());
                result.put("departmentname", deptName);
            } else {
                result.put(deptName, tempAmountObj.toString());
                result.put("departmentname", deptName);
            }
        }
        ifDeptExist = false;
        if (objForNonExpense != null && objForNonExpense.size() != 0) {
            tempAmountObj = new BigDecimal(objForNonExpense.get(0)[0].toString());
            deptName = objForNonExpense.get(0)[1].toString();
            ifDeptExist = result.containsValue(deptName);
            if (ifDeptExist) {
                result.put(deptName, totalExpensePaymentAmount.add(tempAmountObj).toString());
                result.put("departmentname", deptName);
            } else {
                result.put(deptName, tempAmountObj.toString());
                result.put("departmentname", deptName);
            }

        }
    }
    return result;
}

From source file:com.jdom.get.stuff.done.android.AndroidSyncStrategy.java

@Override
public void synchronizeWithRemote() {
    long start = System.currentTimeMillis();
    Log.i(CLASS_NAME, "Started syncing with remote server at " + new SimpleDateFormat().format(new Date()));
    try {/*w  ww.j av a  2 s.  c  om*/
        Tasks service = getTasksService();
        ApplicationDao dao = contextFactory.getDaoFactory().getApplicationDao();

        Map<String, List<com.google.api.services.tasks.model.Task>> listNameToTasks = new HashMap<String, List<com.google.api.services.tasks.model.Task>>();
        Map<String, String> listNameToRemoteIdentifier = new HashMap<String, String>();
        Map<String, TaskList> listNameToTaskList = new HashMap<String, TaskList>();
        Map<String, String> taskIdToListId = new HashMap<String, String>();
        Map<String, String> taskNameToRemoteIdentifier = new HashMap<String, String>();

        long portionStart = System.currentTimeMillis();
        TaskLists taskLists = service.tasklists().list().execute();
        AndroidSyncStrategy.logTimeTaken("Retrieving task lists", portionStart);
        TaskList defaultTaskList = service.tasklists().get(Constants.GOOGLE_DEFAULT_LIST_REMOTE_ID).execute();
        Set<com.jdom.get.stuff.done.domain.TaskList> localTaskLists = dao.getTaskLists();
        Set<Task> localTasks = dao.getTasks();
        List<TaskList> googleTaskLists = taskLists.getItems();

        for (TaskList googleTaskList : googleTaskLists) {
            String googleListTitle = googleTaskList.getTitle();
            String remoteId = googleTaskList.getId();
            if (StringUtils.isEmpty(googleListTitle)) {
                continue;
            } else if (googleListTitle.equals(defaultTaskList.getTitle())) {
                remoteId = Constants.GOOGLE_DEFAULT_LIST_REMOTE_ID;
            }
            listNameToRemoteIdentifier.put(googleListTitle, remoteId);
            listNameToTaskList.put(googleListTitle, googleTaskList);
            List<com.google.api.services.tasks.model.Task> googleTasksForList = new ArrayList<com.google.api.services.tasks.model.Task>();

            portionStart = System.currentTimeMillis();
            List<com.google.api.services.tasks.model.Task> googleTasks = service.tasks().list(remoteId)
                    .execute().getItems();
            AndroidSyncStrategy.logTimeTaken("Retrieving tasks for list " + googleListTitle, portionStart);
            if (googleTasks == null || googleTasks.isEmpty()) {
                continue;
            }

            for (com.google.api.services.tasks.model.Task googleTask : googleTasks) {
                String taskTitle = googleTask.getTitle();
                if (StringUtils.isEmpty(taskTitle)) {
                    continue;
                }
                taskNameToRemoteIdentifier.put(taskTitle, googleTask.getId());
                taskIdToListId.put(googleTask.getId(), remoteId);
                googleTasksForList.add(googleTask);
            }
            listNameToTasks.put(googleListTitle, googleTasksForList);
        }

        // Check for any lists that were renamed remotely
        for (String listName : listNameToRemoteIdentifier.keySet()) {
            String remoteId = listNameToRemoteIdentifier.get(listName);

            com.jdom.get.stuff.done.domain.TaskList localVersion = findLocalTaskListWithRemoteId(remoteId,
                    localTaskLists);
            // No local version, create one
            if (localVersion == null) {
                long localStart = System.currentTimeMillis();
                com.jdom.get.stuff.done.domain.TaskList localTaskList = new com.jdom.get.stuff.done.domain.TaskList(
                        listName);
                localTaskList.setRemoteIdentifier(remoteId);
                localTaskLists.add(localTaskList);
                dao.addTaskList(localTaskList);
                AndroidSyncStrategy.logTimeTaken("Create local list from remote", localStart);
            } else if (!Constants.DEFAULT_LIST.equals(localVersion.getName())
                    && !localVersion.getName().equals(listName)) {
                long lastSyncTime = dao.getLastSyncTime();
                // If hasn't been updated since last sync, then was renamed
                // remotely
                if (localVersion.getLastUpdatedTime() <= lastSyncTime) {
                    long localStart = System.currentTimeMillis();
                    com.jdom.get.stuff.done.domain.TaskList newVersion = localVersion.clone();
                    newVersion.setName(listName);
                    dao.updateTaskList(localVersion, newVersion);
                    AndroidSyncStrategy.logTimeTaken("Update local list from remote", localStart);
                } else {
                    long localStart = System.currentTimeMillis();
                    // If has been updated since last sync, then was renamed
                    // locally
                    TaskList googleTaskList = listNameToTaskList.get(listName);
                    googleTaskList.setTitle(localVersion.getName());
                    service.tasklists().update(remoteId, googleTaskList).execute();
                    AndroidSyncStrategy.logTimeTaken("Update remote list from local", localStart);
                }
            }
        }

        Iterator<com.jdom.get.stuff.done.domain.TaskList> iter = localTaskLists.iterator();
        List<com.jdom.get.stuff.done.domain.TaskList> updatedList = new ArrayList<com.jdom.get.stuff.done.domain.TaskList>();
        while (iter.hasNext()) {
            com.jdom.get.stuff.done.domain.TaskList localTaskList = iter.next();
            String remoteId = localTaskList.getRemoteIdentifier();
            // Any locally created lists that need a remote version created
            if (remoteId == null) {
                TaskList remote = new TaskList();
                remote.setTitle(localTaskList.getName());
                TaskList created = service.tasklists().insert(remote).execute();
                com.jdom.get.stuff.done.domain.TaskList updated = localTaskList.clone();
                updated.setRemoteIdentifier(created.getId());
                dao.updateTaskList(localTaskList, updated);
                updatedList.add(updated);
                iter.remove();
            }
            // Any local task list with remote identifier that doesn't have
            // remote version were deleted remotely
            else if (!listNameToRemoteIdentifier.containsValue(remoteId)) {
                long localStart = System.currentTimeMillis();
                dao.deleteTaskList(localTaskList);
                iter.remove();
                AndroidSyncStrategy.logTimeTaken("Delete local task list because remote was", localStart);
            }
            // Flagged for deletion, remove remote version and local
            else if (localTaskList.isDeleted()) {
                long localStart = System.currentTimeMillis();
                service.tasklists().delete(remoteId).execute();
                dao.deleteTaskList(localTaskList);
                iter.remove();
                AndroidSyncStrategy.logTimeTaken("Delete remote task list because local was", localStart);
            }
        }

        localTaskLists.addAll(updatedList);

        // Now check for tasks
        for (String listName : listNameToTasks.keySet()) {
            List<com.google.api.services.tasks.model.Task> googleTasksForList = listNameToTasks.get(listName);
            long lastSyncTime = dao.getLastSyncTime();

            for (com.google.api.services.tasks.model.Task googleTask : googleTasksForList) {
                String remoteId = googleTask.getId();

                com.jdom.get.stuff.done.domain.Task localVersion = findLocalTaskWithRemoteId(remoteId,
                        localTasks);
                // No local version, create one
                if (localVersion == null) {
                    long localStart = System.currentTimeMillis();
                    localVersion = createLocalTask(googleTask, listName);
                    localTasks.add(localVersion);
                    dao.addTask(localVersion);
                    AndroidSyncStrategy.logTimeTaken("Create local task from remote", localStart);
                } else if (localVersion.getLastUpdatedTime() > lastSyncTime) {
                    long localStart = System.currentTimeMillis();
                    // If has been updated since last sync, then was
                    // changed locally
                    String originalRemoteId = localVersion.getRemoteIdentifier();
                    Task updated = createRemoteTask(service, dao, localVersion, listNameToRemoteIdentifier);
                    localVersion.setRemoteIdentifier(updated.getRemoteIdentifier());
                    taskNameToRemoteIdentifier.put(localVersion.getName(), updated.getRemoteIdentifier());

                    service.tasks().delete(listNameToRemoteIdentifier.get(listName), originalRemoteId)
                            .execute();
                    AndroidSyncStrategy.logTimeTaken("Update remote task from local", localStart);
                }
                // If hasn't been updated since last sync, then may
                // have been changed remotely
                else if (!localVersion.equals(googleTask, listName)) {
                    long localStart = System.currentTimeMillis();
                    com.jdom.get.stuff.done.domain.Task newVersion = createLocalTask(googleTask, listName);
                    dao.updateTask(localVersion, newVersion);
                    AndroidSyncStrategy.logTimeTaken("Update local task from remote", localStart);
                }
            }
        }

        Iterator<com.jdom.get.stuff.done.domain.Task> taskIter = dao.getTasks().iterator();
        List<com.jdom.get.stuff.done.domain.Task> taskUpdatedList = new ArrayList<com.jdom.get.stuff.done.domain.Task>();
        while (taskIter.hasNext()) {
            com.jdom.get.stuff.done.domain.Task localTask = taskIter.next();
            String remoteId = localTask.getRemoteIdentifier();
            // If remoteId is null, then this is a local task that needs a
            // remote created
            if (remoteId == null) {
                long localStart = System.currentTimeMillis();
                Task updated = createRemoteTask(service, dao, localTask, listNameToRemoteIdentifier);

                taskUpdatedList.add(updated);
                taskIter.remove();
                AndroidSyncStrategy.logTimeTaken("Create remote task from local", localStart);
            }
            // Any local task with remote identifier that doesn't have
            // remote version were deleted remotely
            else if (!taskNameToRemoteIdentifier.containsValue(remoteId)) {
                long localStart = System.currentTimeMillis();
                dao.deleteTask(localTask);
                taskIter.remove();
                AndroidSyncStrategy.logTimeTaken("Delete local task because remote was", localStart);
            }
            // Flagged for deletion, remove remote version and local
            else if (localTask.isDeleted()) {
                long localStart = System.currentTimeMillis();
                service.tasks().delete(taskIdToListId.get(remoteId), remoteId).execute();
                dao.deleteTask(localTask);
                taskIter.remove();
                AndroidSyncStrategy.logTimeTaken("Delete remote task because local was", localStart);
            }
        }

        localTasks.addAll(taskUpdatedList);

        // Update the last sync time
        dao.setLastSyncTime(System.currentTimeMillis());
    } catch (Exception e) {
        handleException(e);
    } finally {
        AndroidSyncStrategy.logTimeTaken("Finished syncing with remote server", start);
        running.set(false);
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.TestRMRestart.java

@Test(timeout = 60000)
public void testRMDelegationTokenRestoredOnRMRestart() throws Exception {
    conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 2);
    conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos");
    conf.set(YarnConfiguration.RM_ADDRESS, "localhost:8032");
    UserGroupInformation.setConfiguration(conf);

    MockRM rm1 = new TestSecurityMockRM(conf);
    Assume.assumeFalse(rm1.getResourceScheduler() instanceof FairScheduler);
    rm1.start();/*from ww w  . j  a  v a  2s .co m*/

    // create an empty credential
    Credentials ts = new Credentials();

    // request a token and add into credential
    GetDelegationTokenRequest request1 = GetDelegationTokenRequest.newInstance("renewer1");
    UserGroupInformation.getCurrentUser().setAuthenticationMethod(AuthMethod.KERBEROS);
    GetDelegationTokenResponse response1 = rm1.getClientRMService().getDelegationToken(request1);
    org.apache.hadoop.yarn.api.records.Token delegationToken1 = response1.getRMDelegationToken();
    Token<RMDelegationTokenIdentifier> token1 = ConverterUtils.convertFromYarn(delegationToken1, rmAddr);
    RMDelegationTokenIdentifier dtId1 = token1.decodeIdentifier();

    HashSet<RMDelegationTokenIdentifier> tokenIdentSet = new HashSet<RMDelegationTokenIdentifier>();
    ts.addToken(token1.getService(), token1);
    tokenIdentSet.add(dtId1);

    // submit an app with customized credential
    RMApp app = rm1.submitApp(200, "name", "user", new HashMap<ApplicationAccessType, String>(), false,
            "default", 1, ts);

    // assert app info is saved
    RMState rmState = rm1.getRMContext().getStateStore().loadState();
    Map<ApplicationId, ApplicationStateData> rmAppState = rmState.getApplicationState();
    ApplicationStateData appState = rmAppState.get(app.getApplicationId());
    Assert.assertNotNull(appState);

    // assert all master keys are saved
    Set<DelegationKey> allKeysRM1 = rm1.getRMContext().getRMDelegationTokenSecretManager().getAllMasterKeys();
    rmState = rm1.getRMContext().getStateStore().loadState();
    Set<DelegationKey> rmDTMasterKeyState = rmState.getRMDTSecretManagerState().getMasterKeyState();
    for (DelegationKey expectedKey : allKeysRM1) {
        boolean foundIt = false;
        for (DelegationKey gotKey : rmDTMasterKeyState) {
            if (expectedKey.getKeyId() == gotKey.getKeyId()
                    && Arrays.equals(expectedKey.getEncodedKey(), gotKey.getEncodedKey())) {
                foundIt = true;
                break;
            }
        }
        Assert.assertTrue(foundIt);
    }

    // assert all tokens are saved
    Map<RMDelegationTokenIdentifier, Long> allTokensRM1 = rm1.getRMContext().getRMDelegationTokenSecretManager()
            .getAllTokens();
    Assert.assertEquals(tokenIdentSet, allTokensRM1.keySet());
    rmState = rm1.getRMContext().getStateStore().loadState();
    Map<RMDelegationTokenIdentifier, Long> rmDTState = rmState.getRMDTSecretManagerState().getTokenState();
    Assert.assertEquals(allTokensRM1.size(), rmDTState.size());
    for (RMDelegationTokenIdentifier identifier : allTokensRM1.keySet()) {
        Assert.assertEquals(allTokensRM1.get(identifier), rmDTState.get(identifier));
    }

    // assert sequence number is saved
    rmState = rm1.getRMContext().getStateStore().loadState();
    Assert.assertEquals(rm1.getRMContext().getRMDelegationTokenSecretManager().getLatestDTSequenceNumber(),
            rmState.getRMDTSecretManagerState().getDTSequenceNumber());

    // request one more token
    GetDelegationTokenRequest request2 = GetDelegationTokenRequest.newInstance("renewer2");
    GetDelegationTokenResponse response2 = rm1.getClientRMService().getDelegationToken(request2);
    org.apache.hadoop.yarn.api.records.Token delegationToken2 = response2.getRMDelegationToken();
    Token<RMDelegationTokenIdentifier> token2 = ConverterUtils.convertFromYarn(delegationToken2, rmAddr);
    RMDelegationTokenIdentifier dtId2 = token2.decodeIdentifier();

    // cancel token2
    try {
        rm1.getRMContext().getRMDelegationTokenSecretManager().cancelToken(token2,
                UserGroupInformation.getCurrentUser().getUserName());
    } catch (Exception e) {
        Assert.fail();
    }

    // Assert the token which has the latest delegationTokenSequenceNumber is removed
    Assert.assertEquals(rm1.getRMContext().getRMDelegationTokenSecretManager().getLatestDTSequenceNumber(),
            dtId2.getSequenceNumber());
    rmState = rm1.getRMContext().getStateStore().loadState();
    rmDTState = rmState.getRMDTSecretManagerState().getTokenState();
    Assert.assertFalse(rmDTState.containsKey(dtId2));

    // start new RM
    MockRM rm2 = new TestSecurityMockRM(conf);
    rm2.start();

    // assert master keys and tokens are populated back to DTSecretManager
    Map<RMDelegationTokenIdentifier, Long> allTokensRM2 = rm2.getRMContext().getRMDelegationTokenSecretManager()
            .getAllTokens();
    Assert.assertEquals(allTokensRM2.keySet(), allTokensRM1.keySet());
    // rm2 has its own master keys when it starts, we use containsAll here
    rmDTMasterKeyState = rm2.getRMContext().getRMDelegationTokenSecretManager().getAllMasterKeys();
    for (DelegationKey expectedKey : allKeysRM1) {
        boolean foundIt = false;
        for (DelegationKey gotKey : rmDTMasterKeyState) {
            if (expectedKey.getKeyId() == gotKey.getKeyId()
                    && Arrays.equals(expectedKey.getEncodedKey(), gotKey.getEncodedKey())) {
                foundIt = true;
                break;
            }
        }
        Assert.assertTrue(foundIt);
    }

    // assert sequenceNumber is properly recovered,
    // even though the token which has max sequenceNumber is not stored
    Assert.assertEquals(rm1.getRMContext().getRMDelegationTokenSecretManager().getLatestDTSequenceNumber(),
            rm2.getRMContext().getRMDelegationTokenSecretManager().getLatestDTSequenceNumber());

    // renewDate before renewing
    Long renewDateBeforeRenew = allTokensRM2.get(dtId1);
    try {
        // Sleep for one millisecond to make sure renewDataAfterRenew is greater
        Thread.sleep(1);
        // renew recovered token
        rm2.getRMContext().getRMDelegationTokenSecretManager().renewToken(token1, "renewer1");
    } catch (Exception e) {
        Assert.fail();
    }

    allTokensRM2 = rm2.getRMContext().getRMDelegationTokenSecretManager().getAllTokens();
    Long renewDateAfterRenew = allTokensRM2.get(dtId1);
    // assert token is renewed
    Assert.assertTrue(renewDateAfterRenew > renewDateBeforeRenew);

    // assert new token is added into state store
    rmState = rm2.getRMContext().getStateStore().loadState();
    rmDTState = rmState.getRMDTSecretManagerState().getTokenState();
    Assert.assertTrue(rmDTState.containsValue(renewDateAfterRenew));
    // assert old token is removed from state store
    Assert.assertFalse(rmDTState.containsValue(renewDateBeforeRenew));

    try {
        rm2.getRMContext().getRMDelegationTokenSecretManager().cancelToken(token1,
                UserGroupInformation.getCurrentUser().getUserName());
    } catch (Exception e) {
        Assert.fail();
    }

    // assert token is removed from state after its cancelled
    allTokensRM2 = rm2.getRMContext().getRMDelegationTokenSecretManager().getAllTokens();
    Assert.assertFalse(allTokensRM2.containsKey(dtId1));
    rmState = rm2.getRMContext().getStateStore().loadState();
    rmDTState = rmState.getRMDTSecretManagerState().getTokenState();
    Assert.assertFalse(rmDTState.containsKey(dtId1));
}

From source file:com.atlassian.jira.webtests.JIRAWebTest.java

public void moveOptionsToPositions(String[] optionValue, String[] optionId, String itemType,
        Map<String, String> moveToPosition) {

    for (String currentPosition : moveToPosition.keySet()) {
        String newPosition = moveToPosition.get(currentPosition);

        int currIntPos = Integer.parseInt(currentPosition);
        int newIntPos = Integer.parseInt(newPosition);

        //checks and asserts if the current option is before or after the position it is moving to
        if (currIntPos < newIntPos) {
            assertTextPresentBeforeText("<b>" + optionValue[currIntPos] + "</b>",
                    "<b>" + optionValue[newIntPos] + "</b>");
        } else if (currIntPos > newIntPos) {
            assertTextPresentBeforeText("<b>" + optionValue[newIntPos] + "</b>",
                    "<b>" + optionValue[currIntPos] + "</b>");
        }/*from   w w  w.  j a  v  a 2s  .  c om*/

        //sets the new position for the current option
        log("      Moving item at position " + currIntPos + " to position " + newPosition);
        setFormElement("new" + itemType + "Position_" + optionId[currIntPos], newPosition);
    }

    clickButtonWithValue("Move");

    //completes the Map by filling in missing positions
    for (int i = 1; i < optionValue.length; i++) {
        if (!moveToPosition.containsKey(String.valueOf(i))) {
            int k = 1;
            while (k <= i && moveToPosition.containsValue(String.valueOf(k))) {
                k++;
            }
            moveToPosition.put(String.valueOf(i), String.valueOf(k));
        }
    }

    //checks if the options moved to its correct positions
    for (String currentOption : moveToPosition.keySet()) {
        String newCurrentPos = moveToPosition.get(currentOption);
        String newReplacedPos = moveToPosition.get(newCurrentPos);

        int currentOptionInt = Integer.parseInt(currentOption);
        int newCurrentPosInt = Integer.parseInt(newCurrentPos);
        int otherOptionInt = Integer.parseInt(newCurrentPos);
        int newReplacedPosInt = Integer.parseInt(newReplacedPos);

        if (newCurrentPosInt < newReplacedPosInt) {
            assertTextPresentBeforeText("<b>" + optionValue[currentOptionInt] + "</b>",
                    "<b>" + optionValue[otherOptionInt] + "</b>");
        } else if (newCurrentPosInt > newReplacedPosInt) {
            assertTextPresentBeforeText("<b>" + optionValue[otherOptionInt] + "</b>",
                    "<b>" + optionValue[currentOptionInt] + "</b>");
        }
        //else item remained in the same position
    }
}

From source file:services.object.ObjectService.java

public void readBuildoutDatatableOLD(DatatableVisitor buildoutTable, Planet planet, float x1, float z1)
        throws InstantiationException, IllegalAccessException {

    CrcStringTableVisitor crcTable = ClientFileManager.loadFile("misc/object_template_crc_string_table.iff",
            CrcStringTableVisitor.class);
    List<BuildingObject> persistentBuildings = new ArrayList<BuildingObject>();
    Map<Long, Long> duplicate = new HashMap<Long, Long>();

    for (int i = 0; i < buildoutTable.getRowCount(); i++) {

        String template;/*from w  ww .j  ava2 s  .c o  m*/

        if (buildoutTable.getColumnCount() <= 11)
            template = crcTable.getTemplateString((Integer) buildoutTable.getObject(i, 0));
        else
            template = crcTable.getTemplateString((Integer) buildoutTable.getObject(i, 3));

        if (template != null) {

            float px, py, pz, qw, qx, qy, qz, radius;
            long objectId = 0, containerId = 0;
            int type = 0, cellIndex = 0, portalCRC;

            if (buildoutTable.getColumnCount() <= 11) {

                cellIndex = (Integer) buildoutTable.getObject(i, 1);
                px = (Float) buildoutTable.getObject(i, 2);
                py = (Float) buildoutTable.getObject(i, 3);
                pz = (Float) buildoutTable.getObject(i, 4);
                qw = (Float) buildoutTable.getObject(i, 5);
                qx = (Float) buildoutTable.getObject(i, 6);
                qy = (Float) buildoutTable.getObject(i, 7);
                qz = (Float) buildoutTable.getObject(i, 8);
                radius = (Float) buildoutTable.getObject(i, 9);
                portalCRC = (Integer) buildoutTable.getObject(i, 10);

            } else {

                // Since the ids are just ints, they append 0xFFFF86F9 to them
                // This is demonstated in the packet sent to the server when you /target client-spawned objects
                objectId = (((Integer) buildoutTable.getObject(i, 0) == 0) ? 0
                        : Delta.createBuffer(8).putInt((Integer) buildoutTable.getObject(i, 0))
                                .putInt(0xF986FFFF).flip().getLong());
                containerId = (((Integer) buildoutTable.getObject(i, 1) == 0) ? 0
                        : Delta.createBuffer(8).putInt((Integer) buildoutTable.getObject(i, 1))
                                .putInt(0xF986FFFF).flip().getLong());
                type = (Integer) buildoutTable.getObject(i, 2);
                cellIndex = (Integer) buildoutTable.getObject(i, 4);

                px = (Float) buildoutTable.getObject(i, 5);
                py = (Float) buildoutTable.getObject(i, 6);
                pz = (Float) buildoutTable.getObject(i, 7);
                qw = (Float) buildoutTable.getObject(i, 8);
                qx = (Float) buildoutTable.getObject(i, 9);
                qy = (Float) buildoutTable.getObject(i, 10);
                qz = (Float) buildoutTable.getObject(i, 11);
                radius = (Float) buildoutTable.getObject(i, 12);
                portalCRC = (Integer) buildoutTable.getObject(i, 13);

            }

            // Treeku - Refactored to work around duplicate objectIds
            // Required for instances/heroics which are duplicated ie. 10 times
            //if(!template.equals("object/cell/shared_cell.iff") && objectId != 0 && getObject(objectId) != null) {
            if (!template.equals("object/cell/shared_cell.iff") && objectId != 0
                    && (checkIfObjectAlreadyInList(objectId))) {
                SWGObject object = getObject(objectId);

                // Same coordinates is a true duplicate
                if ((px + ((containerId == 0) ? 0 : x1)) == object.getPosition().x
                        && py == object.getPosition().y
                        && (pz + ((containerId == 0) ? 0 : z1)) == object.getPosition().z) {
                    //System.out.println("Duplicate buildout object: " + template);
                    continue;
                }
            }

            if (duplicate.containsKey(containerId)) {
                containerId = duplicate.get(containerId);
            }

            String planetName = planet.getName();

            // TODO needs to a way to work for mustafar and kashyyyk which both have instances
            //if (objectId != 0 && getObject(objectId) != null && (planetName.contains("dungeon") || planetName.contains("adventure"))) {
            if (objectId != 0 && checkIfObjectAlreadyInList(objectId)
                    && (planetName.contains("dungeon") || planetName.contains("adventure"))) {
                SWGObject container = getObject(containerId);
                float x = (px + ((container == null) ? x1 : container.getPosition().x));
                float z = (pz + ((container == null) ? z1 : container.getPosition().z));
                String key = "" + CRC.StringtoCRC(planet.getName()) + CRC.StringtoCRC(template) + type
                        + containerId + cellIndex + x + py + z;
                long newObjectId = 0;

                if (core.getDuplicateIdODB().contains(key)) {
                    newObjectId = ((DuplicateId) core.getDuplicateIdODB().get(key)).getObjectId();
                } else {
                    newObjectId = generateObjectID();
                    core.getDuplicateIdODB().put(key, new DuplicateId(key, newObjectId));
                }

                duplicate.put(objectId, newObjectId);
                objectId = newObjectId;
            }

            List<Long> containers = new ArrayList<Long>();
            SWGObject object;
            if (objectId != 0 && containerId == 0) {
                if (portalCRC != 0) {
                    if (core.getSWGObjectODB().contains(objectId) && !duplicate.containsValue(objectId))
                        continue;
                    containers.add(objectId);
                    object = createObject(template, objectId, planet, new Point3D(px + x1, py, pz + z1),
                            new Quaternion(qw, qx, qy, qz), null, true, true);
                    object.setAttachment("childObjects", null);

                    /*if (!duplicate.containsValue(objectId)) {
                       ((BuildingObject) object).createTransaction(core.getBuildingODB().getEnvironment());
                       core.getBuildingODB().put((BuildingObject) object, Long.class, BuildingObject.class, ((BuildingObject) object).getTransaction());
                       ((BuildingObject) object).getTransaction().commitSync();
                    }*/
                } else {
                    object = createObject(template, 0, planet, new Point3D(px + x1, py, pz + z1),
                            new Quaternion(qw, qx, qy, qz), null, false, true);
                }
                if (object == null)
                    continue;
                object.setContainerPermissions(WorldPermissions.WORLD_PERMISSIONS);
                if (radius > 256)
                    object.setAttachment("bigSpawnRange", new Boolean(true));
                if (!duplicate.containsValue(objectId) && object instanceof BuildingObject && portalCRC != 0)
                    persistentBuildings.add((BuildingObject) object);
            } else if (containerId != 0) {
                object = createObject(template, 0, planet, new Point3D(px, py, pz),
                        new Quaternion(qw, qx, qy, qz), null, false, true);
                if (containers.contains(containerId)) {
                    object.setContainerPermissions(WorldPermissions.WORLD_PERMISSIONS);
                    object.setisInSnapshot(false);
                    containers.add(objectId);
                }
                if (object instanceof CellObject && cellIndex != 0) {
                    object.setContainerPermissions(WorldCellPermissions.WORLD_CELL_PERMISSIONS);
                    ((CellObject) object).setCellNumber(cellIndex);
                }
                SWGObject parent = getObject(containerId);

                if (parent != null && object != null) {
                    if (parent instanceof BuildingObject
                            && ((BuildingObject) parent).getCellByCellNumber(cellIndex) != null)
                        continue;
                    parent.add(object);
                }
            } else {
                object = createObject(template, 0, planet, new Point3D(px + x1, py, pz + z1),
                        new Quaternion(qw, qx, qy, qz), null, false, true);
                object.setContainerPermissions(WorldPermissions.WORLD_PERMISSIONS);
            }

            if (object != null && object instanceof TangibleObject && !(object instanceof CreatureObject)) {
                ((TangibleObject) object).setStaticObject(true);
            }

            //System.out.println("Spawning: " + template + " at: X:" + object.getPosition().x + " Y: " + object.getPosition().y + " Z: " + object.getPosition().z);
            if (object != null)
                object.setAttachment("isBuildout", new Boolean(true));
        }

    }

    for (BuildingObject building : persistentBuildings) {
        building.setAttachment("buildoutBuilding", true);
        core.getSWGObjectODB().put(building.getObjectID(), building);
        destroyObject(building);
    }

}

From source file:io.warp10.continuum.gts.GTSHelper.java

/**
 * Modify the labels of a GTS instance.//from www .  j  a  v a 2  s  .c  o  m
 * If a label appears in 'newlabels', the associated value will be used in 'gts', unless
 * the associated value is the empty string or null in which case the said label will be removed
 * from 'gts'.
 * If a null key is present in the 'newlabels' map, the labels will replace those of 'gts'
 * instead of modifying them.
 * 
 * @param gts GTS instance whose labels must be modified.
 * @param newlabels Map of label names to label values.
 */
public static GeoTimeSerie relabel(GeoTimeSerie gts, Map<String, String> newlabels) {
    Map<String, String> labels = new HashMap<String, String>();

    if (!newlabels.containsValue(null)) {
        labels.putAll(gts.getLabels());
    }

    for (String name : newlabels.keySet()) {
        String value = newlabels.get(name);
        if (null == value || "".equals(value)) {
            labels.remove(name);
            continue;
        }

        if (null != name) {
            labels.put(name, value);
        }
    }

    gts.setLabels(labels);

    return gts;
}

From source file:com.mss.mirage.employee.general.EmployeeAction.java

public String myQuarterlyAppraisalEdit() {
    resultType = LOGIN;//from ww w . ja  v a  2s  .c  o m

    if (httpServletRequest.getSession(false) != null && httpServletRequest.getSession(false)
            .getAttribute(ApplicationConstants.SESSION_USER_ID) != null) {
        userRoleId = Integer.parseInt(httpServletRequest.getSession(false)
                .getAttribute(ApplicationConstants.SESSION_ROLE_ID).toString());
        loginId = httpServletRequest.getSession(false).getAttribute(ApplicationConstants.SESSION_USER_ID)
                .toString();
        int isManager = Integer.parseInt(httpServletRequest.getSession(false)
                .getAttribute(ApplicationConstants.SESSION_IS_USER_MANAGER).toString());
        // String workingCountry = httpServletRequest.getSession(false).getAttribute(ApplicationConstants.WORKING_COUNTRY).toString();
        String livingCountry = httpServletRequest.getSession(false)
                .getAttribute(ApplicationConstants.Living_COUNTRY).toString();
        String userRoleName = httpServletRequest.getSession(false)
                .getAttribute(ApplicationConstants.SESSION_ROLE_NAME).toString();
        resultType = "accessFailed";
        if (AuthorizationManager.getInstance().isAuthorizedUser("QUARTERLY_APPRAISAL", userRoleId)) {
            try {
                boolean accessAllow = false;
                if (getEmpId() != 0 && getAppraisalId() != 0 && getLineId() != 0) {
                    String emploginId = DataSourceDataProvider.getInstance().getLoginIdByEmpId(getEmpId());

                    Map myTeamMemebrs = new HashMap();
                    Map rolesMap = (Map) httpServletRequest.getSession(false)
                            .getAttribute(ApplicationConstants.SESSION_MY_ROLES);
                    String department = httpServletRequest.getSession(false)
                            .getAttribute(ApplicationConstants.SESSION_MY_DEPT_ID).toString();
                    String access[] = Properties.getProperty("QuarterlyAppraisal.Access")
                            .split(Pattern.quote(","));
                    List accessList = Arrays.asList(access);

                    int sessionEmpId = Integer.parseInt(httpServletRequest.getSession(false)
                            .getAttribute(ApplicationConstants.SESSION_EMP_ID).toString());
                    if (getCurretRole() != null && getCurretRole().equals("my")) {

                        if (sessionEmpId == getEmpId()) {
                            accessAllow = true;
                        }
                    } else if (getCurretRole() != null && getCurretRole().equals("team")) {
                        String roleName = httpServletRequest.getSession(false)
                                .getAttribute(ApplicationConstants.SESSION_ROLE_NAME).toString();
                        if (loginId.equals("rkalaga")) {
                            accessAllow = true;
                        } else if ((roleName.equals("Operations") && accessList.contains(loginId))
                                || (department.equals("Operations") && isManager == 1)
                                || rolesMap.containsValue("Admin")) {
                            accessAllow = true;
                        } else {
                            if (roleName.equalsIgnoreCase("Employee") && isManager == 1) {
                                myTeamMemebrs = (Map) httpServletRequest.getSession(false)
                                        .getAttribute(ApplicationConstants.SESSION_MY_TEAM_MAP);

                                if (myTeamMemebrs.containsKey(emploginId)) {
                                    accessAllow = true;
                                }
                            }
                            if (roleName.equalsIgnoreCase("Operations")) {
                                myTeamMemebrs = DataSourceDataProvider.getInstance().getInstance()
                                        .getEmployeeNamesByOperationsContactId((httpServletRequest
                                                .getSession(false)
                                                .getAttribute(ApplicationConstants.SESSION_EMP_ID).toString()));

                                if (myTeamMemebrs.containsKey(emploginId)) {
                                    accessAllow = true;
                                }
                            }

                        }
                    }
                    if (accessAllow) {
                        //  String quarterAppraisalDetails = ServiceLocator.getEmployeeService().getEmployeeResumeLocation(getId());
                        String result = ServiceLocator.getEmployeeService().quarterlyAppraisalEdit(getEmpId(),
                                getAppraisalId(), getLineId());
                        setQuarterAppraisalDetails(result.split(Pattern.quote("@^$"))[0]);
                        String remainingData[] = (result.split(Pattern.quote("@^$"))[1])
                                .split(Pattern.quote("#^$"));
                        if (remainingData[0] != null && !"".equals(remainingData[0])
                                && !"_".equals(remainingData[0])) {
                            setShortTermGoal(remainingData[0]);
                        }
                        if (remainingData[1] != null && !"".equals(remainingData[1])
                                && !"_".equals(remainingData[1])) {
                            setShortTermGoalComments(remainingData[1]);
                        }
                        if (remainingData[2] != null && !"".equals(remainingData[2])
                                && !"_".equals(remainingData[2])) {
                            setLongTermGoal(remainingData[2]);
                        }
                        if (remainingData[3] != null && !"".equals(remainingData[3])
                                && !"_".equals(remainingData[3])) {
                            setLongTermGoalComments(remainingData[3]);
                        }
                        if (remainingData[4] != null && !"".equals(remainingData[4])
                                && !"_".equals(remainingData[4])) {
                            setStrength(remainingData[4]);
                        }
                        if (remainingData[5] != null && !"".equals(remainingData[5])
                                && !"_".equals(remainingData[5])) {
                            setStrengthsComments(remainingData[5]);
                        }
                        if (remainingData[6] != null && !"".equals(remainingData[6])
                                && !"_".equals(remainingData[6])) {
                            setImprovements(remainingData[6]);
                        }
                        if (remainingData[7] != null && !"".equals(remainingData[7])
                                && !"_".equals(remainingData[7])) {
                            setImprovementsComments(remainingData[7]);
                        }
                        if (remainingData[8] != null && !"".equals(remainingData[8])
                                && !"_".equals(remainingData[8])) {
                            setOperationTeamStatus(remainingData[8]);
                        }

                        if (remainingData[9] != null && !"".equals(remainingData[9])
                                && !"_".equals(remainingData[9])) {
                            setManagerRejectedComments(remainingData[9]);
                        }

                        if (remainingData[10] != null && !"".equals(remainingData[10])
                                && !"_".equals(remainingData[10])) {
                            setOperationRejectedComments(remainingData[10]);
                        }

                        java.util.Date approvedDate = null;
                        java.util.Date opeartionApprovedDate = null;

                        if (remainingData[11] != null && !"".equals(remainingData[11])
                                && !"_".equals(remainingData[11])) {
                            approvedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(remainingData[11]);
                        }
                        if (remainingData[12] != null && !"".equals(remainingData[12])
                                && !"_".equals(remainingData[12])) {
                            opeartionApprovedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                    .parse(remainingData[12]);
                        }

                        if (remainingData[13] != null && !"".equals(remainingData[13])
                                && !"_".equals(remainingData[13])) {
                            setQuarterly(remainingData[13]);
                        }

                        if (remainingData[14] != null && !"".equals(remainingData[14])
                                && !"_".equals(remainingData[14])) {
                            setStatus(remainingData[14]);
                        }
                        if (remainingData[15] != null && !"".equals(remainingData[15])
                                && !"_".equals(remainingData[15])) {
                            setCurrStatus(remainingData[15]);
                        } else {
                            setCurrStatus("");
                        }

                        if (approvedDate == null && opeartionApprovedDate == null) {
                            setDayCount(0);
                        } else {
                            if (opeartionApprovedDate == null) {
                                setDayCount(1);
                            } else {
                                if (approvedDate.compareTo(opeartionApprovedDate) > 0) {
                                    setDayCount(1);
                                } else {
                                    setDayCount(2);
                                }
                            }
                        }

                        //                setDeliveryKeyFactorsList(DataSourceDataProvider.getInstance().getDeliveryFactors());
                        //                setTrainingKeyFactorsList(DataSourceDataProvider.getInstance().getTrainingFactors());
                        List empdetails = DataSourceDataProvider.getInstance()
                                .getEmployeeInfoById(String.valueOf(empId));
                        if (empdetails.size() > 0) {
                            setEmpName((String) empdetails.get(0));
                            setItgBatch((String) empdetails.get(1));
                            setEmpDateOFBirth((String) empdetails.get(2));
                            setPracticeId((String) empdetails.get(4));
                            setTitleId((String) empdetails.get(5));
                            if (isManager == 1) {
                                setIsManager(true);
                            } else {
                                setIsManager(false);
                            }
                        }

                        if (getCurretRole() == null || !getCurretRole().equals("team")) {
                            setCurretRole("my");
                        }

                        if (accessList.contains(loginId) || (department.equals("Operations") && isManager == 1)
                                || rolesMap.containsValue("Admin")) {
                            setAccessCount(1);
                        }

                        // searchPrepare();
                        //  prepare();
                        resultType = SUCCESS;
                    }
                }

            } catch (Exception ex) {
                //List errorMsgList = ExceptionToListUtility.errorMessages(ex);
                ex.printStackTrace();
                httpServletRequest.getSession(false).setAttribute("errorMessage", ex.toString());
                resultType = ERROR;
            }
        } //END-Authorization Checking
    } //Close Session Checking

    /*  if (httpServletRequest.getParameter("quarterly") != null) {
    String empId = httpServletRequest.getParameter("empId");
    String lineId = httpServletRequest.getParameter("lineId");
    String appraisalId = httpServletRequest.getParameter("appraisalId");
    String quarterly = httpServletRequest.getParameter("quarterly");
    setEmpId(Integer.parseInt(empId));
    setLineId(Integer.parseInt(lineId));
    setAppraisalId(Integer.parseInt(appraisalId));
    setQuarterly(quarterly);
    } */

    return resultType;
}

From source file:eionet.meta.imp.VocabularyCSVImportHandler.java

/**
 * In this method, beans are generated (either created or updated) according to values in CSV file.
 *
 * @throws eionet.meta.service.ServiceException
 *             if there is the input is invalid
 *//*from  w w w . j  a  va 2  s  .  co  m*/
public void generateUpdatedBeans() throws ServiceException {
    // content.
    CSVReader reader = new CSVReader(this.content);
    DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");

    try {
        String[] header = reader.readNext();

        // first check if headers contains fix columns
        String[] fixedHeaders = new String[VocabularyCSVOutputHelper.CONCEPT_ENTRIES_COUNT];
        VocabularyCSVOutputHelper.addFixedEntryHeaders(fixedHeaders);

        // compare if it has URI
        boolean isEqual = StringUtils.equalsIgnoreCase(header[VocabularyCSVOutputHelper.URI_INDEX],
                fixedHeaders[VocabularyCSVOutputHelper.URI_INDEX]);

        if (!isEqual) {
            reader.close();
            throw new ServiceException("Missing header! CSV file should start with header: '"
                    + fixedHeaders[VocabularyCSVOutputHelper.URI_INDEX] + "'");
        }

        List<String> fixedHeadersList = new ArrayList<String>(
                Arrays.asList(Arrays.copyOf(fixedHeaders, VocabularyCSVOutputHelper.CONCEPT_ENTRIES_COUNT)));
        // remove uri from header
        fixedHeadersList.remove(VocabularyCSVOutputHelper.URI_INDEX);
        Map<String, Integer> fixedHeaderIndices = new HashMap<String, Integer>();
        for (int i = VocabularyCSVOutputHelper.URI_INDEX + 1; i < header.length; i++) {
            String elementHeader = StringUtils.trimToNull(header[i]);
            if (StringUtils.isBlank(elementHeader)) {
                throw new ServiceException("Header for column (" + (i + 1) + ") is empty!");
            }

            int headerIndex = -1;
            boolean headerFound = false;
            for (headerIndex = 0; headerIndex < fixedHeadersList.size(); headerIndex++) {
                if (StringUtils.equalsIgnoreCase(elementHeader, fixedHeadersList.get(headerIndex))) {
                    headerFound = true;
                    break;
                }
            }

            // if it is a fixed header value (concept property), add to map and continue
            if (headerFound) {
                String headerValue = fixedHeadersList.remove(headerIndex);
                fixedHeaderIndices.put(headerValue, i);
                continue;
            }

            // it is not a concept attribute and but a data element identifier
            // if there is language appended, split it
            String[] tempStrArray = elementHeader.split("[@]");
            if (tempStrArray.length == 2) {
                elementHeader = tempStrArray[0];
            }

            // if bound elements do not contain header already, add it (if possible)
            if (!this.boundElementsIds.containsKey(elementHeader)) {
                // search for data element
                this.elementsFilter.setIdentifier(elementHeader);
                DataElementsResult elementsResult = this.dataService.searchDataElements(this.elementsFilter);
                // if there is one and only one element check if header and identifer exactly matches!
                if (elementsResult.getTotalResults() < 1) {
                    throw new ServiceException("Cannot find any data element for column: " + elementHeader
                            + ". Please bind element manually then upload CSV.");
                } else if (elementsResult.getTotalResults() > 1) {
                    throw new ServiceException("Cannot find single data element for column: " + elementHeader
                            + ". Search returns: " + elementsResult.getTotalResults()
                            + " elements. Please bind element manually then upload CSV.");
                } else {
                    DataElement elem = elementsResult.getDataElements().get(0);
                    if (StringUtils.equals(elementHeader, elem.getIdentifier())) {
                        // found it, add to list and map
                        this.boundElementsIds.put(elementHeader,
                                elementsResult.getDataElements().get(0).getId());
                        this.newBoundElement.add(elem);
                    } else {
                        throw new ServiceException("Found data element did not EXACTLY match with column: "
                                + elementHeader + ", found: " + elem.getIdentifier());
                    }
                }
            }
        } // end of for loop iterating on headers

        String[] lineParams;
        // first row is header so start from 2
        for (int rowNumber = 2; (lineParams = reader.readNext()) != null; rowNumber++) {
            if (lineParams.length != header.length) {
                StringBuilder message = new StringBuilder();
                message.append("Row (").append(rowNumber).append(") ");
                message.append("did not have same number of columns with header, it was skipped.");
                message.append(" It should have have same number of columns (empty or filled).");
                this.logMessages.add(message.toString());
                continue;
            }

            // do line processing
            String uri = lineParams[VocabularyCSVOutputHelper.URI_INDEX];
            if (StringUtils.isEmpty(uri)) {
                this.logMessages.add("Row (" + rowNumber + ") was skipped (Base URI was empty).");
                continue;
            } else if (StringUtils.startsWith(uri, "//")) {
                this.logMessages.add("Row (" + rowNumber
                        + ") was skipped (Concept was excluded by user from update operation).");
                continue;
            } else if (!StringUtils.startsWith(uri, this.folderContextRoot)) {
                this.logMessages
                        .add("Row (" + rowNumber + ") was skipped (Base URI did not match with Vocabulary).");
                continue;
            }

            String conceptIdentifier = uri.replace(this.folderContextRoot, "");
            if (StringUtils.contains(conceptIdentifier, "/") || !Util.isValidIdentifier(conceptIdentifier)) {
                this.logMessages.add("Row (" + rowNumber + ") did not contain a valid concept identifier.");
                continue;
            }

            // now we have a valid row
            Pair<VocabularyConcept, Boolean> foundConceptWithFlag = findOrCreateConcept(conceptIdentifier);

            // if vocabulary concept duplicated with another row, importer will ignore it not to repeat
            if (foundConceptWithFlag == null || foundConceptWithFlag.getRight()) {
                this.logMessages
                        .add("Row (" + rowNumber + ") duplicated with a previous concept, it was skipped.");
                continue;
            }

            VocabularyConcept lastFoundConcept = foundConceptWithFlag.getLeft();
            // vocabulary concept found or created
            this.toBeUpdatedConcepts.add(lastFoundConcept);

            Integer conceptPropertyIndex = null;
            // check label
            conceptPropertyIndex = fixedHeaderIndices.get(fixedHeaders[VocabularyCSVOutputHelper.LABEL_INDEX]);
            if (conceptPropertyIndex != null) {
                lastFoundConcept.setLabel(StringUtils.trimToNull(lineParams[conceptPropertyIndex]));
            }

            // check definition
            conceptPropertyIndex = fixedHeaderIndices
                    .get(fixedHeaders[VocabularyCSVOutputHelper.DEFINITION_INDEX]);
            if (conceptPropertyIndex != null) {
                lastFoundConcept.setDefinition(StringUtils.trimToNull(lineParams[conceptPropertyIndex]));
            }

            // check notation
            conceptPropertyIndex = fixedHeaderIndices
                    .get(fixedHeaders[VocabularyCSVOutputHelper.NOTATION_INDEX]);
            if (conceptPropertyIndex != null) {
                lastFoundConcept.setNotation(StringUtils.trimToNull(lineParams[conceptPropertyIndex]));
            }

            // TODO: update - with merging flexible csv import
            // check start date
            // ignore status and accepteddate changes

            // now it is time iterate on rest of the columns, here is the tricky part
            List<DataElement> elementsOfConcept = null;
            List<DataElement> elementsOfConceptByLang = null;
            String prevHeader = null;
            String prevLang = null;
            for (int k = VocabularyCSVOutputHelper.URI_INDEX + 1; k < lineParams.length; k++) {
                if (StringUtils.isEmpty(lineParams[k])) {
                    // value is empty, no need to proceed
                    continue;
                }

                if (fixedHeaderIndices.containsValue(k)) {
                    // concept property, already handled
                    continue;
                }

                String elementHeader = header[k];
                String lang = null;
                String[] tempStrArray = elementHeader.split("[@]");
                if (tempStrArray.length == 2) {
                    elementHeader = tempStrArray[0];
                    lang = tempStrArray[1];
                }

                if (!StringUtils.equals(elementHeader, prevHeader)) {
                    elementsOfConcept = getDataElementValuesByName(elementHeader,
                            lastFoundConcept.getElementAttributes());
                    if (elementsOfConcept == null) {
                        elementsOfConcept = new ArrayList<DataElement>();
                        lastFoundConcept.getElementAttributes().add(elementsOfConcept);
                    }
                }

                if (!StringUtils.equals(elementHeader, prevHeader) || !StringUtils.equals(lang, prevLang)) {
                    elementsOfConceptByLang = getDataElementValuesByNameAndLang(elementHeader, lang,
                            lastFoundConcept.getElementAttributes());
                }

                prevLang = lang;
                prevHeader = elementHeader;

                VocabularyConcept foundRelatedConcept = null;
                if (Util.isValidUri(lineParams[k])) {
                    foundRelatedConcept = findRelatedConcept(lineParams[k]);
                }

                // check for pre-existence of the VCE by attribute value or related concept id
                Integer relatedId = null;
                if (foundRelatedConcept != null) {
                    relatedId = foundRelatedConcept.getId();
                }
                boolean returnFromThisPoint = false;
                for (DataElement elemByLang : elementsOfConceptByLang) {
                    String elementValueByLang = elemByLang.getAttributeValue();
                    if (StringUtils.equals(lineParams[k], elementValueByLang)) {
                        // vocabulary concept element already in database, no need to continue, return
                        returnFromThisPoint = true;
                        break;
                    }

                    if (relatedId != null) {
                        Integer relatedConceptId = elemByLang.getRelatedConceptId();
                        if (relatedConceptId != null && relatedConceptId.intValue() == relatedId.intValue()) {
                            // vocabulary concept element already in database, no need to continue, return
                            returnFromThisPoint = true;
                            break;
                        }
                    }
                }
                // check if an existing VCE found or not
                if (returnFromThisPoint) {
                    continue;
                }

                // create VCE
                DataElement elem = new DataElement();
                elementsOfConcept.add(elem);
                elem.setAttributeLanguage(lang);
                elem.setIdentifier(elementHeader);
                elem.setId(this.boundElementsIds.get(elementHeader));
                // check if there is a found related concept
                if (foundRelatedConcept != null) {
                    elem.setRelatedConceptIdentifier(foundRelatedConcept.getIdentifier());
                    int id = foundRelatedConcept.getId();
                    elem.setRelatedConceptId(id);
                    elem.setAttributeValue(null);
                    if (id < 0) {
                        addToElementsReferringNotCreatedConcepts(id, elem);
                    }
                } else {
                    elem.setAttributeValue(lineParams[k]);
                    elem.setRelatedConceptId(null);
                }
            } // end of for loop iterating on rest of the columns (for data elements)
        } // end of row iterator (while loop on rows)
        processUnseenConceptsForRelatedElements();
    } catch (IOException e) {
        e.printStackTrace();
        throw new ServiceException(e.getMessage());
    } catch (RuntimeException e) {
        e.printStackTrace();
        throw new ServiceException(e.getMessage());
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:io.warp10.continuum.gts.GTSHelper.java

public static GTSEncoder parseJSON(GTSEncoder encoder, String str, Map<String, String> extraLabels, Long now)
        throws IOException, ParseException {

    JsonParser parser = jpf.createFastParser();

    //Gson gson = new Gson();
    //Map<String,Object> o = gson.fromJson(str, GSON_MAP_TYPE);
    Map<String, Object> o = (Map<String, Object>) parser.parse(str);

    String name = (String) o.get("c");
    Map<String, String> labels = (Map<String, String>) o.get("l");

    ///*from w  ww  . j a va  2s  .co  m*/
    // Add any provided extra labels
    //

    if (null != extraLabels) {
        labels.putAll(extraLabels);

        //
        // Remove labels with null values
        //
        // FIXME(hbs): may be removed when dummy tokens have disappeared
        //

        if (extraLabels.containsValue(null)) {
            Set<Entry<String, String>> entries = extraLabels.entrySet();

            while (labels.containsValue(null)) {
                for (Entry<String, String> entry : entries) {
                    if (null == entry.getValue()) {
                        labels.remove(entry.getKey());
                    }
                }
            }
        }
    }

    Object ots = o.get("t");

    long ts = (null != ots ? ((Number) ots).longValue() : (null != now ? (long) now : TimeSource.getTime()));

    long location = GeoTimeSerie.NO_LOCATION;

    if (o.containsKey("lat") && o.containsKey("lon")) {
        double lat = (double) o.get("lat");
        double lon = (double) o.get("lon");

        location = GeoXPLib.toGeoXPPoint(lat, lon);
    }

    long elevation = GeoTimeSerie.NO_ELEVATION;

    if (o.containsKey("elev")) {
        elevation = ((Number) o.get("elev")).longValue();
    }

    Object v = o.get("v");

    // Allocate a new Encoder if need be, with a base timestamp of 0L.
    if (null == encoder || !name.equals(encoder.getName()) || !labels.equals(encoder.getLabels())) {
        encoder = new GTSEncoder(0L);
        encoder.setName(name);
        encoder.setLabels(labels);
    }

    if (v instanceof Long || v instanceof Integer || v instanceof Short || v instanceof Byte
            || v instanceof BigInteger) {
        encoder.addValue(ts, location, elevation, ((Number) v).longValue());
    } else if (v instanceof Double || v instanceof Float) {
        encoder.addValue(ts, location, elevation, ((Number) v).doubleValue());
    } else if (v instanceof BigDecimal) {
        encoder.addValue(ts, location, elevation, v);
    } else if (v instanceof Boolean || v instanceof String) {
        encoder.addValue(ts, location, elevation, v);
    } else {
        throw new ParseException("Invalid value.", 0);
    }

    return encoder;
}