Example usage for java.util EnumMap EnumMap

List of usage examples for java.util EnumMap EnumMap

Introduction

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

Prototype

public EnumMap(Map<K, ? extends V> m) 

Source Link

Document

Creates an enum map initialized from the specified map.

Usage

From source file:org.talend.mdm.engines.client.ui.wizards.DeployOnMDMExportWizardPage.java

private Map<ExportChoice, Object> getExportChoiceMap(boolean needContextScript) {
    Map<ExportChoice, Object> exportChoiceMap = new EnumMap<ExportChoice, Object>(ExportChoice.class);

    // zip//from  w  w w  .ja  v a 2 s  .  c o  m
    exportChoiceMap.put(ExportChoice.needLauncher, true);
    exportChoiceMap.put(ExportChoice.needSystemRoutine, true);
    exportChoiceMap.put(ExportChoice.needUserRoutine, true);
    exportChoiceMap.put(ExportChoice.needTalendLibraries, true);
    exportChoiceMap.put(ExportChoice.needJobItem, true);
    // exportChoiceMap.put(ExportChoice.needSourceCode, true);
    exportChoiceMap.put(ExportChoice.needDependencies, true);
    exportChoiceMap.put(ExportChoice.needJobScript, true);
    exportChoiceMap.put(ExportChoice.needContext, true);
    exportChoiceMap.put(ExportChoice.applyToChildren, true);
    exportChoiceMap.put(ExportChoice.needDependencies, true);

    exportChoiceMap.put(ExportChoice.needContext, needContextScript);

    return exportChoiceMap;
}

From source file:org.quantumbadger.redreader.reddit.prepared.RedditPreparedPost.java

public VerticalToolbar generateToolbar(final Activity activity, boolean isComments,
        final SideToolbarOverlay overlay) {

    final VerticalToolbar toolbar = new VerticalToolbar(activity);
    final EnumSet<Action> itemsPref = PrefsUtility.pref_menus_post_toolbar_items(activity,
            PreferenceManager.getDefaultSharedPreferences(activity));

    final Action[] possibleItems = { Action.ACTION_MENU,
            isComments ? Action.LINK_SWITCH : Action.COMMENTS_SWITCH, Action.UPVOTE, Action.DOWNVOTE,
            Action.SAVE, Action.HIDE, Action.DELETE, Action.REPLY, Action.EXTERNAL, Action.SAVE_IMAGE,
            Action.SHARE, Action.COPY, Action.USER_PROFILE, Action.PROPERTIES };

    // TODO make static
    final EnumMap<Action, Integer> iconsDark = new EnumMap<Action, Integer>(Action.class);
    iconsDark.put(Action.ACTION_MENU, R.drawable.ic_action_overflow);
    iconsDark.put(Action.COMMENTS_SWITCH, R.drawable.ic_action_comments_dark);
    iconsDark.put(Action.LINK_SWITCH,
            mIsProbablyAnImage ? R.drawable.ic_action_image_dark : R.drawable.ic_action_page_dark);
    iconsDark.put(Action.UPVOTE, R.drawable.action_upvote_dark);
    iconsDark.put(Action.DOWNVOTE, R.drawable.action_downvote_dark);
    iconsDark.put(Action.SAVE, R.drawable.ic_action_star_filled_dark);
    iconsDark.put(Action.HIDE, R.drawable.ic_action_cross_dark);
    iconsDark.put(Action.REPLY, R.drawable.ic_action_reply_dark);
    iconsDark.put(Action.EXTERNAL, R.drawable.ic_action_globe_dark);
    iconsDark.put(Action.SAVE_IMAGE, R.drawable.ic_action_save_dark);
    iconsDark.put(Action.SHARE, R.drawable.ic_action_share_dark);
    iconsDark.put(Action.COPY, R.drawable.ic_action_copy_dark);
    iconsDark.put(Action.USER_PROFILE, R.drawable.ic_action_person_dark);
    iconsDark.put(Action.PROPERTIES, R.drawable.ic_action_info_dark);

    final EnumMap<Action, Integer> iconsLight = new EnumMap<Action, Integer>(Action.class);
    iconsLight.put(Action.ACTION_MENU, R.drawable.ic_action_overflow);
    iconsLight.put(Action.COMMENTS_SWITCH, R.drawable.ic_action_comments_light);
    iconsLight.put(Action.LINK_SWITCH,
            mIsProbablyAnImage ? R.drawable.ic_action_image_light : R.drawable.ic_action_page_light);
    iconsLight.put(Action.UPVOTE, R.drawable.action_upvote_light);
    iconsLight.put(Action.DOWNVOTE, R.drawable.action_downvote_light);
    iconsLight.put(Action.SAVE, R.drawable.ic_action_star_filled_light);
    iconsLight.put(Action.HIDE, R.drawable.ic_action_cross_light);
    iconsLight.put(Action.REPLY, R.drawable.ic_action_reply_light);
    iconsLight.put(Action.EXTERNAL, R.drawable.ic_action_globe_light);
    iconsLight.put(Action.SAVE_IMAGE, R.drawable.ic_action_save_light);
    iconsLight.put(Action.SHARE, R.drawable.ic_action_share_light);
    iconsLight.put(Action.COPY, R.drawable.ic_action_copy_light);
    iconsLight.put(Action.USER_PROFILE, R.drawable.ic_action_person_light);
    iconsLight.put(Action.PROPERTIES, R.drawable.ic_action_info_light);

    for (final Action action : possibleItems) {

        if (action == Action.SAVE_IMAGE && !mIsProbablyAnImage)
            continue;

        if (itemsPref.contains(action)) {

            final FlatImageButton ib = new FlatImageButton(activity);

            final int buttonPadding = General.dpToPixels(activity, 10);
            ib.setPadding(buttonPadding, buttonPadding, buttonPadding, buttonPadding);

            if (action == Action.UPVOTE && isUpvoted() || action == Action.DOWNVOTE && isDownvoted()
                    || action == Action.SAVE && isSaved() || action == Action.HIDE && isHidden()) {

                ib.setBackgroundColor(Color.WHITE);
                ib.setImageResource(iconsLight.get(action));

            } else {
                ib.setImageResource(iconsDark.get(action));
                // TODO highlight on click
            }/*from  ww w. java 2  s .  c  o m*/

            ib.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    final Action actionToTake;

                    switch (action) {
                    case UPVOTE:
                        actionToTake = isUpvoted() ? Action.UNVOTE : Action.UPVOTE;
                        break;

                    case DOWNVOTE:
                        actionToTake = isDownvoted() ? Action.UNVOTE : Action.DOWNVOTE;
                        break;

                    case SAVE:
                        actionToTake = isSaved() ? Action.UNSAVE : Action.SAVE;
                        break;

                    case HIDE:
                        actionToTake = isHidden() ? Action.UNHIDE : Action.HIDE;
                        break;

                    default:
                        actionToTake = action;
                        break;
                    }

                    onActionMenuItemSelected(RedditPreparedPost.this, activity, actionToTake);
                    overlay.hide();
                }
            });

            toolbar.addItem(ib);
        }
    }

    return toolbar;
}

From source file:com.wanikani.androidnotifier.ItemsFragment.java

/**
 * Creation of the fragment. We build up all the singletons, leaving the
 * bundle alone, because we set the retain instance flag to <code>true</code>.
 *    @param bundle the saved instance state
 *//*  www  . j  a v  a2s . co  m*/
@Override
public void onCreate(Bundle bundle) {
    Resources res;

    super.onCreate(bundle);

    setRetainInstance(true);

    fmap = new EnumMap<FilterType, Filter>(FilterType.class);
    fmap.put(FilterType.NONE, new NoFilter(this));
    fmap.put(FilterType.LEVEL, new LevelFilter(this));
    fmap.put(FilterType.CRITICAL, new CriticalFilter(this));
    fmap.put(FilterType.TOXIC, new ToxicFilter(this));
    fmap.put(FilterType.UNLOCKS, new UnlockFilter(this));

    filterType = FilterType.LEVEL;

    lcl = new LevelClickListener();

    mpl = new MenuPopupListener();
    rgl = new RadioGroupListener();

    res = getResources();
    srsht = new EnumMap<SRSLevel, Drawable>(SRSLevel.class);
    srsht.put(SRSLevel.APPRENTICE, res.getDrawable(R.drawable.apprentice));
    srsht.put(SRSLevel.GURU, res.getDrawable(R.drawable.guru));
    srsht.put(SRSLevel.MASTER, res.getDrawable(R.drawable.master));
    srsht.put(SRSLevel.ENLIGHTEN, res.getDrawable(R.drawable.enlighten));
    srsht.put(SRSLevel.BURNED, res.getDrawable(R.drawable.burned));

    normalColor = res.getColor(R.color.normal);
    importantColor = res.getColor(R.color.important);
    selectedColor = res.getColor(R.color.selected);
    unselectedColor = res.getColor(R.color.unselected);

    lad = new LevelListAdapter();
    iad = new ItemListAdapter(Item.SortByType.INSTANCE, ItemInfo.AVAILABLE);

    iss = new ItemSearchDialog.State();
}

From source file:org.apache.ambari.server.controller.internal.ServiceResourceProvider.java

private void updateServiceComponents(RequestStageContainer requestStages,
        Map<State, List<ServiceComponent>> changedComps,
        Map<String, Map<State, List<ServiceComponentHost>>> changedScHosts,
        Collection<ServiceComponentHost> ignoredScHosts, Resource.Type reqOpLvl, Service service,
        State newState) throws AmbariException {

    Cluster cluster = service.getCluster();
    AmbariManagementController controller = getManagementController();
    AmbariMetaInfo ambariMetaInfo = controller.getAmbariMetaInfo();

    for (ServiceComponent sc : service.getServiceComponents().values()) {
        State oldScState = sc.getDesiredState();
        if (newState != oldScState) {
            if (sc.isClientComponent() && !newState.isValidClientComponentState()) {
                continue;
            }/*from   w  w  w.  j a  v a  2 s  .co  m*/
            if (!State.isValidDesiredStateTransition(oldScState, newState)) {
                throw new AmbariException("Invalid transition for" + " servicecomponent" + ", clusterName="
                        + cluster.getClusterName() + ", clusterId=" + cluster.getClusterId() + ", serviceName="
                        + sc.getServiceName() + ", componentName=" + sc.getName() + ", currentDesiredState="
                        + oldScState + ", newDesiredState=" + newState);
            }
            if (!changedComps.containsKey(newState)) {
                changedComps.put(newState, new ArrayList<ServiceComponent>());
            }
            changedComps.get(newState).add(sc);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Handling update to ServiceComponent" + ", clusterName=" + cluster.getClusterName()
                    + ", serviceName=" + service.getName() + ", componentName=" + sc.getName()
                    + ", currentDesiredState=" + oldScState + ", newDesiredState=" + newState);
        }

        for (ServiceComponentHost sch : sc.getServiceComponentHosts().values()) {
            State oldSchState = sch.getState();
            if (oldSchState == State.DISABLED || oldSchState == State.UNKNOWN) {
                //Ignore host components updates in this state
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Ignoring ServiceComponentHost" + ", clusterName=" + cluster.getClusterName()
                            + ", serviceName=" + service.getName() + ", componentName=" + sc.getName()
                            + ", hostname=" + sch.getHostName() + ", currentState=" + oldSchState
                            + ", newDesiredState=" + newState);
                }
                continue;
            }
            //
            if (newState == oldSchState) {
                ignoredScHosts.add(sch);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Ignoring ServiceComponentHost" + ", clusterName=" + cluster.getClusterName()
                            + ", serviceName=" + service.getName() + ", componentName=" + sc.getName()
                            + ", hostname=" + sch.getHostName() + ", currentState=" + oldSchState
                            + ", newDesiredState=" + newState);
                }
                continue;
            }

            if (!maintenanceStateHelper.isOperationAllowed(reqOpLvl, sch)) {
                ignoredScHosts.add(sch);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Ignoring ServiceComponentHost" + ", clusterName=" + cluster.getClusterName()
                            + ", serviceName=" + service.getName() + ", componentName=" + sc.getName()
                            + ", hostname=" + sch.getHostName());
                }
                continue;
            }

            if (sc.isClientComponent() && !newState.isValidClientComponentState()) {
                continue;
            }
            /**
             * This is hack for now wherein we don't fail if the
             * sch is in INSTALL_FAILED
             */
            if (!isValidStateTransition(requestStages, oldSchState, newState, sch)) {
                String error = "Invalid transition for" + " servicecomponenthost" + ", clusterName="
                        + cluster.getClusterName() + ", clusterId=" + cluster.getClusterId() + ", serviceName="
                        + sch.getServiceName() + ", componentName=" + sch.getServiceComponentName()
                        + ", hostname=" + sch.getHostName() + ", currentState=" + oldSchState
                        + ", newDesiredState=" + newState;
                StackId sid = cluster.getDesiredStackVersion();

                if (ambariMetaInfo.getComponent(sid.getStackName(), sid.getStackVersion(), sc.getServiceName(),
                        sch.getServiceComponentName()).isMaster()) {
                    throw new AmbariException(error);
                } else {
                    LOG.warn("Ignoring: " + error);
                    continue;
                }
            }
            if (!changedScHosts.containsKey(sc.getName())) {
                changedScHosts.put(sc.getName(), new EnumMap<State, List<ServiceComponentHost>>(State.class));
            }
            if (!changedScHosts.get(sc.getName()).containsKey(newState)) {
                changedScHosts.get(sc.getName()).put(newState, new ArrayList<ServiceComponentHost>());
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("Handling update to ServiceComponentHost" + ", clusterName="
                        + cluster.getClusterName() + ", serviceName=" + service.getName() + ", componentName="
                        + sc.getName() + ", hostname=" + sch.getHostName() + ", currentState=" + oldSchState
                        + ", newDesiredState=" + newState);
            }
            changedScHosts.get(sc.getName()).get(newState).add(sch);
        }
    }
}

From source file:canreg.client.dataentry.Import.java

public static boolean importFiles(Task<Object, Void> task, Document doc,
        List<canreg.client.dataentry.Relation> map, File[] files, CanRegServerInterface server,
        ImportOptions io) throws SQLException, RemoteException, SecurityException, RecordLockedException {
    int numberOfLinesRead = 0;
    Writer reportWriter = new BufferedWriter(new OutputStreamWriter(System.out));
    if (io.getReportFileName() != null && io.getReportFileName().trim().length() > 0) {
        try {/*from   w  ww.j a v a2  s . c  om*/
            reportWriter = new BufferedWriter(new FileWriter(io.getReportFileName()));
        } catch (IOException ex) {
            Logger.getLogger(Import.class.getName()).log(Level.WARNING, null, ex);
        }
    }
    boolean success = false;
    Set<String> noNeedToLookAtPatientVariables = new TreeSet<String>();
    noNeedToLookAtPatientVariables
            .add(canreg.common.Tools.toLowerCaseStandardized(io.getPatientIDVariableName()));
    noNeedToLookAtPatientVariables
            .add(canreg.common.Tools.toLowerCaseStandardized(io.getPatientRecordIDVariableName()));

    String[] lineElements;
    ResultCode worstResultCodeFound;
    //         CSVReader reader = null;
    CSVParser parser = null;
    CSVFormat format = CSVFormat.DEFAULT.withFirstRecordAsHeader().withDelimiter(io.getSeparators()[0]);

    int linesToRead = io.getMaxLines();

    try {
        // first we get the patients
        if (task != null) {
            task.firePropertyChange(PROGRESS, 0, 0);
            task.firePropertyChange(PATIENTS, 0, 0);
        }
        if (files[0] != null) {
            reportWriter
                    .write("Starting to import patients from " + files[0].getAbsolutePath() + Globals.newline);
            FileInputStream patientFIS = new FileInputStream(files[0]);
            InputStreamReader patientISR = new InputStreamReader(patientFIS, io.getFileCharsets()[0]);

            Logger.getLogger(Import.class.getName()).log(Level.CONFIG, "Name of the character encoding {0}",
                    patientISR.getEncoding());

            int numberOfRecordsInFile = canreg.common.Tools.numberOfLinesInFile(files[0].getAbsolutePath());

            numberOfLinesRead = 0;

            if (linesToRead > 0) {
                linesToRead = Math.min(numberOfRecordsInFile, linesToRead);
            } else {
                linesToRead = numberOfRecordsInFile;
            }
            parser = CSVParser.parse(files[0], io.getFileCharsets()[0], format);

            for (CSVRecord csvRecord : parser) {
                // We allow for null tasks...
                boolean savePatient = true;
                boolean deletePatient = false;
                int oldPatientDatabaseRecordID = -1;

                if (task != null) {
                    task.firePropertyChange(PROGRESS, ((numberOfLinesRead - 1) * 100 / linesToRead) / 3,
                            ((numberOfLinesRead) * 100 / linesToRead) / 3);
                    task.firePropertyChange(PATIENTS, ((numberOfLinesRead - 1) * 100 / linesToRead),
                            ((numberOfLinesRead) * 100 / linesToRead));
                }

                // Build patient part
                Patient patient = new Patient();
                for (int i = 0; i < map.size(); i++) {
                    Relation rel = map.get(i);
                    if (rel.getDatabaseTableVariableID() >= 0
                            && rel.getDatabaseTableName().equalsIgnoreCase("patient")) {
                        if (rel.getVariableType().equalsIgnoreCase("Number")) {
                            if (csvRecord.get(rel.getFileColumnNumber()).length() > 0) {
                                try {
                                    patient.setVariable(rel.getDatabaseVariableName(),
                                            Integer.parseInt(csvRecord.get(rel.getFileColumnNumber())));
                                } catch (NumberFormatException ex) {
                                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE,
                                            "Number format error in line: " + (numberOfLinesRead + 1 + 1)
                                                    + ". ",
                                            ex);
                                    success = false;
                                }
                            }
                        } else {
                            patient.setVariable(rel.getDatabaseVariableName(),
                                    csvRecord.get(rel.getFileColumnNumber()));
                        }
                    }
                    if (task != null) {
                        task.firePropertyChange(RECORD, i - 1 / map.size() * 50, i / map.size() * 50);
                    }
                }
                // debugOut(patient.toString());

                // debugOut(tumour.toString());
                // add patient to the database
                Object patientID = patient.getVariable(io.getPatientRecordIDVariableName());
                Patient oldPatientRecord = null;
                try {
                    oldPatientRecord = CanRegClientApp.getApplication().getPatientRecord((String) patientID,
                            false);
                } catch (DistributedTableDescriptionException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (RecordLockedException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (RemoteException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SecurityException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnknownTableException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                }

                if (oldPatientRecord != null) {
                    // deal with discrepancies                        
                    switch (io.getDiscrepancies()) {
                    case ImportOptions.REJECT:
                        savePatient = false;
                        break;
                    case ImportOptions.UPDATE:
                        String updateReport = updateRecord(oldPatientRecord, patient);
                        if (updateReport.length() > 0) {
                            reportWriter.write(patient.getVariable(io.getTumourIDVariablename())
                                    + Globals.newline + updateReport);
                        }
                        oldPatientDatabaseRecordID = (Integer) oldPatientRecord
                                .getVariable(Globals.PATIENT_TABLE_RECORD_ID_VARIABLE_NAME);
                        patient = oldPatientRecord;
                        savePatient = true;
                        break;
                    case ImportOptions.OVERWRITE:
                        // deleteTumour;
                        oldPatientDatabaseRecordID = (Integer) oldPatientRecord
                                .getVariable(Globals.PATIENT_TABLE_RECORD_ID_VARIABLE_NAME);
                        String overWriteReport = overwriteRecord(oldPatientRecord, patient);
                        if (overWriteReport.length() > 0) {
                            reportWriter.write(patient.getVariable(io.getTumourIDVariablename())
                                    + Globals.newline + overWriteReport);
                        }
                        patient = oldPatientRecord;
                        savePatient = true;
                        break;
                    }
                    // reportWriter.write(tumour.getVariable(io.getTumourIDVariablename()) + "Tumour already exists.\n");
                }

                if (task != null) {
                    task.firePropertyChange(RECORD, 50, 75);
                }

                if ((!io.isTestOnly())) {
                    if (deletePatient) {
                        server.deleteRecord(oldPatientDatabaseRecordID, Globals.PATIENT_TABLE_NAME);
                    }
                    if (savePatient) {
                        if (patient.getVariable(Globals.PATIENT_TABLE_RECORD_ID_VARIABLE_NAME) != null) {
                            server.editPatient(patient);
                        } else {
                            server.savePatient(patient);
                        }
                    }
                }

                if (task != null) {
                    task.firePropertyChange(RECORD, 100, 75);
                }

                numberOfLinesRead++;

                if (Thread.interrupted()) {
                    //We've been interrupted: no more importing.
                    reportWriter.flush();
                    throw new InterruptedException();
                }
            }
            parser.close();
            reportWriter.write("Finished reading patients." + Globals.newline + Globals.newline);
            reportWriter.flush();
        }
        if (task != null) {
            task.firePropertyChange(PATIENTS, 100, 100);
            task.firePropertyChange("progress", 33, 34);
        }

        // then we get the tumours            
        if (task != null) {
            task.firePropertyChange(TUMOURS, 0, 0);
        }

        if (files[1] != null) {
            reportWriter
                    .write("Starting to import tumours from " + files[1].getAbsolutePath() + Globals.newline);

            FileInputStream tumourFIS = new FileInputStream(files[1]);
            InputStreamReader tumourISR = new InputStreamReader(tumourFIS, io.getFileCharsets()[1]);

            Logger.getLogger(Import.class.getName()).log(Level.CONFIG, "Name of the character encoding {0}",
                    tumourISR.getEncoding());

            numberOfLinesRead = 0;

            int numberOfRecordsInFile = canreg.common.Tools.numberOfLinesInFile(files[1].getAbsolutePath());

            if (linesToRead > 0) {
                linesToRead = Math.min(numberOfRecordsInFile, linesToRead);
            } else {
                linesToRead = numberOfRecordsInFile;
            }

            format = CSVFormat.DEFAULT.withFirstRecordAsHeader().withDelimiter(io.getSeparators()[1]);

            parser = CSVParser.parse(files[1], io.getFileCharsets()[1], format);

            for (CSVRecord csvRecord : parser) {
                // We allow for null tasks...
                boolean saveTumour = true;
                boolean deleteTumour = false;

                if (task != null) {
                    task.firePropertyChange(PROGRESS, 33 + ((numberOfLinesRead - 1) * 100 / linesToRead) / 3,
                            33 + ((numberOfLinesRead) * 100 / linesToRead) / 3);
                    task.firePropertyChange(TUMOURS, ((numberOfLinesRead - 1) * 100 / linesToRead),
                            ((numberOfLinesRead) * 100 / linesToRead));
                }
                // Build tumour part
                Tumour tumour = new Tumour();
                for (int i = 0; i < map.size(); i++) {
                    Relation rel = map.get(i);
                    if (rel.getDatabaseTableVariableID() >= 0
                            && rel.getDatabaseTableName().equalsIgnoreCase("tumour")) {
                        if (rel.getVariableType().equalsIgnoreCase("Number")) {
                            if (csvRecord.get(rel.getFileColumnNumber()).length() > 0) {
                                try {
                                    tumour.setVariable(rel.getDatabaseVariableName(),
                                            Integer.parseInt(csvRecord.get(rel.getFileColumnNumber())));
                                } catch (NumberFormatException ex) {
                                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE,
                                            "Number format error in line: " + (numberOfLinesRead + 1 + 1)
                                                    + ". ",
                                            ex);
                                    success = false;
                                }
                            }
                        } else {
                            tumour.setVariable(rel.getDatabaseVariableName(),
                                    csvRecord.get(rel.getFileColumnNumber()));
                        }
                    }
                    if (task != null) {
                        task.firePropertyChange(RECORD, i - 1 / map.size() * 50, i / map.size() * 50);
                    }
                }

                // see if this tumour exists in the database already
                // TODO: Implement this using arrays and getTumourRexords instead
                Tumour tumour2 = null;
                try {
                    tumour2 = CanRegClientApp.getApplication().getTumourRecordBasedOnTumourID(
                            (String) tumour.getVariable(io.getTumourIDVariablename()), false);
                } catch (DistributedTableDescriptionException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (RecordLockedException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (RemoteException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SecurityException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnknownTableException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                }

                if (tumour2 != null) {
                    // deal with discrepancies
                    switch (io.getDiscrepancies()) {
                    case ImportOptions.REJECT:
                        saveTumour = false;
                        break;
                    case ImportOptions.UPDATE:
                        String updateReport = updateRecord(tumour2, tumour);
                        if (updateReport.length() > 0) {
                            reportWriter.write(tumour.getVariable(io.getTumourIDVariablename())
                                    + Globals.newline + updateReport);
                        }
                        tumour = tumour2;
                        saveTumour = true;
                        break;
                    case ImportOptions.OVERWRITE:
                        // deleteTumour;
                        deleteTumour = true;
                        saveTumour = true;
                        break;
                    }
                    // reportWriter.write(tumour.getVariable(io.getTumourIDVariablename()) + "Tumour already exists.\n");

                }

                Patient patient = null;
                try {
                    patient = CanRegClientApp.getApplication().getPatientRecord(
                            (String) tumour.getVariable(io.getPatientRecordIDTumourTableVariableName()), false);
                } catch (DistributedTableDescriptionException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (RecordLockedException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (RemoteException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SecurityException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnknownTableException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                }

                if (patient != null) {
                    if (io.isDoChecks() && saveTumour) {
                        // run the edits...
                        String message = "";
                        LinkedList<CheckResult> checkResults = canreg.client.CanRegClientApp.getApplication()
                                .performChecks(patient, tumour);

                        Map<Globals.StandardVariableNames, CheckResult.ResultCode> mapOfVariablesAndWorstResultCodes = new EnumMap<Globals.StandardVariableNames, CheckResult.ResultCode>(
                                Globals.StandardVariableNames.class);
                        worstResultCodeFound = CheckResult.ResultCode.OK;
                        for (CheckResult result : checkResults) {
                            if (result.getResultCode() != CheckResult.ResultCode.OK
                                    && result.getResultCode() != CheckResult.ResultCode.NotDone) {
                                if (!result.getResultCode().equals(CheckResult.ResultCode.Missing)) {
                                    message += result + "\t";
                                    worstResultCodeFound = CheckResult.decideWorstResultCode(
                                            result.getResultCode(), worstResultCodeFound);
                                    for (Globals.StandardVariableNames standardVariableName : result
                                            .getVariablesInvolved()) {
                                        CheckResult.ResultCode worstResultCodeFoundForThisVariable = mapOfVariablesAndWorstResultCodes
                                                .get(standardVariableName);
                                        if (worstResultCodeFoundForThisVariable == null) {
                                            mapOfVariablesAndWorstResultCodes.put(standardVariableName,
                                                    result.getResultCode());
                                        } else if (CheckResult.compareResultSets(result.getResultCode(),
                                                worstResultCodeFoundForThisVariable) > 0) {
                                            mapOfVariablesAndWorstResultCodes.put(standardVariableName,
                                                    result.getResultCode());
                                        }
                                    }
                                }
                            }
                            // Logger.getLogger(Import.class.getName()).log(Level.INFO, result.toString());
                        }
                        // always generate ICD10...
                        // ConversionResult[] conversionResult = canreg.client.CanRegClientApp.getApplication().performConversions(Converter.ConversionName.ICDO3toICD10, patient, tumour);
                        // tumour.setVariable(io.getICD10VariableName(), conversionResult[0].getValue());

                        if (worstResultCodeFound != CheckResult.ResultCode.Invalid
                                && worstResultCodeFound != CheckResult.ResultCode.Missing) {
                            // generate ICD10 codes
                            ConversionResult[] conversionResult = canreg.client.CanRegClientApp.getApplication()
                                    .performConversions(Converter.ConversionName.ICDO3toICD10, patient, tumour);
                            tumour.setVariable(io.getICD10VariableName(), conversionResult[0].getValue());
                            // generate ICCC codes
                            ConversionResult[] conversionResultICCC = canreg.client.CanRegClientApp
                                    .getApplication()
                                    .performConversions(Converter.ConversionName.ICDO3toICCC3, patient, tumour);
                            tumour.setVariable(io.getICCCVariableName(), conversionResultICCC[0].getValue());
                        } else {
                            tumour.setVariable(io.getTumourRecordStatus(), "0");
                        }

                        if (worstResultCodeFound == CheckResult.ResultCode.OK) {
                            // message += "Cross-check conclusion: Valid";
                        } else {
                            reportWriter.write(tumour.getVariable(io.getTumourIDVariablename()) + "\t" + message
                                    + Globals.newline);
                            // System.out.println(tumour.getVariable(io.getTumourIDVariablename()) + " " + message);
                        }
                        tumour.setVariable(io.getTumourCheckStatus(),
                                CheckResult.toDatabaseVariable(worstResultCodeFound));

                    } else {
                        // try to generate ICD10, if missing, anyway
                        String icd10 = (String) tumour.getVariable(io.getICD10VariableName());
                        if (icd10 == null || icd10.trim().length() == 0) {
                            ConversionResult[] conversionResult = canreg.client.CanRegClientApp.getApplication()
                                    .performConversions(Converter.ConversionName.ICDO3toICD10, patient, tumour);
                            tumour.setVariable(io.getICD10VariableName(), conversionResult[0].getValue());
                        }
                        // try to generate ICCC3, if missing, anyway
                        String iccc = (String) tumour.getVariable(io.getICCCVariableName());
                        if (iccc == null || iccc.trim().length() == 0) {
                            ConversionResult[] conversionResult = canreg.client.CanRegClientApp.getApplication()
                                    .performConversions(Converter.ConversionName.ICDO3toICCC3, patient, tumour);
                            tumour.setVariable(io.getICCCVariableName(), conversionResult[0].getValue());
                        }
                    }
                } else {
                    reportWriter.write(tumour.getVariable(io.getTumourIDVariablename()) + "\t"
                            + "No patient matches this Tumour." + Globals.newline);
                    tumour.setVariable(io.getTumourRecordStatus(), "0");
                    tumour.setVariable(io.getTumourCheckStatus(),
                            CheckResult.toDatabaseVariable(ResultCode.Missing));
                }
                if (task != null) {
                    task.firePropertyChange(RECORD, 50, 75);
                }
                if (!io.isTestOnly()) {
                    if (deleteTumour) {
                        server.deleteRecord(
                                (Integer) tumour2.getVariable(Globals.TUMOUR_TABLE_RECORD_ID_VARIABLE_NAME),
                                Globals.TUMOUR_TABLE_NAME);
                    }
                    if (saveTumour) {
                        // if tumour has no record ID we save it
                        if (tumour.getVariable(Globals.TUMOUR_TABLE_RECORD_ID_VARIABLE_NAME) == null) {
                            server.saveTumour(tumour);
                        } // if not we edit it
                        else {
                            server.editTumour(tumour);
                        }
                    }
                }
                if (task != null) {
                    task.firePropertyChange(RECORD, 75, 100);
                }
                //Read next line of data

                numberOfLinesRead++;

                if (Thread.interrupted()) {
                    //We've been interrupted: no more importing.
                    reportWriter.flush();
                    throw new InterruptedException();
                }
            }
            parser.close();
            reportWriter.write("Finished reading tumours." + Globals.newline + Globals.newline);
            reportWriter.flush();
        }
        if (task != null) {
            task.firePropertyChange(TUMOURS, 100, 100);
        }
        // then at last we get the sources
        if (task != null) {
            task.firePropertyChange(SOURCES, 0, 0);
            task.firePropertyChange(PROGRESS, 66, 66);
        }
        if (files[2] != null) {
            reportWriter
                    .write("Starting to import sources from " + files[2].getAbsolutePath() + Globals.newline);

            FileInputStream sourceFIS = new FileInputStream(files[2]);
            InputStreamReader sourceISR = new InputStreamReader(sourceFIS, io.getFileCharsets()[2]);

            Logger.getLogger(Import.class.getName()).log(Level.CONFIG, "Name of the character encoding {0}",
                    sourceISR.getEncoding());

            numberOfLinesRead = 0;

            int numberOfRecordsInFile = canreg.common.Tools.numberOfLinesInFile(files[2].getAbsolutePath());

            if (linesToRead > 0) {
                linesToRead = Math.min(numberOfRecordsInFile, linesToRead);
            } else {
                linesToRead = numberOfRecordsInFile;
            }

            format = CSVFormat.DEFAULT.withFirstRecordAsHeader().withDelimiter(io.getSeparators()[2]);

            parser = CSVParser.parse(files[2], io.getFileCharsets()[2], format);

            for (CSVRecord csvRecord : parser) {
                // We allow for null tasks...
                if (task != null) {
                    task.firePropertyChange(PROGRESS, 67 + ((numberOfLinesRead - 1) * 100 / linesToRead) / 3,
                            67 + ((numberOfLinesRead) * 100 / linesToRead) / 3);
                    task.firePropertyChange(SOURCES, ((numberOfLinesRead - 1) * 100 / linesToRead),
                            ((numberOfLinesRead) * 100 / linesToRead));
                }

                // Build source part
                Source source = new Source();
                for (int i = 0; i < map.size(); i++) {
                    Relation rel = map.get(i);
                    if (rel.getDatabaseTableVariableID() >= 0
                            && rel.getDatabaseTableName().equalsIgnoreCase(Globals.SOURCE_TABLE_NAME)) {
                        if (rel.getVariableType().equalsIgnoreCase("Number")) {
                            if (csvRecord.get(rel.getFileColumnNumber()).length() > 0) {
                                try {
                                    source.setVariable(rel.getDatabaseVariableName(),
                                            Integer.parseInt(csvRecord.get(rel.getFileColumnNumber())));
                                } catch (NumberFormatException ex) {
                                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE,
                                            "Number format error in line: " + (numberOfLinesRead + 1 + 1)
                                                    + ". ",
                                            ex);
                                    success = false;
                                }
                            }
                        } else {
                            source.setVariable(rel.getDatabaseVariableName(),
                                    csvRecord.get(rel.getFileColumnNumber()));
                        }
                    }
                    if (task != null) {
                        task.firePropertyChange(RECORD, i - 1 / map.size() * 50, i / map.size() * 50);
                    }
                }

                Tumour tumour = null;
                try {
                    tumour = CanRegClientApp.getApplication().getTumourRecordBasedOnTumourID(
                            (String) source.getVariable(io.getTumourIDSourceTableVariableName()), false);
                } catch (DistributedTableDescriptionException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (RecordLockedException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (RemoteException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SecurityException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnknownTableException ex) {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                }
                if (task != null) {
                    task.firePropertyChange(RECORD, 50, 75);
                }
                boolean addSource = true;

                if (tumour != null) {
                    Set<Source> sources = tumour.getSources();
                    Object sourceRecordID = source.getVariable(io.getSourceIDVariablename());
                    // look for source in sources
                    for (Source oldSource : sources) {
                        if (oldSource.getVariable(io.getSourceIDVariablename()).equals(sourceRecordID)) {
                            // deal with discrepancies
                            switch (io.getDiscrepancies()) {
                            case ImportOptions.REJECT:
                                addSource = false;
                                break;
                            case ImportOptions.UPDATE:
                                String updateReport = updateRecord(oldSource, source);
                                if (updateReport.length() > 0) {
                                    reportWriter.write(tumour.getVariable(io.getTumourIDVariablename())
                                            + Globals.newline + updateReport);
                                }
                                source = oldSource;
                                addSource = false;
                                break;
                            case ImportOptions.OVERWRITE:
                                // deleteTumour;
                                sources.remove(oldSource);
                                addSource = true;
                                break;
                            }
                        }
                    }
                    if (addSource) {
                        sources.add(source);
                    }
                    tumour.setSources(sources);
                    if (!io.isTestOnly()) {
                        server.editTumour(tumour);
                    }
                } else {
                    Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null,
                            "No tumour for source record.");
                }
                if (task != null) {
                    task.firePropertyChange(RECORD, 75, 100);
                }
                //Read next line of data

                numberOfLinesRead++;

                if (Thread.interrupted()) {
                    //We've been interrupted: no more importing.
                    reportWriter.flush();
                    throw new InterruptedException();
                }
            }
            reportWriter.write("Finished reading sources." + Globals.newline + Globals.newline);
            reportWriter.flush();
            parser.close();
        }
        if (task != null) {
            task.firePropertyChange(SOURCES, 100, 100);
            task.firePropertyChange(PROGRESS, 100, 100);
            while (!task.isProgressPropertyValid()) {
                // wait untill progress has been updated...
            }
        }
        reportWriter.write("Finished" + Globals.newline);
        reportWriter.flush();
        success = true;
    } catch (IOException ex) {
        Logger.getLogger(Import.class.getName()).log(Level.SEVERE,
                "Error in line: " + (numberOfLinesRead + 1 + 1) + ". ", ex);
        success = false;
    } catch (InterruptedException ex) {
        Logger.getLogger(Import.class.getName()).log(Level.INFO,
                "Interupted on line: " + (numberOfLinesRead + 1) + ". ", ex);
        success = true;
    } catch (IndexOutOfBoundsException ex) {
        Logger.getLogger(Import.class.getName()).log(Level.SEVERE,
                "String too short error in line: " + (numberOfLinesRead + 1 + 1) + ". ", ex);
        success = false;
    } finally {
        if (parser != null) {
            try {
                parser.close();
            } catch (IOException ex) {
                Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            reportWriter.flush();
            reportWriter.close();
        } catch (IOException ex) {
            Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    if (task != null) {
        task.firePropertyChange(PROGRESS, 100, 100);
        task.firePropertyChange("finished", null, null);
    }
    return success;
}

From source file:org.openecomp.sdc.be.servlets.AbstractValidationsServlet.java

private Either<org.openecomp.sdc.be.model.Resource, ResponseFormat> getAndValidateCsarYaml(
        Map<String, byte[]> csarUIPayload, org.openecomp.sdc.be.model.Resource resource, User user,
        String csarUUID) {/*from w  w  w  .j a v a  2  s.  co  m*/

    Either<ImmutablePair<String, String>, ResponseFormat> getToscaYamlRes = CsarValidationUtils
            .getToscaYaml(csarUIPayload, csarUUID, getComponentsUtils());

    if (getToscaYamlRes.isRight()) {
        ResponseFormat responseFormat = getToscaYamlRes.right().value();
        log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID,
                responseFormat);
        BeEcompErrorManager.getInstance().logBeDaoSystemError(
                "Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
        getComponentsUtils().auditResource(responseFormat, user, resource, "", "",
                AuditingActionEnum.CREATE_RESOURCE, null);
        return Either.right(responseFormat);
    }
    String toscaYaml = getToscaYamlRes.left().value().getValue();

    log.debug("checking tosca template is valid yml");
    YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
    boolean isValid = yamlConvertor.isValidYaml(toscaYaml.getBytes());
    if (!isValid) {
        ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_YAML_FILE);
        EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(
                AuditingFieldsKeysEnum.class);
        additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName());
        getComponentsUtils().auditResource(responseFormat, user, null, "", "",
                AuditingActionEnum.IMPORT_RESOURCE, additionalParam);
        return Either.right(responseFormat);
    }

    log.debug("checking payload is valid tosca");
    String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaYaml))
            ? new String(Base64.decodeBase64(toscaYaml))
            : toscaYaml;
    Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
    Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils
            .findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);

    if (findFirstToscaStringElement.isRight()) {
        isValid = false;
    } else {
        String defenitionVersionFound = findFirstToscaStringElement.left().value();
        if (defenitionVersionFound == null || defenitionVersionFound.isEmpty()) {
            isValid = false;
        } else {
            isValid = ImportUtils.Constants.TOSCA_DEFINITION_VERSIONS.contains(defenitionVersionFound);
        }
    }

    if (!isValid) {
        ResponseFormat responseFormat = getComponentsUtils()
                .getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
        EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(
                AuditingFieldsKeysEnum.class);
        additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName());
        getComponentsUtils().auditResource(responseFormat, user, null, "", "",
                AuditingActionEnum.IMPORT_RESOURCE, additionalParam);
        return Either.right(responseFormat);
    }
    return Either.left(resource);
}

From source file:org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.java

public EnumMap<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(
        ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) {
    EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(
            AuditingFieldsKeysEnum.class);
    // Putting together artifact info
    String artifactData = buildAuditingArtifactData(artifactDefinition);
    auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData);
    auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid);
    auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid);
    return auditingFields;
}

From source file:org.apache.hadoop.corona.ConfigManager.java

/**
 * Reload the general configuration and update all in-memory values. Should
 * be invoked under synchronization.//  ww w .java 2 s .c o  m
 *
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 */
private void reloadConfig() throws IOException, SAXException, ParserConfigurationException, JSONException {
    // Loading corona configuration as JSON.
    if (configFileName != null && configFileName.endsWith(Configuration.MATERIALIZEDJSON)) {
        reloadJsonConfig();
        return;
    }
    // Loading corona configuration as XML.  XML configurations are
    // deprecated.  We intend to remove all XML configurations and 
    // transition entirely into JSON.
    Map<ResourceType, Long> newTypeToNodeWait;
    Map<ResourceType, Long> newTypeToRackWait;
    ScheduleComparator newDefaultPoolComparator = DEFAULT_POOL_COMPARATOR;
    double newShareStarvingRatio = DEFAULT_SHARE_STARVING_RATIO;
    long newMinPreemptPeriod = DEFAULT_MIN_PREEMPT_PERIOD;
    int newGrantsPerIteration = DEFAULT_GRANTS_PER_ITERATION;
    long newStarvingTimeForMinimum = DEFAULT_STARVING_TIME_FOR_MINIMUM;
    long newStarvingTimeForShare = DEFAULT_STARVING_TIME_FOR_SHARE;
    long newPreemptedTaskMaxRunningTime = DEFAULT_PREEMPT_TASK_MAX_RUNNING_TIME;
    int newPreemptionRounds = DEFAULT_PREEMPTION_ROUNDS;
    boolean newScheduleFromNodeToSession = DEFAULT_SCHEDULE_FROM_NODE_TO_SESSION;
    newTypeToNodeWait = new EnumMap<ResourceType, Long>(ResourceType.class);
    newTypeToRackWait = new EnumMap<ResourceType, Long>(ResourceType.class);
    Map<PoolInfo, PoolInfo> newPoolInfoToRedirect = new HashMap<PoolInfo, PoolInfo>();

    for (ResourceType type : TYPES) {
        newTypeToNodeWait.put(type, 0L);
        newTypeToRackWait.put(type, 0L);
    }

    Element root = getRootElement(configFileName);
    NodeList elements = root.getChildNodes();
    for (int i = 0; i < elements.getLength(); ++i) {
        Node node = elements.item(i);
        if (!(node instanceof Element)) {
            continue;
        }
        Element element = (Element) node;
        for (ResourceType type : TYPES) {
            if (matched(element, "nodeLocalityWait" + type)) {
                long val = Long.parseLong(getText(element));
                newTypeToNodeWait.put(type, val);
            }
            if (matched(element, "rackLocalityWait" + type)) {
                long val = Long.parseLong(getText(element));
                newTypeToRackWait.put(type, val);
            }
        }
        if (matched(element, "defaultSchedulingMode")) {
            newDefaultPoolComparator = ScheduleComparator.valueOf(getText(element));
        }
        if (matched(element, "shareStarvingRatio")) {
            newShareStarvingRatio = Double.parseDouble(getText(element));
            if (newShareStarvingRatio < 0 || newShareStarvingRatio > 1.0) {
                LOG.error("Illegal shareStarvingRatio:" + newShareStarvingRatio);
                newShareStarvingRatio = DEFAULT_SHARE_STARVING_RATIO;
            }
        }
        if (matched(element, "grantsPerIteration")) {
            newGrantsPerIteration = Integer.parseInt(getText(element));
            if (newMinPreemptPeriod < 0) {
                LOG.error("Illegal grantsPerIteration: " + newGrantsPerIteration);
                newGrantsPerIteration = DEFAULT_GRANTS_PER_ITERATION;
            }
        }
        if (matched(element, "minPreemptPeriod")) {
            newMinPreemptPeriod = Long.parseLong(getText(element));
            if (newMinPreemptPeriod < 0) {
                LOG.error("Illegal minPreemptPeriod: " + newMinPreemptPeriod);
                newMinPreemptPeriod = DEFAULT_MIN_PREEMPT_PERIOD;
            }
        }
        if (matched(element, "starvingTimeForShare")) {
            newStarvingTimeForShare = Long.parseLong(getText(element));
            if (newStarvingTimeForShare < 0) {
                LOG.error("Illegal starvingTimeForShare:" + newStarvingTimeForShare);
                newStarvingTimeForShare = DEFAULT_STARVING_TIME_FOR_SHARE;
            }
        }
        if (matched(element, "starvingTimeForMinimum")) {
            newStarvingTimeForMinimum = Long.parseLong(getText(element));
            if (newStarvingTimeForMinimum < 0) {
                LOG.error("Illegal starvingTimeForMinimum:" + newStarvingTimeForMinimum);
                newStarvingTimeForMinimum = DEFAULT_STARVING_TIME_FOR_MINIMUM;
            }
        }
        if (matched(element, "preemptedTaskMaxRunningTime")) {
            newPreemptedTaskMaxRunningTime = Long.parseLong(getText(element));
            if (newPreemptedTaskMaxRunningTime < 0) {
                LOG.error("Illegal preemptedTaskMaxRunningTime:" + newPreemptedTaskMaxRunningTime);
                newPreemptedTaskMaxRunningTime = DEFAULT_PREEMPT_TASK_MAX_RUNNING_TIME;
            }
        }
        if (matched(element, "preemptionRounds")) {
            newPreemptionRounds = Integer.parseInt(getText(element));
            if (newPreemptionRounds < 0) {
                LOG.error("Illegal preemptedTaskMaxRunningTime:" + newPreemptionRounds);
                newPreemptionRounds = DEFAULT_PREEMPTION_ROUNDS;
            }
        }
        if (matched(element, "scheduleFromNodeToSession")) {
            newScheduleFromNodeToSession = Boolean.parseBoolean(getText(element));
        }
        if (matched(element, REDIRECT_TAG_NAME)) {
            loadPoolInfoToRedirect(element.getAttribute(SOURCE_ATTRIBUTE),
                    element.getAttribute(DESTINATION_ATTRIBUTE), newPoolInfoToRedirect);
        }
    }
    synchronized (this) {
        this.typeToNodeWait = newTypeToNodeWait;
        this.typeToRackWait = newTypeToRackWait;
        this.defaultPoolComparator = newDefaultPoolComparator;
        this.shareStarvingRatio = newShareStarvingRatio;
        this.minPreemptPeriod = newMinPreemptPeriod;
        this.grantsPerIteration = newGrantsPerIteration;
        this.starvingTimeForMinimum = newStarvingTimeForMinimum;
        this.starvingTimeForShare = newStarvingTimeForShare;
        this.preemptedTaskMaxRunningTime = newPreemptedTaskMaxRunningTime;
        this.preemptionRounds = newPreemptionRounds;
        this.scheduleFromNodeToSession = newScheduleFromNodeToSession;
        this.poolInfoToRedirect = newPoolInfoToRedirect;
    }
}

From source file:org.openecomp.sdc.be.components.impl.ResourceImportManager.java

private void auditErrorImport(UploadResourceInfo resourceMetaData, User user,
        ResponseFormat errorResponseWrapper, boolean isNormative) {
    EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
    auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.IMPORT_RESOURCE.getName());
    auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceMetaData.getName());
    auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, ComponentTypeEnum.RESOURCE.getValue());
    auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, "");
    auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, user.getUserId());
    auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, "");
    auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, "");
    auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, errorResponseWrapper.getStatus());
    String message = "";
    if (errorResponseWrapper.getMessageId() != null) {
        message = errorResponseWrapper.getMessageId() + ": ";
    }/*  www  .jav a  2  s  .c o  m*/
    message += errorResponseWrapper.getFormattedMessage();
    auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
    auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME,
            user.getFirstName() + " " + user.getLastName());

    String version, lifeCycleState;
    if (isNormative) {
        version = Constants.FIRST_CERTIFIED_VERSION_VERSION;
        lifeCycleState = LifecycleStateEnum.CERTIFIED.name();
    } else {
        version = "";
        lifeCycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name();

    }
    auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, version);
    auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, lifeCycleState);
    auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, "");

    getAuditingManager().auditEvent(auditingFields);
}

From source file:sg.ncl.MainController.java

@RequestMapping(path = "/password_reset")
public String resetPassword(@ModelAttribute("passwordResetForm") PasswordResetForm passwordResetForm)
        throws IOException {
    if (!passwordResetForm.isPasswordOk()) {
        return FORGET_PSWD_NEW_PSWD_PAGE;
    }/*from w  w w . j a  va2  s  .  c  o m*/

    JSONObject obj = new JSONObject();
    obj.put("key", passwordResetForm.getKey());
    obj.put("new", passwordResetForm.getPassword1());

    log.info("Connecting to sio for password reset, key = {}", passwordResetForm.getKey());
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> request = new HttpEntity<>(obj.toString(), headers);
    restTemplate.setErrorHandler(new MyResponseErrorHandler());
    ResponseEntity response = null;
    try {
        response = restTemplate.exchange(properties.getPasswordResetURI(), HttpMethod.PUT, request,
                String.class);
    } catch (RestClientException e) {
        log.warn("Error connecting to sio for password reset! {}", e);
        passwordResetForm.setErrMsg("Cannot connect to server! Please try again later.");
        return FORGET_PSWD_NEW_PSWD_PAGE;
    }

    if (RestUtil.isError(response.getStatusCode())) {
        EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class);
        exceptionMessageMap.put(PASSWORD_RESET_REQUEST_TIMEOUT_EXCEPTION,
                "Password reset request timed out. Please request a new reset email.");
        exceptionMessageMap.put(PASSWORD_RESET_REQUEST_NOT_FOUND_EXCEPTION,
                "Invalid password reset request. Please request a new reset email.");
        exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION,
                "Server-side error. Please contact " + CONTACT_EMAIL);

        MyErrorResource error = objectMapper.readValue(response.getBody().toString(), MyErrorResource.class);
        ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());

        final String errMsg = exceptionMessageMap.get(exceptionState) == null ? ERR_SERVER_OVERLOAD
                : exceptionMessageMap.get(exceptionState);
        passwordResetForm.setErrMsg(errMsg);
        log.warn("Server responded error for password reset: {}", exceptionState.toString());
        return FORGET_PSWD_NEW_PSWD_PAGE;
    }
    log.info("Password was reset, key = {}", passwordResetForm.getKey());
    return "password_reset_success";
}