Example usage for java.util LinkedHashMap get

List of usage examples for java.util LinkedHashMap get

Introduction

In this page you can find the example usage for java.util LinkedHashMap get.

Prototype

public V get(Object key) 

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:com.cloud.network.router.VpcNetworkHelperImpl.java

@Override
public void reallocateRouterNetworks(final RouterDeploymentDefinition vpcRouterDeploymentDefinition,
        final VirtualRouter router, final VMTemplateVO template, final HypervisorType hType)
        throws ConcurrentOperationException, InsufficientCapacityException {

    final TreeSet<String> publicVlans = new TreeSet<String>();
    publicVlans.add(vpcRouterDeploymentDefinition.getSourceNatIP().getVlanTag());

    //1) allocate nic for control and source nat public ip
    final LinkedHashMap<Network, List<? extends NicProfile>> networks = configureDefaultNics(
            vpcRouterDeploymentDefinition);

    final Long vpcId = vpcRouterDeploymentDefinition.getVpc().getId();
    //2) allocate nic for private gateways if needed
    final List<PrivateGateway> privateGateways = vpcMgr.getVpcPrivateGateways(vpcId);
    if (privateGateways != null && !privateGateways.isEmpty()) {
        for (final PrivateGateway privateGateway : privateGateways) {
            final NicProfile privateNic = nicProfileHelper.createPrivateNicProfileForGateway(privateGateway,
                    router);/*w w  w .  j  a  v  a2  s .c o  m*/
            final Network privateNetwork = _networkModel.getNetwork(privateGateway.getNetworkId());
            networks.put(privateNetwork, new ArrayList<NicProfile>(Arrays.asList(privateNic)));
        }
    }

    //3) allocate nic for guest gateway if needed
    final List<? extends Network> guestNetworks = vpcMgr.getVpcNetworks(vpcId);
    for (final Network guestNetwork : guestNetworks) {
        if (_networkModel.isPrivateGateway(guestNetwork.getId())) {
            continue;
        }
        if (guestNetwork.getState() == Network.State.Implemented
                || guestNetwork.getState() == Network.State.Setup) {
            final NicProfile guestNic = nicProfileHelper
                    .createGuestNicProfileForVpcRouter(vpcRouterDeploymentDefinition, guestNetwork);
            networks.put(guestNetwork, new ArrayList<NicProfile>(Arrays.asList(guestNic)));
        }
    }

    //4) allocate nic for additional public network(s)
    final List<IPAddressVO> ips = _ipAddressDao.listByAssociatedVpc(vpcId, false);
    final List<NicProfile> publicNics = new ArrayList<NicProfile>();
    Network publicNetwork = null;
    for (final IPAddressVO ip : ips) {
        final PublicIp publicIp = PublicIp.createFromAddrAndVlan(ip, _vlanDao.findById(ip.getVlanId()));
        if ((ip.getState() == IpAddress.State.Allocated || ip.getState() == IpAddress.State.Allocating)
                && vpcMgr.isIpAllocatedToVpc(ip) && !publicVlans.contains(publicIp.getVlanTag())) {
            s_logger.debug("Allocating nic for router in vlan " + publicIp.getVlanTag());
            final NicProfile publicNic = new NicProfile();
            publicNic.setDefaultNic(false);
            publicNic.setIPv4Address(publicIp.getAddress().addr());
            publicNic.setIPv4Gateway(publicIp.getGateway());
            publicNic.setIPv4Netmask(publicIp.getNetmask());
            publicNic.setMacAddress(publicIp.getMacAddress());
            publicNic.setBroadcastType(BroadcastDomainType.Vlan);
            publicNic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(publicIp.getVlanTag()));
            publicNic.setIsolationUri(IsolationType.Vlan.toUri(publicIp.getVlanTag()));
            final NetworkOffering publicOffering = _networkModel
                    .getSystemAccountNetworkOfferings(NetworkOffering.SystemPublicNetwork).get(0);
            if (publicNetwork == null) {
                final List<? extends Network> publicNetworks = _networkMgr.setupNetwork(s_systemAccount,
                        publicOffering, vpcRouterDeploymentDefinition.getPlan(), null, null, false);
                publicNetwork = publicNetworks.get(0);
            }
            publicNics.add(publicNic);
            publicVlans.add(publicIp.getVlanTag());
        }
    }
    if (publicNetwork != null) {
        if (networks.get(publicNetwork) != null) {
            @SuppressWarnings("unchecked")
            final List<NicProfile> publicNicProfiles = (List<NicProfile>) networks.get(publicNetwork);
            publicNicProfiles.addAll(publicNics);
            networks.put(publicNetwork, publicNicProfiles);
        } else {
            networks.put(publicNetwork, publicNics);
        }
    }

    final ServiceOfferingVO routerOffering = _serviceOfferingDao
            .findById(vpcRouterDeploymentDefinition.getServiceOfferingId());

    _itMgr.allocate(router.getInstanceName(), template, routerOffering, networks,
            vpcRouterDeploymentDefinition.getPlan(), hType);
}

From source file:au.org.theark.core.dao.DataExtractionDao.java

public File createGenoCSV(Search search, DataExtractionVO devo, FieldCategory fieldCategory,
        Long maxProcessesPerPipeline, Map<Long, Long> maxInputList, Map<Long, Long> maxOutputList) {
    final String tempDir = System.getProperty("java.io.tmpdir");
    String filename = new String("GENO.csv");
    final java.io.File file = new File(tempDir, filename);

    List<LinkedExtractionVO> genoData = devo.getGenoData();

    OutputStream outputStream;/*from w  ww.  ja v  a 2 s  .c om*/
    try {
        outputStream = new FileOutputStream(file);
        CsvWriter csv = new CsvWriter(outputStream);

        // Header
        csv.write("SUBJECTUID");
        //csv.write("RECORD_DATE_TIME");??

        csv.write(Constants.GENO_FIELDS_PIPELINE_ID);
        csv.write(Constants.GENO_FIELDS_PIPELINE_NAME);
        csv.write(Constants.GENO_FIELDS_PIPELINE_DECSRIPTION);
        for (int processIndex = 1; processIndex <= maxProcessesPerPipeline; processIndex++) { //one-based humanized
            //process
            csv.write(Constants.GENO_FIELDS_PROCESS_ID + "_forProcess_" + processIndex);
            csv.write(Constants.GENO_FIELDS_PROCESS_NAME + "_forProcess_" + processIndex);
            csv.write(Constants.GENO_FIELDS_PROCESS_DESCRIPTION + "_forProcess_" + processIndex);
            csv.write(Constants.GENO_FIELDS_PROCESS_START_TIME + "_forProcess_" + processIndex);
            csv.write(Constants.GENO_FIELDS_PROCESS_END_TIME + "_forProcess_" + processIndex);

            //commmand
            csv.write(Constants.GENO_FIELDS_PROCESS_COMMAND_SERVER_URL + "_" + processIndex);
            csv.write(Constants.GENO_FIELDS_PROCESS_COMMAND_NAME + "_" + processIndex);
            csv.write(Constants.GENO_FIELDS_PROCESS_COMMAND_LOCATION + "_" + processIndex);
            //            csv.write(Constants.GENO_FIELDS_PROCESS_COMMAND_INPUT_FILE_FORMAT)//            csv.write(Constants.GENO_FIELDS_PROCESS_COMMAND_OUTPUT_FILE_FORMAT);

            //input
            //for each of the inputs..........!!!!  EACH - there COULD be more than one
            long maxInputsForThisProcess = 0L;
            if (maxInputList != null && maxInputList.get(new Long(processIndex)) != null) {
                maxInputsForThisProcess = maxInputList.get(new Long(processIndex)).longValue();
            }

            long maxOutputsForThisProcess = 0L;
            if (maxOutputList != null && maxOutputList.get(new Long(processIndex)) != null) {
                maxOutputsForThisProcess = maxOutputList.get(new Long(processIndex)).longValue();
            }

            /**why ther heck isnt this workinG?
            for(long inputIndex=1L ; inputIndex<=maxInputsForThisProcess ; inputIndex++){
               //csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_SERVER);
               csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_SERVER + (processIndex>1?("_forProcess_"+processIndex):"") + "_" + inputIndex );
               csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_LOCATION + (processIndex>1?("_forProcess_"+processIndex):"") + "_" + inputIndex );
               csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_FILE_HASH + (processIndex>1?("_forProcess_"+processIndex):"") + "_" + inputIndex );
               csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_FILE_TYPE + (processIndex>1?("_forProcess_"+processIndex):"") + "_" + inputIndex );
               csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_KEPT + (processIndex>1?("_forProcess_"+processIndex):"") + "_" + inputIndex );
            }*/
            long inputIndex = 1L;
            while (inputIndex <= maxInputsForThisProcess) {
                //csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_SERVER);
                csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_SERVER + "_" + inputIndex + "_forProcess_"
                        + processIndex);
                csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_LOCATION + "_" + inputIndex + "_forProcess_"
                        + processIndex);
                csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_FILE_HASH + "_" + inputIndex + "_forProcess_"
                        + processIndex);
                csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_FILE_TYPE + "_" + inputIndex + "_forProcess_"
                        + processIndex);
                csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_KEPT + "_" + inputIndex + "_forProcess_"
                        + processIndex);
                inputIndex++;
            }

            long outputIndex = 1L;
            while (outputIndex <= maxOutputsForThisProcess) {
                //csv.write(Constants.GENO_FIELDS_PROCESS_OUTPUT_SERVER);
                csv.write(Constants.GENO_FIELDS_PROCESS_OUTPUT_SERVER + "_" + outputIndex + "_forProcess_"
                        + processIndex);
                csv.write(Constants.GENO_FIELDS_PROCESS_OUTPUT_LOCATION + "_" + outputIndex + "_forProcess_"
                        + processIndex);
                csv.write(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_HASH + "_" + outputIndex + "_forProcess_"
                        + processIndex);
                csv.write(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_TYPE + "_" + outputIndex + "_forProcess_"
                        + processIndex);
                csv.write(Constants.GENO_FIELDS_PROCESS_OUTPUT_KEPT + "_" + outputIndex + "_forProcess_"
                        + processIndex);
                outputIndex++;
            }

            /*      long maxInputsForThisProcess = 0L;
                  if(maxInputList!=null && maxInputList.get(new Long(processIndex))!=null){
                     maxInputsForThisProcess = maxInputList.get(new Long(processIndex));
                  }
                  for(long inputIndex=1 ; inputIndex<maxInputsForThisProcess ; inputIndex++){
                     //csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_SERVER);
                     csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_SERVER + (processIndex>1?("_"+processIndex):"") + "_" + inputIndex );
                     csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_LOCATION + (processIndex>1?("_"+processIndex):"") + "_" + inputIndex );
                     csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_FILE_HASH + (processIndex>1?("_"+processIndex):"") + "_" + inputIndex );
                     csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_FILE_TYPE + (processIndex>1?("_"+processIndex):"") + "_" + inputIndex );
                     csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_KEPT + (processIndex>1?("_"+processIndex):"") + "_" + inputIndex );
                  }*/
            /*
                        //input
                        //for each of the inputs..........!!!!  EACH - there COULD be more than one
                        csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_SERVER + "_" + processIndex);
                        csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_LOCATION + "_" + processIndex);
                        csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_FILE_HASH + "_" + processIndex);
                        csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_FILE_TYPE + "_" + processIndex);
                        csv.write(Constants.GENO_FIELDS_PROCESS_INPUT_KEPT + "_" + processIndex);
                                
                        //output
                        //for each of the outputs..........!!!!  EACH - there COULD be more than one
                        csv.write(Constants.GENO_FIELDS_PROCESS_OUTPUT_SERVER + "_forProcess_" + processIndex);
                        csv.write(Constants.GENO_FIELDS_PROCESS_OUTPUT_LOCATION + "_forProcess_" + processIndex);
                        csv.write(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_HASH + "_forProcess_" + processIndex);
                        csv.write(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_TYPE + "_forProcess_" + processIndex);
                        csv.write(Constants.GENO_FIELDS_PROCESS_OUTPUT_KEPT + "_forProcess_" + processIndex);
            */
        }
        csv.endLine();

        //now for the actual data
        for (LinkedExtractionVO evo : genoData) {
            //csv.write(evo.getSubjectUid());//ExtractionVO evo = genoData.get(phenoCollectionId);

            if (evo != null) {
                csv.write(evo.getSubjectUid());
                //csv.write(evo.getRecordDate());
                LinkedHashMap<String, String> keyValues = evo.getKeyValues(); //TODO:  Something should be done to check that values always match order of columns
                /*order is based on the code that constructs this in study dao 
                              Pipeline pl = lssp.getPipeline();
                            map.put(Constants.GENO_FIELDS_PIPELINE_ID, pl.getId().toString());
                            map.put(Constants.GENO_FIELDS_PIPELINE_NAME, pl.getName());
                            map.put(Constants.GENO_FIELDS_PIPELINE_DECSRIPTION, pl.getDescription());
                                    
                            int index = 0;
                            for(Process p : pl.getPipelineProcesses()){
                               index++;
                                       
                               //TODO : obvbiously need to pre=append the pipeline info/count too
                               map.put((Constants.GENO_FIELDS_PROCESS_ID + (index>1?("_"+index):"")), p.getId().toString());
                               map.put((Constants.GENO_FIELDS_PROCESS_NAME + (index>1?("_"+index):"")), p.getName());
                               map.put((Constants.GENO_FIELDS_PROCESS_DESCRIPTION + (index>1?("_"+index):"")), p.getDescription());
                               map.put((Constants.GENO_FIELDS_PROCESS_START_TIME + (index>1?("_"+index):"")), p.getStartTime()!=null?p.getStartTime().toString():"");
                               map.put((Constants.GENO_FIELDS_PROCESS_END_TIME + (index>1?("_"+index):"")), p.getEndTime()!=null?p.getEndTime().toString():"");
                               Command command = p.getCommand();
                               map.put((Constants.GENO_FIELDS_PROCESS_COMMAND_NAME + (index>1?("_"+index):"")), (command==null?"":command.getName()));
                               map.put((Constants.GENO_FIELDS_PROCESS_COMMAND_LOCATION + (index>1?("_"+index):"")), (command==null?"":command.getLocation()));
                               map.put((Constants.GENO_FIELDS_PROCESS_COMMAND_SERVER_URL + (index>1?("_"+index):"")), (command==null?"":command.getServerUrl()));
                */
                for (String key : keyValues.keySet()) {
                    log.info(key + keyValues.get(key));
                }
                csv.write(keyValues.get(Constants.GENO_FIELDS_PIPELINE_ID));

                csv.write(keyValues.get(Constants.GENO_FIELDS_PIPELINE_NAME));
                csv.write(keyValues.get(Constants.GENO_FIELDS_PIPELINE_DECSRIPTION));
                for (int processIndex = 1; processIndex <= maxProcessesPerPipeline; processIndex++) { //one-based humanized
                    if (processIndex == 1) {
                        //process
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_ID) == null) ? ""
                                : keyValues.get(Constants.GENO_FIELDS_PROCESS_ID));
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_NAME) == null) ? ""
                                : keyValues.get(Constants.GENO_FIELDS_PROCESS_NAME));
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_DESCRIPTION) == null) ? ""
                                : keyValues.get(Constants.GENO_FIELDS_PROCESS_DESCRIPTION));
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_START_TIME) == null) ? ""
                                : keyValues.get(Constants.GENO_FIELDS_PROCESS_START_TIME));
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_END_TIME) == null) ? ""
                                : keyValues.get(Constants.GENO_FIELDS_PROCESS_END_TIME));
                        // == null)?"":
                        //commmand
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_COMMAND_SERVER_URL) == null) ? ""
                                : keyValues.get(Constants.GENO_FIELDS_PROCESS_COMMAND_SERVER_URL));
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_COMMAND_NAME) == null) ? ""
                                : keyValues.get(Constants.GENO_FIELDS_PROCESS_COMMAND_NAME));
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_COMMAND_LOCATION) == null) ? ""
                                : keyValues.get(Constants.GENO_FIELDS_PROCESS_COMMAND_LOCATION));
                        //            csv.write(Constants.GENO_FIELDS_PROCESS_COMMAND_INPUT_FILE_FORMAT)//            csv.write(Constants.GENO_FIELDS_PROCESS_COMMAND_OUTPUT_FILE_FORMAT);

                        long maxInputsForThisProcess = 0L;
                        if (maxInputList != null && maxInputList.get(new Long(processIndex)) != null) {
                            maxInputsForThisProcess = maxInputList.get(new Long(processIndex));
                        }
                        long inputIndex = 1L;
                        while (inputIndex <= maxInputsForThisProcess) {
                            //input
                            //for each of the inputs..........!!!!  EACH - there COULD be more than one
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_SERVER + "_"
                                    + processIndex + "_" + inputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_SERVER + "_"
                                                    + processIndex + "_" + inputIndex));
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_LOCATION + "_"
                                    + processIndex + "_" + inputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_LOCATION + "_"
                                                    + processIndex + "_" + inputIndex));
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_FILE_HASH + "_"
                                    + processIndex + "_" + inputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_FILE_HASH + "_"
                                                    + processIndex + "_" + inputIndex));
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_FILE_TYPE + "_"
                                    + processIndex + "_" + inputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_FILE_TYPE + "_"
                                                    + processIndex + "_" + inputIndex));
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_KEPT + "_"
                                    + processIndex + "_" + inputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_KEPT + "_"
                                                    + processIndex + "_" + inputIndex));
                            inputIndex++;
                        }

                        long maxOutputsForThisProcess = 0L;
                        if (maxOutputList != null && maxOutputList.get(new Long(processIndex)) != null) {
                            maxOutputsForThisProcess = maxOutputList.get(new Long(processIndex));
                        }
                        for (long outputIndex = 1L; outputIndex <= maxOutputsForThisProcess; outputIndex++) {
                            //output
                            //for each of the outputs..........!!!!  EACH - there COULD be more than one
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_SERVER + "_"
                                    + processIndex + "_" + outputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_SERVER + "_"
                                                    + processIndex + "_" + outputIndex));
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_LOCATION + "_"
                                    + processIndex + "_" + outputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_LOCATION + "_"
                                                    + processIndex + "_" + outputIndex));
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_HASH + "_"
                                    + processIndex + "_" + outputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_HASH + "_"
                                                    + processIndex + "_" + outputIndex));
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_TYPE + "_"
                                    + processIndex + "_" + outputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_TYPE + "_"
                                                    + processIndex + "_" + outputIndex));
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_KEPT + "_"
                                    + processIndex + "_" + outputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_KEPT + "_"
                                                    + processIndex + "_" + outputIndex));
                        }

                        log.info("\n\nprocess=" + processIndex + "    \n max in=" + maxInputsForThisProcess
                                + "   \n  max outs=" + maxOutputsForThisProcess + "\nequation="
                                + (inputIndex < maxInputsForThisProcess));

                        /*
                        //output
                        //for each of the outputs..........!!!!  EACH - there COULD be more than one
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_SERVER)== null)?"":keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_SERVER));
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_LOCATION)== null)?"":keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_LOCATION));
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_HASH)== null)?"":keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_HASH));
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_TYPE)== null)?"":keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_TYPE));
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_KEPT)== null)?"":keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_KEPT));*/
                    } else {
                        //process
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_ID + "_" + processIndex) == null)
                                ? ""
                                : keyValues.get(Constants.GENO_FIELDS_PROCESS_ID + "_" + processIndex));
                        csv.write(
                                (keyValues.get(Constants.GENO_FIELDS_PROCESS_NAME + "_" + processIndex) == null)
                                        ? ""
                                        : keyValues
                                                .get(Constants.GENO_FIELDS_PROCESS_NAME + "_" + processIndex));
                        csv.write((keyValues
                                .get(Constants.GENO_FIELDS_PROCESS_DESCRIPTION + "_" + processIndex) == null)
                                        ? ""
                                        : keyValues.get(Constants.GENO_FIELDS_PROCESS_DESCRIPTION + "_"
                                                + processIndex));
                        csv.write((keyValues
                                .get(Constants.GENO_FIELDS_PROCESS_START_TIME + "_" + processIndex) == null)
                                        ? ""
                                        : keyValues.get(
                                                Constants.GENO_FIELDS_PROCESS_START_TIME + "_" + processIndex));
                        csv.write((keyValues
                                .get(Constants.GENO_FIELDS_PROCESS_END_TIME + "_" + processIndex) == null) ? ""
                                        : keyValues.get(
                                                Constants.GENO_FIELDS_PROCESS_END_TIME + "_" + processIndex));

                        //commmand
                        csv.write((keyValues.get(
                                Constants.GENO_FIELDS_PROCESS_COMMAND_SERVER_URL + "_" + processIndex) == null)
                                        ? ""
                                        : keyValues.get(Constants.GENO_FIELDS_PROCESS_COMMAND_SERVER_URL + "_"
                                                + processIndex));
                        csv.write((keyValues
                                .get(Constants.GENO_FIELDS_PROCESS_COMMAND_NAME + "_" + processIndex) == null)
                                        ? ""
                                        : keyValues.get(Constants.GENO_FIELDS_PROCESS_COMMAND_NAME + "_"
                                                + processIndex));
                        csv.write((keyValues.get(
                                Constants.GENO_FIELDS_PROCESS_COMMAND_LOCATION + "_" + processIndex) == null)
                                        ? ""
                                        : keyValues.get(Constants.GENO_FIELDS_PROCESS_COMMAND_LOCATION + "_"
                                                + processIndex));
                        //            csv.write((Constants.GENO_FIELDS_PROCESS_COMMAND_INPUT_FILE_FORMAT)//            csv.write(Constants.GENO_FIELDS_PROCESS_COMMAND_OUTPUT_FILE_FORMAT));

                        long maxInputsForThisProcess = 0L;
                        if (maxInputList != null && maxInputList.get(new Long(processIndex)) != null) {
                            maxInputsForThisProcess = maxInputList.get(new Long(processIndex));
                        }

                        long inputIndex = 1L;
                        while (inputIndex <= maxInputsForThisProcess) {
                            log.info("pr=" + processIndex + " in=" + inputIndex);
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_SERVER + "_"
                                    + processIndex + "_" + inputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_SERVER + "_"
                                                    + processIndex + "_" + inputIndex));
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_LOCATION + "_"
                                    + processIndex + "_" + inputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_LOCATION + "_"
                                                    + processIndex + "_" + inputIndex));
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_FILE_HASH + "_"
                                    + processIndex + "_" + inputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_FILE_HASH + "_"
                                                    + processIndex + "_" + inputIndex));
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_FILE_TYPE + "_"
                                    + processIndex + "_" + inputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_FILE_TYPE + "_"
                                                    + processIndex + "_" + inputIndex));
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_KEPT + "_"
                                    + processIndex + "_" + inputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_INPUT_KEPT + "_"
                                                    + processIndex + "_" + inputIndex));
                            inputIndex++;
                        }

                        long maxOutputsForThisProcess = 0L;
                        if (maxOutputList != null && maxOutputList.get(new Long(processIndex)) != null) {
                            maxOutputsForThisProcess = maxOutputList.get(new Long(processIndex));
                        }

                        log.info("\n\nprocess=" + processIndex + "    \n max in=" + maxInputsForThisProcess
                                + "   \n  max outs=" + maxOutputsForThisProcess + "\nequation="
                                + (inputIndex < maxInputsForThisProcess));

                        for (long outputIndex = 1; outputIndex <= maxOutputsForThisProcess; outputIndex++) {
                            //output
                            //for each of the outputs..........!!!!  EACH - there COULD be more than one
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_SERVER + "_"
                                    + processIndex + "_" + outputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_SERVER + "_"
                                                    + processIndex + "_" + outputIndex));
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_LOCATION + "_"
                                    + processIndex + "_" + outputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_LOCATION + "_"
                                                    + processIndex + "_" + outputIndex));
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_HASH + "_"
                                    + processIndex + "_" + outputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_HASH + "_"
                                                    + processIndex + "_" + outputIndex));
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_TYPE + "_"
                                    + processIndex + "_" + outputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_TYPE + "_"
                                                    + processIndex + "_" + outputIndex));
                            csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_KEPT + "_"
                                    + processIndex + "_" + outputIndex) == null) ? ""
                                            : keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_KEPT + "_"
                                                    + processIndex + "_" + outputIndex));
                        }

                        /*output
                        //for each of the outputs..........!!!!  EACH - there COULD be more than one
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_SERVER + "_" + processIndex)== null)?"":keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_SERVER + "_" + processIndex));
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_LOCATION + "_" + processIndex)== null)?"":keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_LOCATION + "_" + processIndex));
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_HASH + "_" + processIndex)== null)?"":keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_HASH + "_" + processIndex));
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_TYPE + "_" + processIndex)== null)?"":keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_FILE_TYPE + "_" + processIndex));
                        csv.write((keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_KEPT + "_" + processIndex)== null)?"":keyValues.get(Constants.GENO_FIELDS_PROCESS_OUTPUT_KEPT + "_" + processIndex));
                         */
                    }
                }

                //TODO:  replace this with hardcoded use of the field names or use the function if 
                //      available to getColumnOf(GENO_FIELD_PIPELINE_ID) and put it in there at appropriate line

                /*
                 * TODO ASAP  : Change this to iterating in order so naming remains the same
                 *
                 * THIS CODE WORKS BUT WE MAY WANT TO MAKE SURE THAT WE HAVE THE CORRECT ORDER
                 *         
                for (String key : keyValues.keySet()) {
                        
                   String valueResult = keyValues.get(key);
                   if (valueResult != null) {
                      if(key.startsWith(Constants.GENO_FIELDS_PROCESS_END_TIME) || key.startsWith(Constants.GENO_FIELDS_PROCESS_START_TIME)){
                try {
                   DateFormat dateFormat = new SimpleDateFormat(au.org.theark.core.Constants.DD_MM_YYYY);
                   String[] dateFormats = { au.org.theark.core.Constants.DD_MM_YYYY, au.org.theark.core.Constants.yyyy_MM_dd_hh_mm_ss_S };
                   Date date = DateUtils.parseDate(valueResult, dateFormats);
                   csv.write(dateFormat.format(date));
                }
                catch (ParseException e) {
                   csv.write(valueResult);
                }
                      }
                      else{
                csv.write(valueResult);
                      }
                   }
                   else {
                      csv.write("");
                   }
                } */
            } else {
                //not sure if we need this
                //               // Write out a line with no values (no data existed for subject in question
                //               for (CustomFieldDisplay cfd : cfds) {
                //                  csv.write("");
                //               }
            }

            csv.endLine();
        }
        csv.close();
    } catch (FileNotFoundException e) {
        log.error(e.getMessage());
    }

    return file;
}

From source file:edu.internet2.middleware.psp.Psp.java

/**
 * Return the SPMLv2 target object for the given target id suitable for inclusion in a list targets request.
 * // w ww . jav  a2  s  .  co m
 * @param targetId the target id
 * @return the SPMLv2 target object or null if the target id is unknown.
 * @throws Spml2Exception if an SPMLv2 toolkit error occursF
 */
public org.openspml.v2.msg.spml.Target getSpmlTarget(String targetId) throws Spml2Exception {

    if (!objects.containsKey(targetId)) {
        return null;
    }

    org.openspml.v2.msg.spml.Target target = new org.openspml.v2.msg.spml.Target();
    target.setTargetID(targetId);
    // FUTURE support XSD ?
    target.setProfile(new DSMLProfileRegistrar().getProfileURI());

    Schema schema = new Schema();

    // FUTURE support other schemas ?
    DSMLSchema dsmlSchema = new DSMLSchema();

    CapabilitiesList cl = new CapabilitiesList();

    LinkedHashMap<String, SchemaEntityRef> schemaEntityRefMap = new LinkedHashMap<String, SchemaEntityRef>();

    for (Pso psoDefinition : objects.get(targetId)) {
        SchemaEntityRef entity = new SchemaEntityRef();
        entity.setEntityName(psoDefinition.getId());
        entity.setTargetID(getId());
        schemaEntityRefMap.put(entity.getEntityName(), entity);

        schema.addSupportedSchemaEntity(entity);

        ObjectClassDefinition objectClassDef = new ObjectClassDefinition();
        objectClassDef.setName(psoDefinition.getId());

        AttributeDefinitionReferences attrRefs = new AttributeDefinitionReferences();

        for (PsoAttribute psoAttributeDefinition : psoDefinition.getPsoAttributes()) {
            AttributeDefinition attrDef = new AttributeDefinition();
            attrDef.setName(psoAttributeDefinition.getName());
            dsmlSchema.addAttributeDefinition(attrDef);

            AttributeDefinitionReference attrDefRef = new AttributeDefinitionReference();
            attrDefRef.setName(psoAttributeDefinition.getName());
            // FUTURE attrRef.setRequired(required);
            attrRefs.addAttributeDefinitionReference(attrDefRef);
        }

        objectClassDef.setMemberAttributes(attrRefs);
        dsmlSchema.addObjectClassDefinition(objectClassDef);
    }

    for (Pso psoDefinition : objects.get(targetId)) {
        for (PsoReferences psoReferencesDefinition : psoDefinition.getReferences()) {
            for (PsoReference psoReferenceDefinition : psoReferencesDefinition.getPsoReferences()) {
                SchemaEntityRef fromEntity = schemaEntityRefMap.get(psoDefinition.getId());
                SchemaEntityRef toEntity = schemaEntityRefMap.get(psoReferenceDefinition.getToObject().getId());

                Capability capability = new Capability();
                capability.setNamespaceURI(PsoReferences.REFERENCE_URI);
                capability.addAppliesTo(fromEntity);
                cl.addCapability(capability);

                ReferenceDefinition rd = new ReferenceDefinition();
                rd.setTypeOfReference(psoReferencesDefinition.getName());
                rd.setSchemaEntity(fromEntity);
                rd.addCanReferTo(toEntity);

                OCEtoMarshallableAdapter oce = new OCEtoMarshallableAdapter(rd);
                capability.addOpenContentElement(oce);
            }
        }
    }

    target.setCapabilities(cl);
    schema.addOpenContentElement(dsmlSchema);
    target.addSchema(schema);

    return target;
}

From source file:com.twinsoft.convertigo.engine.migration.Migration7_0_0.java

public static void migrate(final String projectName) {
    try {//from  w  w  w  .j av a 2s. c  om
        Map<String, Reference> referenceMap = new HashMap<String, Reference>();
        XmlSchema projectSchema = null;

        Project project = Engine.theApp.databaseObjectsManager.getOriginalProjectByName(projectName, false);

        // Copy all xsd files to project's xsd directory
        File destDir = new File(project.getXsdDirPath());
        copyXsdOfProject(projectName, destDir);

        String projectWsdlFilePath = Engine.PROJECTS_PATH + "/" + projectName + "/" + projectName + ".wsdl";
        File wsdlFile = new File(projectWsdlFilePath);

        String projectXsdFilePath = Engine.PROJECTS_PATH + "/" + projectName + "/" + projectName + ".xsd";
        File xsdFile = new File(projectXsdFilePath);

        if (xsdFile.exists()) {
            // Load project schema from old XSD file
            XmlSchemaCollection collection = new XmlSchemaCollection();
            collection.setSchemaResolver(new DefaultURIResolver() {
                public InputSource resolveEntity(String targetNamespace, String schemaLocation,
                        String baseUri) {
                    // Case of a c8o project location
                    if (schemaLocation.startsWith("../") && schemaLocation.endsWith(".xsd")) {
                        try {
                            String targetProjectName = schemaLocation.substring(3,
                                    schemaLocation.indexOf("/", 3));
                            File pDir = new File(Engine.PROJECTS_PATH + "/" + targetProjectName);
                            if (pDir.exists()) {
                                File pFile = new File(Engine.PROJECTS_PATH + schemaLocation.substring(2));
                                // Case c8o project is already migrated
                                if (!pFile.exists()) {
                                    Document doc = Engine.theApp.schemaManager
                                            .getSchemaForProject(targetProjectName).getSchemaDocument();
                                    DOMSource source = new DOMSource(doc);
                                    StringWriter writer = new StringWriter();
                                    StreamResult result = new StreamResult(writer);
                                    TransformerFactory.newInstance().newTransformer().transform(source, result);
                                    StringReader reader = new StringReader(writer.toString());
                                    return new InputSource(reader);
                                }
                            }
                            return null;
                        } catch (Exception e) {
                            Engine.logDatabaseObjectManager
                                    .warn("[Migration 7.0.0] Unable to find schema location \"" + schemaLocation
                                            + "\"", e);
                            return null;
                        }
                    } else if (schemaLocation.indexOf("://") == -1 && schemaLocation.endsWith(".xsd")) {
                        return super.resolveEntity(targetNamespace, schemaLocation,
                                Engine.PROJECTS_PATH + "/" + projectName);
                    }
                    return super.resolveEntity(targetNamespace, schemaLocation, baseUri);
                }

            });
            projectSchema = SchemaUtils.loadSchema(new File(projectXsdFilePath), collection);
            ConvertigoError.updateXmlSchemaObjects(projectSchema);
            SchemaMeta.setCollection(projectSchema, collection);

            for (Connector connector : project.getConnectorsList()) {
                for (Transaction transaction : connector.getTransactionsList()) {
                    try {
                        // Migrate transaction in case of a Web Service consumption project
                        if (transaction instanceof XmlHttpTransaction) {
                            XmlHttpTransaction xmlHttpTransaction = (XmlHttpTransaction) transaction;
                            String reqn = xmlHttpTransaction.getResponseElementQName();
                            if (!reqn.equals("")) {
                                boolean useRef = reqn.indexOf(";") == -1;
                                // Doc/Literal case
                                if (useRef) {
                                    try {
                                        String[] qn = reqn.split(":");
                                        QName refName = new QName(
                                                projectSchema.getNamespaceContext().getNamespaceURI(qn[0]),
                                                qn[1]);
                                        xmlHttpTransaction.setXmlElementRefAffectation(new XmlQName(refName));
                                    } catch (Exception e) {
                                    }
                                }
                                // RPC case
                                else {
                                    int index, index2;
                                    try {
                                        index = reqn.indexOf(";");
                                        String opName = reqn.substring(0, index);
                                        if ((index2 = reqn.indexOf(";", index + 1)) != -1) {
                                            String eltName = reqn.substring(index + 1, index2);
                                            String eltType = reqn.substring(index2 + 1);
                                            String[] qn = eltType.split(":");

                                            QName typeName = new QName(
                                                    projectSchema.getNamespaceContext().getNamespaceURI(qn[0]),
                                                    qn[1]);
                                            String responseElementQName = opName + ";" + eltName + ";" + "{"
                                                    + typeName.getNamespaceURI() + "}"
                                                    + typeName.getLocalPart();
                                            xmlHttpTransaction.setResponseElementQName(responseElementQName);
                                        }
                                    } catch (Exception e) {
                                    }
                                }
                            }
                        }

                        // Retrieve required XmlSchemaObjects for transaction
                        QName requestQName = new QName(project.getTargetNamespace(),
                                transaction.getXsdRequestElementName());
                        QName responseQName = new QName(project.getTargetNamespace(),
                                transaction.getXsdResponseElementName());
                        LinkedHashMap<QName, XmlSchemaObject> map = new LinkedHashMap<QName, XmlSchemaObject>();
                        XmlSchemaWalker dw = XmlSchemaWalker.newDependencyWalker(map, true, false);
                        dw.walkByElementRef(projectSchema, requestQName);
                        dw.walkByElementRef(projectSchema, responseQName);

                        // Create transaction schema
                        String targetNamespace = projectSchema.getTargetNamespace();
                        String prefix = projectSchema.getNamespaceContext().getPrefix(targetNamespace);
                        XmlSchema transactionSchema = SchemaUtils.createSchema(prefix, targetNamespace,
                                XsdForm.unqualified.name(), XsdForm.unqualified.name());

                        // Add required prefix declarations
                        List<String> nsList = new LinkedList<String>();
                        for (QName qname : map.keySet()) {
                            String nsURI = qname.getNamespaceURI();
                            if (!nsURI.equals(Constants.URI_2001_SCHEMA_XSD)) {
                                if (!nsList.contains(nsURI)) {
                                    nsList.add(nsURI);
                                }
                            }
                            String nsPrefix = qname.getPrefix();
                            if (!nsURI.equals(targetNamespace)) {
                                NamespaceMap nsMap = SchemaUtils.getNamespaceMap(transactionSchema);
                                if (nsMap.getNamespaceURI(nsPrefix) == null) {
                                    nsMap.add(nsPrefix, nsURI);
                                    transactionSchema.setNamespaceContext(nsMap);
                                }
                            }
                        }

                        // Add required imports
                        for (String namespaceURI : nsList) {
                            XmlSchemaObjectCollection includes = projectSchema.getIncludes();
                            for (int i = 0; i < includes.getCount(); i++) {
                                XmlSchemaObject xmlSchemaObject = includes.getItem(i);
                                if (xmlSchemaObject instanceof XmlSchemaImport) {
                                    if (((XmlSchemaImport) xmlSchemaObject).getNamespace()
                                            .equals(namespaceURI)) {

                                        // do not allow import with same ns !
                                        if (namespaceURI.equals(project.getTargetNamespace()))
                                            continue;

                                        String location = ((XmlSchemaImport) xmlSchemaObject)
                                                .getSchemaLocation();

                                        // This is a convertigo project reference
                                        if (location.startsWith("../")) {
                                            // Copy all xsd files to xsd directory
                                            String targetProjectName = location.substring(3,
                                                    location.indexOf("/", 3));
                                            copyXsdOfProject(targetProjectName, destDir);
                                        }

                                        // Add reference
                                        addReferenceToMap(referenceMap, namespaceURI, location);

                                        // Add import
                                        addImport(transactionSchema, namespaceURI, location);
                                    }
                                }
                            }
                        }

                        QName responseTypeQName = new QName(project.getTargetNamespace(),
                                transaction.getXsdResponseTypeName());

                        // Add required schema objects
                        for (QName qname : map.keySet()) {
                            if (qname.getNamespaceURI().equals(targetNamespace)) {
                                XmlSchemaObject ob = map.get(qname);

                                if (qname.getLocalPart().startsWith("ConvertigoError"))
                                    continue;
                                transactionSchema.getItems().add(ob);

                                // Add missing response error element and attributes
                                if (qname.equals(responseTypeQName)) {
                                    Transaction.addSchemaResponseObjects(transactionSchema,
                                            (XmlSchemaComplexType) ob);
                                }
                            }
                        }

                        // Add missing ResponseType (with document)
                        if (map.containsKey(responseTypeQName)) {
                            Transaction.addSchemaResponseType(transactionSchema, transaction);
                        }

                        // Add everything
                        if (map.isEmpty()) {
                            Transaction.addSchemaObjects(transactionSchema, transaction);
                        }

                        // Add c8o error objects (for internal xsd edition only)
                        ConvertigoError.updateXmlSchemaObjects(transactionSchema);

                        // Save schema to file
                        String transactionXsdFilePath = transaction.getSchemaFilePath();
                        new File(transaction.getSchemaFileDirPath()).mkdirs();
                        SchemaUtils.saveSchema(transactionXsdFilePath, transactionSchema);
                    } catch (Exception e) {
                        Engine.logDatabaseObjectManager
                                .error("[Migration 7.0.0] An error occured while migrating transaction \""
                                        + transaction.getName() + "\"", e);
                    }

                    if (transaction instanceof TransactionWithVariables) {
                        TransactionWithVariables transactionVars = (TransactionWithVariables) transaction;
                        handleRequestableVariable(transactionVars.getVariablesList());

                        // Change SQLQuery variables : i.e. {id} --> {{id}}
                        if (transaction instanceof SqlTransaction) {
                            String sqlQuery = ((SqlTransaction) transaction).getSqlQuery();

                            sqlQuery = sqlQuery.replaceAll("\\{([a-zA-Z0-9_]+)\\}", "{{$1}}");
                            ((SqlTransaction) transaction).setSqlQuery(sqlQuery);
                        }

                    }
                }
            }
        } else {// Should only happen for projects which version <= 4.6.0 
            XmlSchemaCollection collection = new XmlSchemaCollection();
            String prefix = project.getName() + "_ns";
            projectSchema = SchemaUtils.createSchema(prefix, project.getNamespaceUri(),
                    XsdForm.unqualified.name(), XsdForm.unqualified.name());
            ConvertigoError.addXmlSchemaObjects(projectSchema);
            SchemaMeta.setCollection(projectSchema, collection);

            for (Connector connector : project.getConnectorsList()) {
                for (Transaction transaction : connector.getTransactionsList()) {
                    if (transaction instanceof TransactionWithVariables) {
                        TransactionWithVariables transactionVars = (TransactionWithVariables) transaction;
                        handleRequestableVariable(transactionVars.getVariablesList());
                    }
                }
            }
        }

        // Handle sequence objects
        for (Sequence sequence : project.getSequencesList()) {
            handleSteps(projectSchema, referenceMap, sequence.getSteps());
            handleRequestableVariable(sequence.getVariablesList());
        }

        // Add all references to project
        if (!referenceMap.isEmpty()) {
            for (Reference reference : referenceMap.values())
                project.add(reference);
        }

        // Delete XSD file
        if (xsdFile.exists())
            xsdFile.delete();

        // Delete WSDL file
        if (wsdlFile.exists())
            wsdlFile.delete();

    } catch (Exception e) {
        Engine.logDatabaseObjectManager
                .error("[Migration 7.0.0] An error occured while migrating project \"" + projectName + "\"", e);
    }
}

From source file:edu.jhuapl.openessence.controller.ReportController.java

private GraphObject createGraph(OeDataSource dataSource, final String userPrincipalName,
        final Collection<Record> records, final Dimension dimension, final Dimension filter,
        final Dimension accumulation, DefaultGraphData data, ChartModel chart, List<Filter> filters) {

    String filterId = (filter == null) ? dimension.getId() : filter.getId();
    Map<String, String> possibleKeyValueMap = null;
    if (dimension.getPossibleValuesConfiguration() != null
            && dimension.getPossibleValuesConfiguration().getData() != null) {
        List<List<Object>> dataMap = dimension.getPossibleValuesConfiguration().getData();
        possibleKeyValueMap = new HashMap<String, String>();
        for (int i = 0; i < dataMap.size(); i++) {
            String dispVal = dataMap.get(i).size() == 2 ? dataMap.get(i).get(1).toString()
                    : dataMap.get(i).get(0).toString();
            possibleKeyValueMap.put(dataMap.get(i).get(0).toString(), dispVal);
        }//from   w  ww  . ja  v  a  2s .  c  om
    }

    GraphDataSerializeToDiskHandler hndl = new GraphDataSerializeToDiskHandler(graphDir);
    GraphObject graph = null;

    Color[] colorsFromHex = null;
    //only set an array if they provided one
    if (!ArrayUtils.isEmpty(chart.getGraphBaseColors())) {
        colorsFromHex = ControllerUtils.getColorsFromHex(Color.BLUE, chart.getGraphBaseColors());
        //TODO when we limit the series these colors need augmented.  Create a map of id = graphbasecolor[index] first, then use that map to create a
        //new graph base color array that combines the parameter list with the default list...
        data.setGraphBaseColors(colorsFromHex);
    }

    GraphController gc = getGraphController(null, hndl, userPrincipalName);

    List<Record> recs = new ArrayList<Record>(records);

    String otherLabel = messageSource.getDataSourceMessage("graph.category.other", dataSource);

    LinkedHashMap<String, ChartData> recordMap = getRecordMap(recs, accumulation.getId(), dimension.getId(),
            filterId);
    //perform series limit
    recordMap = ControllerUtils.getSortedAndLimitedChartDataMap(recordMap, chart.getCategoryLimit(),
            otherLabel);

    //if there is no data (all zeros for a pie chart) the chart will not display anything
    if (!ControllerUtils.isCollectionValued(getCountsForChart(recordMap)) && !chart.isShowNoDataGraph()) {
        //this will hide the title and message if there is no data
        data.setGraphTitle("");
        data.setNoDataMessage("");
    }

    // Create urls for each slice/bar
    DataSeriesSource dss = null;
    StringBuilder jsCall = new StringBuilder();
    jsCall.append("javascript:OE.report.datasource.showDetails({");

    if (dataSource instanceof DataSeriesSource) {
        dss = (DataSeriesSource) dataSource;

        Collection<Dimension> dims = new ArrayList<Dimension>(dss.getResultDimensions());
        Collection<String> dimIds = ControllerUtils.getDimensionIdsFromCollection(dims);

        Collection<Dimension> accums = new ArrayList<Dimension>(dss.getAccumulations());

        for (Dimension d : accums) {
            if (dimIds.contains(d.getId()) && d.getId().equals(accumulation.getId())) {

            } else {
                dimIds.remove(d.getId());
            }
        }

        jsCall.append("dsId:'").append(dss.getClass().getName()).append("'");
        //specify results
        jsCall.append(",results:[").append(StringUtils.collectionToDelimitedString(dimIds, ",", "'", "'"))
                .append(']');
        //specify accumId
        jsCall.append(",accumId:'").append(accumulation.getId()).append("'");

        addJavaScriptFilters(jsCall, filters, dimension.getId());
    }

    int rSize = recordMap.size();
    int aSize = 1;
    String[] lbl = new String[rSize];
    String[][] txtb = new String[1][rSize];
    double[][] bardat = new double[aSize][rSize];
    String[][] txtp = new String[rSize][1];
    double[][] piedat = new double[rSize][aSize];
    String[][] urlsP = new String[rSize][1];
    String[][] urlsB = new String[1][rSize];
    int i = 0;
    double totalCount = 0;
    DecimalFormat df = new DecimalFormat("#.##");

    for (String key : recordMap.keySet()) {
        if (recordMap.get(key) != null && recordMap.get(key).getCount() != null
                && !recordMap.get(key).getCount().isNaN()) {
            totalCount += recordMap.get(key).getCount();
        }
    }

    for (String key : recordMap.keySet()) {
        Double dubVal = recordMap.get(key).getCount();
        String strPercentVal = df.format(100 * dubVal / totalCount);
        lbl[i] = recordMap.get(key).getName();
        //create bar data set
        bardat[0][i] = dubVal;
        txtb[0][i] = lbl[i] + " - " + Double.toString(dubVal) + " (" + strPercentVal + "%)";
        if (lbl[i].length() > DEFAULT_LABEL_LENGTH) {
            lbl[i] = lbl[i].substring(0, DEFAULT_LABEL_LENGTH - 3) + "...";
        }
        //create pie data set
        piedat[i][0] = dubVal;
        txtp[i][0] = lbl[i] + " - " + Double.toString(dubVal) + " (" + strPercentVal + "%)";
        if (lbl[i].length() > DEFAULT_LABEL_LENGTH) {
            lbl[i] = lbl[i].substring(0, DEFAULT_LABEL_LENGTH - 3) + "...";
        }
        //TODO all "Others" to return details of all results except for those in recordMap.keyset
        //We need a "Not" filter
        if (!otherLabel.equals(key)) {
            if (dataSource instanceof DataSeriesSource) {
                if (dimension.getId().equals(filterId) && possibleKeyValueMap != null) {
                    if (possibleKeyValueMap.containsKey(key)) {
                        urlsP[i][0] = jsCall.toString() + "," + filterId + ":'" + key + "'" + "});";
                        urlsB[0][i] = jsCall.toString() + "," + filterId + ":'" + key + "'" + "});";
                    } else {
                        urlsP[i][0] = jsCall.toString() + "});";
                        urlsB[0][i] = jsCall.toString() + "});";
                    }
                } else {
                    if (key == null || key.equals("")
                            || key.equals(messageSource.getMessage("graph.dimension.null", "Empty Value"))) {
                        // TODO: This is when we have an ID field also marked as isResult:true and the value is null
                        // We can not provide url param filterId:null as field can be numeric and we get a java.lang.NumberFormatException...
                        urlsP[i][0] = jsCall.toString() + "});";
                        urlsB[0][i] = jsCall.toString() + "});";
                    } else {
                        urlsP[i][0] = jsCall.toString() + "," + filterId + ":'" + key + "'" + "});";
                        urlsB[0][i] = jsCall.toString() + "," + filterId + ":'" + key + "'" + "});";
                    }
                }
            }
        }

        i++;
    }

    if (BAR.equalsIgnoreCase(chart.getType())) {
        data.setCounts(bardat);
        data.setXLabels(lbl);
        data.setMaxLabeledCategoryTicks(rSize);
        data.setAltTexts(txtb);
        if (jsCall.length() > 0) {
            data.setLineSetURLs(urlsB);
        }
        //TODO add encoding?
        graph = gc.createBarGraph(data, false, true);
    } else if (PIE.equalsIgnoreCase(chart.getType())) {
        data.setCounts(piedat);
        data.setLineSetLabels(lbl);
        data.setAltTexts(txtp);
        if (jsCall.length() > 0) {
            data.setLineSetURLs(urlsP);
        }
        graph = gc.createPieGraph(data, Encoding.PNG_WITH_TRANSPARENCY);
    }
    return graph;
}

From source file:com.allinfinance.startup.init.MenuInfoUtil.java

/**
 * ???/* w ww .j a  v a  2 s  .  c  o m*/
 * @param degree
 */
@SuppressWarnings("unchecked")
public static LinkedHashMap<String, Object> setOperatorMenuWithDegree(String degree, String contextPath) {
    String sql = "select VALUE_ID FROM TBL_ROLE_FUNC_MAP ,TBL_ROLE_INF WHERE ROLE_ID = KEY_ID and KEY_ID = "
            + degree;
    ICommQueryDAO commQueryDAO = (ICommQueryDAO) ContextUtil.getBean("CommQueryDAO");
    List<Object> funcMapList = commQueryDAO.findBySQLQuery(sql);
    List<Object> menuLvl1List = allMenuBean.getDataList();
    LinkedHashMap<String, Object> menuIndexMap = new LinkedHashMap<String, Object>();
    //?????
    for (int i = 0, n = menuLvl1List.size(); i < n; i++) {
        Map<String, Object> menuLvl1Map = (Map<String, Object>) menuLvl1List.get(i);
        LinkedList<Object> menuLvl2List = (LinkedList<Object>) menuLvl1Map.get(Constants.MENU_CHILDREN);
        for (int j = 0, m = menuLvl2List.size(); j < m; j++) {
            Map<String, Object> menuLvl2Map = (Map<String, Object>) menuLvl2List.get(j);
            LinkedList<Object> menuLvl3List = (LinkedList<Object>) menuLvl2Map.get(Constants.MENU_CHILDREN);
            for (int k = 0, l = menuLvl3List.size(); k < l; k++) {
                Map<String, Object> menuLvl3Map = (Map<String, Object>) menuLvl3List.get(k);
                for (int a = 0, b = funcMapList.size(); a < b; a++) {
                    if (StringUtils.trim(funcMapList.get(a).toString())
                            .equals(StringUtils.trim(menuLvl3Map.get(Constants.MENU_ID).toString()))) {
                        if (!menuIndexMap.containsKey(menuLvl1Map.get(Constants.MENU_ID).toString())) {
                            Map<String, Object> menuLvl1HashMap = new LinkedHashMap<String, Object>();
                            menuLvl1HashMap.put(Constants.MENU_ID, menuLvl1Map.get(Constants.MENU_ID));
                            menuLvl1HashMap.put(Constants.MENU_TEXT, menuLvl1Map.get(Constants.MENU_TEXT));
                            menuLvl1HashMap.put(Constants.MENU_CLS, menuLvl1Map.get(Constants.MENU_CLS));
                            menuLvl1HashMap.put(Constants.MENU_HANDLER, Constants.MENU_LVL1_FUNC);
                            menuLvl1HashMap.put(Constants.TOOL_BAR_TYPE, Constants.TOOL_BAR_BUTTON);
                            menuLvl1HashMap.put(Constants.TOOLBAR_ICON, Constants.TOOLBAR_ICON_MENU);

                            Map<String, Object> menuLvl2HashMap = new LinkedHashMap<String, Object>();
                            menuLvl2HashMap.put(Constants.MENU_ID, menuLvl2Map.get(Constants.MENU_ID));
                            menuLvl2HashMap.put(Constants.MENU_TEXT, menuLvl2Map.get(Constants.MENU_TEXT));
                            menuLvl2HashMap.put(Constants.MENU_PARENT_ID,
                                    menuLvl2Map.get(Constants.MENU_PARENT_ID));
                            menuLvl2HashMap.put(Constants.MENU_CLS, menuLvl2Map.get(Constants.MENU_CLS));
                            //                        menuLvl2HashMap.put(Constants.TOOLBAR_ICON, Constants.TOOLBAR_ICON_MENUITEM);

                            //
                            menuLvl2HashMap.put(Constants.TOOLBAR_ICON,
                                    menuLvl2Map.get(Constants.TOOLBAR_ICON));

                            Map<String, Object> menuLvl3HashMap = new LinkedHashMap<String, Object>();
                            menuLvl3HashMap.put(Constants.MENU_ID, menuLvl3Map.get(Constants.MENU_ID));
                            menuLvl3HashMap.put(Constants.MENU_TEXT, menuLvl3Map.get(Constants.MENU_TEXT));
                            menuLvl3HashMap.put(Constants.MENU_PARENT_ID,
                                    menuLvl3Map.get(Constants.MENU_PARENT_ID));
                            menuLvl3HashMap.put(Constants.MENU_LEAF, true);
                            menuLvl3HashMap.put(Constants.MENU_URL,
                                    contextPath + menuLvl3Map.get(Constants.MENU_URL));
                            menuLvl3HashMap.put(Constants.MENU_CLS, menuLvl3Map.get(Constants.MENU_CLS));
                            menuLvl3HashMap.put(Constants.MENU_HANDLER, Constants.MENU_LVL3_FUNC);
                            //menuLvl3HashMap.put(Constants.TOOLBAR_ICON, Constants.TOOLBAR_ICON_MENUITEM);
                            menuLvl3HashMap.put(Constants.TOOLBAR_ICON,
                                    menuLvl3Map.get(Constants.TOOLBAR_ICON));

                            LinkedList<Object> menuLvl3Child = new LinkedList<Object>();
                            menuLvl3Child.add(menuLvl3HashMap);
                            menuLvl2HashMap.put(Constants.MENU_CHILDREN, menuLvl3Child);
                            menuLvl2HashMap.put(Constants.TOOL_BAR_CHILDREN, menuLvl3Child);
                            LinkedList<Object> menuLvl2Child = new LinkedList<Object>();
                            menuLvl2Child.add(menuLvl2HashMap);
                            menuLvl1HashMap.put(Constants.MENU_CHILDREN, menuLvl2Child);
                            menuLvl1HashMap.put(Constants.TOOL_BAR_CHILDREN, menuLvl2Child);

                            menuIndexMap.put(menuLvl1Map.get(Constants.MENU_ID).toString(), menuLvl1HashMap);
                        } else {
                            Map<String, Object> menuLvl1HashMap = (Map<String, Object>) menuIndexMap
                                    .get(menuLvl1Map.get(Constants.MENU_ID).toString());
                            LinkedList<Object> menuLvl2Child = (LinkedList<Object>) menuLvl1HashMap
                                    .get(Constants.MENU_CHILDREN);
                            boolean hasMenu = false;
                            for (int c = 0, d = menuLvl2Child.size(); c < d; c++) {
                                Map<String, Object> menuLvl2HashMap = (Map<String, Object>) menuLvl2Child
                                        .get(c);
                                if (StringUtils.trim(menuLvl2HashMap.get(Constants.MENU_ID).toString()).equals(
                                        StringUtils.trim(menuLvl2Map.get(Constants.MENU_ID).toString()))) {
                                    LinkedList<Object> menuLvl3Child = (LinkedList<Object>) menuLvl2HashMap
                                            .get(Constants.MENU_CHILDREN);
                                    Map<String, Object> menuLvl3HashMap = new LinkedHashMap<String, Object>();
                                    menuLvl3HashMap.put(Constants.MENU_ID, menuLvl3Map.get(Constants.MENU_ID));
                                    menuLvl3HashMap.put(Constants.MENU_TEXT,
                                            menuLvl3Map.get(Constants.MENU_TEXT));
                                    menuLvl3HashMap.put(Constants.MENU_PARENT_ID,
                                            menuLvl3Map.get(Constants.MENU_PARENT_ID));
                                    menuLvl3HashMap.put(Constants.MENU_LEAF, true);
                                    menuLvl3HashMap.put(Constants.MENU_URL,
                                            contextPath + menuLvl3Map.get(Constants.MENU_URL));
                                    menuLvl3HashMap.put(Constants.MENU_CLS,
                                            menuLvl3Map.get(Constants.MENU_CLS));
                                    menuLvl3HashMap.put(Constants.MENU_HANDLER, Constants.MENU_LVL3_FUNC);
                                    //menuLvl3HashMap.put(Constants.TOOLBAR_ICON, Constants.TOOLBAR_ICON_MENUITEM);
                                    menuLvl3HashMap.put(Constants.TOOLBAR_ICON,
                                            menuLvl3Map.get(Constants.TOOLBAR_ICON));

                                    menuLvl3Child.add(menuLvl3HashMap);
                                    menuLvl2HashMap.put(Constants.MENU_CHILDREN, menuLvl3Child);
                                    menuLvl2HashMap.put(Constants.TOOL_BAR_CHILDREN, menuLvl3Child);
                                    menuLvl2Child.set(c, menuLvl2HashMap);
                                    hasMenu = true;
                                    break;
                                }
                            }
                            if (!hasMenu) {
                                Map<String, Object> menuLvl2HashMap = new HashMap<String, Object>();
                                menuLvl2HashMap.put(Constants.MENU_ID, menuLvl2Map.get(Constants.MENU_ID));
                                menuLvl2HashMap.put(Constants.MENU_TEXT, menuLvl2Map.get(Constants.MENU_TEXT));
                                menuLvl2HashMap.put(Constants.MENU_PARENT_ID,
                                        menuLvl2Map.get(Constants.MENU_PARENT_ID));
                                menuLvl2HashMap.put(Constants.MENU_CLS, menuLvl2Map.get(Constants.MENU_CLS));
                                //                           menuLvl2HashMap.put(Constants.TOOLBAR_ICON, Constants.TOOLBAR_ICON_MENUITEM);                           

                                //
                                menuLvl2HashMap.put(Constants.TOOLBAR_ICON,
                                        menuLvl2Map.get(Constants.TOOLBAR_ICON));

                                LinkedList<Object> menuLvl3Child = new LinkedList<Object>();
                                Map<String, Object> menuLvl3HashMap = new LinkedHashMap<String, Object>();
                                menuLvl3HashMap.put(Constants.MENU_ID, menuLvl3Map.get(Constants.MENU_ID));
                                menuLvl3HashMap.put(Constants.MENU_TEXT, menuLvl3Map.get(Constants.MENU_TEXT));
                                menuLvl3HashMap.put(Constants.MENU_PARENT_ID,
                                        menuLvl3Map.get(Constants.MENU_PARENT_ID));
                                menuLvl3HashMap.put(Constants.MENU_LEAF, true);
                                menuLvl3HashMap.put(Constants.MENU_URL,
                                        contextPath + menuLvl3Map.get(Constants.MENU_URL));
                                menuLvl3HashMap.put(Constants.MENU_CLS, menuLvl3Map.get(Constants.MENU_CLS));
                                menuLvl3HashMap.put(Constants.MENU_HANDLER, Constants.MENU_LVL3_FUNC);
                                //menuLvl3HashMap.put(Constants.TOOLBAR_ICON, Constants.TOOLBAR_ICON_MENUITEM);
                                menuLvl3HashMap.put(Constants.TOOLBAR_ICON,
                                        menuLvl3Map.get(Constants.TOOLBAR_ICON));

                                menuLvl3Child.add(menuLvl3HashMap);
                                menuLvl2HashMap.put(Constants.MENU_CHILDREN, menuLvl3Child);
                                menuLvl2HashMap.put(Constants.TOOL_BAR_CHILDREN, menuLvl3Child);
                                menuLvl2Child.add(menuLvl2HashMap);
                            }
                            menuLvl1HashMap.put(Constants.MENU_CHILDREN, menuLvl2Child);
                            menuLvl1HashMap.put(Constants.TOOL_BAR_CHILDREN, menuLvl2Child);
                            menuIndexMap.put(menuLvl1Map.get(Constants.MENU_ID).toString(), menuLvl1HashMap);
                        }
                    }
                }
            }
        }
    }
    return menuIndexMap;
}

From source file:mondrian.rolap.RolapSchemaLoader.java

private MondrianDef.Dimension useSharedDimension(RolapCube cube, MondrianDef.Dimension xmlCubeDimension,
        RolapSchema schema, MondrianDef.Schema xmlSchema) {
    MondrianDef.Dimension xmlDimension;
    if (xmlCubeDimension.key != null) {
        getHandler().warning("Attribute '" + "key" + "' must not be specified in dimension that references "
                + "other dimension", xmlCubeDimension, "source");
    }/*  www  . j ava  2  s . c o m*/

    MondrianDef.Dimension sharedDimension = xmlSchema.getDimensions().get(xmlCubeDimension.source);
    if (sharedDimension == null) {
        getHandler().error("Unknown shared dimension '" + xmlCubeDimension.source
                + "' in definition of dimension '" + xmlCubeDimension.name + "'", xmlCubeDimension, "source");
        return null;
    }
    // this section of code handles the case where the schema uses the
    // same shared dimension multiple times.  The SQL generated uses
    // the phys schema objects so we need to create copies of those
    // objects with a different alias
    MondrianDef.Dimension clonedDim = null;
    if (cubeToDimMap.containsKey(cube) && cubeToDimMap.getCollection(cube).contains(sharedDimension)) {
        try {
            LinkedHashMap<String, RolapSchema.PhysRelation> tbls = schema.getPhysicalSchema().tablesByName;
            RolapSchema.PhysRelation physRelation = tbls.get(sharedDimension.table);
            if (physRelation != null) {
                String newAlias = newTableAlias(physRelation, tbls);
                RolapSchema.PhysRelation clonedRelation = physRelation.cloneWithAlias(newAlias);
                tbls.put(newAlias, clonedRelation);
                clonedDim = new MondrianDef.Dimension(sharedDimension._def);
                clonedDim.table = newAlias;
            }
        } catch (XOMException e) {
            throw new MondrianException(e);
        }
    }
    cubeToDimMap.put(cube, sharedDimension);
    if (clonedDim != null) {
        xmlDimension = clonedDim;
    } else {
        xmlDimension = sharedDimension;
    }
    return xmlDimension;
}

From source file:com.ibm.replication.iidr.warehouse.CollectCDCStats.java

/**
 * Log the subscription metrics//from w w  w .j a  va  2  s . co  m
 */
private void logSubscriptionMetrics(String subscriptionName, Timestamp collectTimestamp)
        throws EmbeddedScriptException, SQLException {

    ArrayList<String> metricIDList = new ArrayList<String>();
    LinkedHashMap<String, Integer> metricDescriptionMap = new LinkedHashMap<String, Integer>();

    // If the metrics for the subscriptions have not been retrieved yet, get
    // metric IDs
    if (!subscriptionMetrics.containsKey(subscriptionName)) {
        logger.debug("Obtaining available metrics of subscription " + subscriptionName);
        // Which performance metrics are available
        script.execute("list subscription performance metrics name " + subscriptionName);
        ResultStringTable availableMetrics = (ResultStringTable) script.getResult();
        String currentGroup = "";
        for (int r = 0; r < availableMetrics.getRowCount(); r++) {
            if (availableMetrics.getValueAt(r, 1).isEmpty()) {
                currentGroup = availableMetrics.getValueAt(r, 0);
            } else {
                String metricID = availableMetrics.getValueAt(r, 1);
                // Only include metric if in include list and not in exclude
                // list
                if ((settings.includeMetricsList.isEmpty() || settings.includeMetricsList.contains(metricID))
                        && !settings.excludeMetricsList.contains(metricID)) {
                    metricIDList.add(availableMetrics.getValueAt(r, 1));
                    metricDescriptionMap.put(currentGroup + " - " + availableMetrics.getValueAt(r, 0).trim(),
                            Integer.parseInt(availableMetrics.getValueAt(r, 1)));
                }
            }
        }
        logger.debug("Available metrics reported by engine: " + metricIDList);
        // Now check if the metric IDs are actually available
        boolean metricsChecked = false;
        while (!metricsChecked) {
            try {
                logger.debug("Checking adjusted list of metrics: " + metricIDList);
                String metricIDs = StringUtils.join(metricIDList, ",");
                script.execute("monitor subscription performance name " + subscriptionName + " metricIDs \""
                        + metricIDs + "\"");
                // If the program gets here, the metrics were valid
                metricsChecked = true;
            } catch (EmbeddedScriptException e) {
                if (script.getResultCode() == -2004) {
                    logger.debug("Invalid metrics found in the list, error message: "
                            + script.getResultCodeAndMessage());
                    metricIDList = removeInvalidMetrics(script.getResultMessage(), metricIDList);
                    metricsChecked = false;
                } else
                    throw new EmbeddedScriptException(script.getResultCode(), script.getResultMessage());
            }
        }

        logger.debug("Metric IDs for subscription " + subscriptionName + ": " + metricIDList);
        logger.debug("Metrics map for subscription " + subscriptionName + ": " + metricDescriptionMap);
        subscriptionMetrics.put(subscriptionName, metricIDList);
        subscriptionMetricsMap.put(subscriptionName, metricDescriptionMap);
    }

    String metricIDs = StringUtils.join(subscriptionMetrics.get(subscriptionName), ",");
    metricDescriptionMap = subscriptionMetricsMap.get(subscriptionName);

    // Now get the metrics
    script.execute(
            "monitor subscription performance name " + subscriptionName + " metricIDs \"" + metricIDs + "\"");
    ResultStringTable metrics = (ResultStringTable) script.getResult();
    logger.debug("Number of metrics retrieved: " + metrics.getRowCount());

    String metricSourceTarget = "";
    for (int r = 0; r < metrics.getRowCount(); r++) {
        String metric = metrics.getValueAt(r, 0).trim();
        if (metric.equals("Source") || metric.equals("Target")) {
            metricSourceTarget = metric.substring(0, 1);
        } else {
            Integer metricID = metricDescriptionMap.get(metric);
            String metricValue = metrics.getValueAt(r, 1);
            logger.debug(
                    r + " : " + metricSourceTarget + " - " + metricID + " - " + metric + " - " + metricValue);
            Number metricNumber;
            try {
                metricNumber = localNumberFormat.parse(metricValue);
            } catch (ParseException e) {
                logger.error("Error while parsing value for metric ID " + metricID + ", value is " + metricValue
                        + ". Error: " + e.getMessage());
                metricNumber = 0;
            }
            if (settings.logMetricsToDB)
                logDatabase.logMetrics(parms.datastore, subscriptionName, collectTimestamp, metricSourceTarget,
                        metricID, (long) metricNumber);
            if (settings.logMetricsToCsv)
                logCsv.logMetrics(parms.datastore, subscriptionName, collectTimestamp, metricSourceTarget,
                        metricID, (long) metricNumber);
        }
    }
}

From source file:jp.or.openid.eiwg.scim.operation.Operation.java

/**
 * //from w w w .  j  av  a  2 s .  c o m
 *
 * @param context
 * @param request
 * @param attributes
 * @param requestJson
 */
public LinkedHashMap<String, Object> updateUserInfo(ServletContext context, HttpServletRequest request,
        String targetId, String attributes, String requestJson) {
    LinkedHashMap<String, Object> result = null;

    Set<String> returnAttributeNameSet = new HashSet<>();

    // ?
    setError(0, null, null);

    // ??
    if (attributes != null && !attributes.isEmpty()) {
        // 
        String[] tempList = attributes.split(",");
        for (int i = 0; i < tempList.length; i++) {
            String attributeName = tempList[i].trim();
            // ???????
            LinkedHashMap<String, Object> attributeSchema = SCIMUtil.getUserAttributeInfo(context,
                    attributeName, true);
            if (attributeSchema != null && !attributeSchema.isEmpty()) {
                returnAttributeNameSet.add(attributeName);
            } else {
                // ???????
                String message = String.format(MessageConstants.ERROR_INVALID_ATTRIBUTES, attributeName);
                setError(HttpServletResponse.SC_BAD_REQUEST, null, message);
                return result;
            }
        }
    }

    // id?
    LinkedHashMap<String, Object> targetInfo = null;
    @SuppressWarnings("unchecked")
    ArrayList<LinkedHashMap<String, Object>> users = (ArrayList<LinkedHashMap<String, Object>>) context
            .getAttribute("Users");
    Iterator<LinkedHashMap<String, Object>> usersIt = null;
    if (users != null && !users.isEmpty()) {
        usersIt = users.iterator();
        while (usersIt.hasNext()) {
            LinkedHashMap<String, Object> userInfo = usersIt.next();
            Object id = SCIMUtil.getAttribute(userInfo, "id");
            if (id != null && id instanceof String) {
                if (targetId.equals(id.toString())) {
                    targetInfo = userInfo;
                    break;
                }
            }
        }
    }

    if (targetInfo == null) {
        setError(HttpServletResponse.SC_NOT_FOUND, null, MessageConstants.ERROR_NOT_FOUND);
        return result;
    }

    // ?
    if (requestJson == null || requestJson.isEmpty()) {
        // 
        setError(HttpServletResponse.SC_BAD_REQUEST, null, MessageConstants.ERROR_INVALID_REQUEST);
        return result;
    }

    // (JSON)?
    ObjectMapper mapper = new ObjectMapper();
    LinkedHashMap<String, Object> requestObject = null;
    try {
        requestObject = mapper.readValue(requestJson, new TypeReference<LinkedHashMap<String, Object>>() {
        });
    } catch (JsonParseException e) {
        String datailMessage = e.getMessage();
        datailMessage = datailMessage.substring(0, datailMessage.indexOf('\n'));
        setError(HttpServletResponse.SC_BAD_REQUEST, null,
                MessageConstants.ERROR_INVALID_REQUEST + "(" + datailMessage + ")");
        return result;
    } catch (JsonMappingException e) {
        String datailMessage = e.getMessage();
        datailMessage = datailMessage.substring(0, datailMessage.indexOf('\n'));
        setError(HttpServletResponse.SC_BAD_REQUEST, null,
                MessageConstants.ERROR_INVALID_REQUEST + "(" + datailMessage + ")");
        return result;
    } catch (IOException e) {
        setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, MessageConstants.ERROR_UNKNOWN);
        return result;
    }

    // ?
    if (requestObject != null && !requestObject.isEmpty()) {
        Iterator<String> attributeIt = requestObject.keySet().iterator();
        while (attributeIt.hasNext()) {
            // ???
            String attributeName = attributeIt.next();
            // ?
            LinkedHashMap<String, Object> attributeSchema = SCIMUtil.getUserAttributeInfo(context,
                    attributeName, false);
            if (attributeSchema != null) {
                // ????
                Object mutability = attributeSchema.get("mutability");
                if (mutability != null && mutability.toString().equalsIgnoreCase("readOnly")) {
                    // readOnly 
                    String message = String.format(MessageConstants.ERROR_READONLY_ATTRIBUTE, attributeName);
                    setError(HttpServletResponse.SC_BAD_REQUEST, null, message);
                    return result;
                }

                // ??
                // ()
            } else {
                if (!attributeName.equalsIgnoreCase("schemas") && !attributeName.equalsIgnoreCase("id")
                        && !attributeName.equalsIgnoreCase("meta")) {
                    // ????
                    String message = String.format(MessageConstants.ERROR_UNKNOWN_ATTRIBUTE, attributeName);
                    setError(HttpServletResponse.SC_BAD_REQUEST, null, message);
                    return result;
                }
            }
        }
    } else {
        // 
        setError(HttpServletResponse.SC_BAD_REQUEST, null, MessageConstants.ERROR_INVALID_REQUEST);
        return result;
    }

    // ?
    // ()

    LinkedHashMap<String, Object> updateUserInfo = new LinkedHashMap<String, Object>();

    // 
    updateUserInfo.put("id", targetId);

    Iterator<String> attributeIt = requestObject.keySet().iterator();
    while (attributeIt.hasNext()) {
        // ???
        String attributeName = attributeIt.next();
        // ?
        Object attributeValue = requestObject.get(attributeName);

        updateUserInfo.put(attributeName, attributeValue);
    }

    // meta
    Object metaObject = targetInfo.get("meta");
    @SuppressWarnings("unchecked")
    LinkedHashMap<String, Object> metaValues = (LinkedHashMap<String, Object>) metaObject;
    // meta.lastModified 
    SimpleDateFormat xsdDateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
    xsdDateTime.setTimeZone(TimeZone.getTimeZone("UTC"));
    metaValues.put("lastModified", xsdDateTime.format(new Date()));

    updateUserInfo.put("meta", metaValues);

    // (??)
    usersIt.remove();
    users.add(updateUserInfo);
    context.setAttribute("Users", users);

    // ??
    result = new LinkedHashMap<String, Object>();
    attributeIt = updateUserInfo.keySet().iterator();
    while (attributeIt.hasNext()) {
        // ???
        String attributeName = attributeIt.next();

        // ?
        LinkedHashMap<String, Object> attributeSchema = SCIMUtil.getUserAttributeInfo(context, attributeName,
                true);
        Object returned = attributeSchema.get("returned");

        if (returned != null && returned.toString().equalsIgnoreCase("never")) {
            continue;
        }

        // ?
        Object attributeValue = updateUserInfo.get(attributeName);

        result.put(attributeName, attributeValue);
    }

    return result;
}