Example usage for java.lang Integer toString

List of usage examples for java.lang Integer toString

Introduction

In this page you can find the example usage for java.lang Integer toString.

Prototype

public String toString() 

Source Link

Document

Returns a String object representing this Integer 's value.

Usage

From source file:MathUtils.java

/**
 * <p>//from   w ww . ja v  a 2  s. c o  m
 * Returns a visual approximation of a number, keeping only a specified decimals. <br/>
 * For exemple : <br/>
 *    &nbsp; approximate(12.2578887 , 2) will return 12.25 <br/>
 *    &nbsp; approximate(12.25 , 0) will return 12 <br/>
 *    &nbsp; approximate(12.00 , 3) will return 12 <br/>
 *    &nbsp; approximate(19.5 , 0) will return 20 <br/>
 *</p>
 * <p>The last exemple emphasis the fact that it's made for showing convenient numbers for no mathematical public. If the number was</p>
 * <p>Note that Math.round(19.5) returns 20, not 19. This function will act the same way.</p>
 * @param n
 * @param precision
 * @return
 */
public static String approximate(Number n, int precision) {

    if (n instanceof Integer) {
        return n.toString();
    }

    String s = n.toString();

    if (!s.contains(".")) {
        return s;
    }

    String serious = s.substring(0, s.indexOf('.'));

    s = s.substring(s.indexOf('.') + 1);
    s = StringUtils.removeTrailingCharacters(s, '0');

    if (s.length() == 0) {
        return serious;
    }

    // We'll comments results based on approximate(12.63645, 3) and approximate(12.63545, 0)
    String decimals = "";

    if (s.length() > precision) {

        decimals = StringUtils.truncate(s, precision + 1);
        //decimal is now "636" or "6"

        Float after = new Float(decimals);
        //after is 636 or 6, as Float objects
        after = after / 10;
        //after is 63.6 or .6, as Float objects
        Integer round = Math.round(after);
        //round is 64 or 1
        decimals = round.toString();
        decimals = StringUtils.removeTrailingCharacters(decimals, '0');

    } else {

        decimals = StringUtils.truncate(s, precision);
        decimals = StringUtils.removeTrailingCharacters(decimals, '0');

    }

    if (decimals.length() > 0 && precision > 0) {
        return serious + "." + decimals;
    } else {
        //if we must round the serious string
        if (decimals.length() > 0 && precision == 0) {
            assert decimals.length() == 1 : "problem here !";
            if (decimals.length() != 1) {
                throw new IllegalStateException(
                        "Error in the algorithm for MathUtilisties.approximate(" + n + ", " + precision + ")");
            }
            Integer finalValue = new Integer(decimals);
            if (finalValue > 0) {
                Integer si = new Integer(serious);
                si += 1;
                return si.toString();
            } else {
                return serious;
            }
        } else {
            return serious;
        }
    }
}

From source file:com.t3.macro.api.functions.input.InputFunctions.java

/**
 * <pre>//w  ww .j  ava 2  s. co m
 * <span style="font-family:sans-serif;">The input() function prompts the user to input several variable values at once.
 * 
 * Each of the string parameters has the following format:
 *     "varname|value|prompt|inputType|options"
 * 
 * Only the first section is required.
 *     varname   - the variable name to be assigned
 *     value     - sets the initial contents of the input field
 *     prompt    - UI text shown for the variable
 *     inputType - specifies the type of input field
 *     options   - a string of the form "opt1=val1; opt2=val2; ..."
 * 
 * The inputType field can be any of the following (defaults to TEXT):
 *     TEXT  - A text field.
 *             "value" sets the initial contents.
 *             The return value is the string in the text field.
 *             Option: WIDTH=nnn sets the width of the text field (default 16).
 *     LIST  - An uneditable combo box.
 *             "value" populates the list, and has the form "item1,item2,item3..." (trailing empty strings are dropped)
 *             The return value is the numeric index of the selected item.
 *             Option: SELECT=nnn sets the initial selection (default 0).
 *             Option: VALUE=STRING returns the string contents of the selected item (default NUMBER).
 *             Option: TEXT=FALSE suppresses the text of the list item (default TRUE).
 *             Option: ICON=TRUE causes icon asset URLs to be extracted from the "value" and displayed (default FALSE).
 *             Option: ICONSIZE=nnn sets the size of the icons (default 50).
 *     CHECK - A checkbox.
 *             "value" sets the initial state of the box (anything but "" or "0" checks the box)
 *             The return value is 0 or 1.
 *             No options.
 *     RADIO - A group of radio buttons.
 *             "value" is a list "name1, name2, name3, ..." which sets the labels of the buttons.
 *             The return value is the index of the selected item.
 *             Option: SELECT=nnn sets the initial selection (default 0).
 *             Option: ORIENT=H causes the radio buttons to be laid out on one line (default V).
 *             Option: VALUE=STRING causes the return value to be the string of the selected item (default NUMBER).
 *     LABEL - A label.
 *             The "varname" is ignored and no value is assigned to it.
 *             Option: TEXT=FALSE, ICON=TRUE, ICONSIZE=nnn, as in the LIST type.
 *     PROPS - A sub-panel with multiple text boxes.
 *             "value" contains a StrProp of the form "key1=val1; key2=val2; ..."
 *             One text box is created for each key, populated with the matching value.
 *             Option: SETVARS=SUFFIXED causes variable assignment to each key name, with appended "_" (default NONE).
 *             Option: SETVARS=UNSUFFIXED causes variable assignment to each key name.
 *     TAB   - A tabbed dialog tab is created.  Subsequent variables are contained in the tab.
 *             Option: SELECT=TRUE causes this tab to be shown at start (default SELECT=FALSE).
 * 
 *  All inputTypes except TAB accept the option SPAN=TRUE, which causes the prompt to be hidden and the input
 *  control to span both columns of the dialog layout (default FALSE).
 * </span>
 * </pre>
 * @param parameters a list of strings containing information as described above
 * @return a HashMap with the returned values or null if the user clicked on cancel
 * @author knizia.fan
 * @throws MacroException 
 */
public static Map<String, String> input(TokenView token, String... parameters) throws MacroException {
    // Extract the list of specifier strings from the parameters
    // "name | value | prompt | inputType | options"
    List<String> varStrings = new ArrayList<String>();
    for (Object param : parameters) {
        String paramStr = (String) param;
        if (StringUtils.isEmpty(paramStr)) {
            continue;
        }
        // Multiple vars can be packed into a string, separated by "##"
        for (String varString : StringUtils.splitByWholeSeparator(paramStr, "##")) {
            if (StringUtils.isEmpty(paramStr)) {
                continue;
            }
            varStrings.add(varString);
        }
    }

    // Create VarSpec objects from each variable's specifier string
    List<VarSpec> varSpecs = new ArrayList<VarSpec>();
    for (String specifier : varStrings) {
        VarSpec vs;
        try {
            vs = new VarSpec(specifier);
        } catch (VarSpec.SpecifierException se) {
            throw new MacroException(se);
        } catch (InputType.OptionException oe) {
            throw new MacroException(I18N.getText("macro.function.input.invalidOptionType", oe.key, oe.value,
                    oe.type, specifier));
        }
        varSpecs.add(vs);
    }

    // Check if any variables were defined
    if (varSpecs.isEmpty())
        return Collections.emptyMap(); // No work to do, so treat it as a successful invocation.

    // UI step 1 - First, see if a token is given

    String dialogTitle = "Input Values";
    if (token != null) {
        String name = token.getName(), gm_name = token.getGMName();
        boolean isGM = TabletopTool.getPlayer().isGM();
        String extra = "";

        if (isGM && gm_name != null && gm_name.compareTo("") != 0)
            extra = " for " + gm_name;
        else if (name != null && name.compareTo("") != 0)
            extra = " for " + name;

        dialogTitle = dialogTitle + extra;
    }

    // UI step 2 - build the panel with the input fields
    InputPanel ip = new InputPanel(varSpecs);

    // Calculate the height
    // TODO: remove this workaround
    int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
    int maxHeight = screenHeight * 3 / 4;
    Dimension ipPreferredDim = ip.getPreferredSize();
    if (maxHeight < ipPreferredDim.height) {
        ip.modifyMaxHeightBy(maxHeight - ipPreferredDim.height);
    }

    // UI step 3 - show the dialog
    JOptionPane jop = new JOptionPane(ip, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
    JDialog dlg = jop.createDialog(TabletopTool.getFrame(), dialogTitle);

    // Set up callbacks needed for desired runtime behavior
    dlg.addComponentListener(new FixupComponentAdapter(ip));

    dlg.setVisible(true);
    int dlgResult = JOptionPane.CLOSED_OPTION;
    try {
        dlgResult = (Integer) jop.getValue();
    } catch (NullPointerException npe) {
    }
    dlg.dispose();

    if (dlgResult == JOptionPane.CANCEL_OPTION || dlgResult == JOptionPane.CLOSED_OPTION)
        return null;

    HashMap<String, String> results = new HashMap<String, String>();

    // Finally, assign values from the dialog box to the variables
    for (ColumnPanel cp : ip.columnPanels) {
        List<VarSpec> panelVars = cp.varSpecs;
        List<JComponent> panelControls = cp.inputFields;
        int numPanelVars = panelVars.size();
        StringBuilder allAssignments = new StringBuilder(); // holds all values assigned in this tab

        for (int varCount = 0; varCount < numPanelVars; varCount++) {
            VarSpec vs = panelVars.get(varCount);
            JComponent comp = panelControls.get(varCount);
            String newValue = null;
            switch (vs.inputType) {
            case TEXT: {
                newValue = ((JTextField) comp).getText();
                break;
            }
            case LIST: {
                Integer index = ((JComboBox) comp).getSelectedIndex();
                if (vs.optionValues.optionEquals("VALUE", "STRING")) {
                    newValue = vs.valueList.get(index);
                } else { // default is "NUMBER"
                    newValue = index.toString();
                }
                break;
            }
            case CHECK: {
                Integer value = ((JCheckBox) comp).isSelected() ? 1 : 0;
                newValue = value.toString();
                break;
            }
            case RADIO: {
                // This code assumes that the Box container returns components
                // in the same order that they were added.
                Component[] comps = ((Box) comp).getComponents();
                int componentCount = 0;
                Integer index = 0;
                for (Component c : comps) {
                    if (c instanceof JRadioButton) {
                        JRadioButton radio = (JRadioButton) c;
                        if (radio.isSelected())
                            index = componentCount;
                    }
                    componentCount++;
                }
                if (vs.optionValues.optionEquals("VALUE", "STRING")) {
                    newValue = vs.valueList.get(index);
                } else { // default is "NUMBER"
                    newValue = index.toString();
                }
                break;
            }
            case LABEL: {
                newValue = null;
                // The variable name is ignored and not set.
                break;
            }
            case PROPS: {
                // Read out and assign all the subvariables.
                // The overall return value is a property string (as in StrPropFunctions.java) with all the new settings.
                Component[] comps = ((JPanel) comp).getComponents();
                StringBuilder sb = new StringBuilder();
                int setVars = 0; // "NONE", no assignments made
                if (vs.optionValues.optionEquals("SETVARS", "SUFFIXED"))
                    setVars = 1;
                if (vs.optionValues.optionEquals("SETVARS", "UNSUFFIXED"))
                    setVars = 2;
                if (vs.optionValues.optionEquals("SETVARS", "TRUE"))
                    setVars = 2; // for backward compatibility
                for (int compCount = 0; compCount < comps.length; compCount += 2) {
                    String key = ((JLabel) comps[compCount]).getText().split("\\:")[0]; // strip trailing colon
                    String value = ((JTextField) comps[compCount + 1]).getText();
                    sb.append(key);
                    sb.append("=");
                    sb.append(value);
                    sb.append(" ; ");
                    switch (setVars) {
                    case 0:
                        // Do nothing
                        break;
                    case 1:
                        results.put(key + "_", value);
                        break;
                    case 2:
                        results.put(key, value);
                        break;
                    }
                }
                newValue = sb.toString();
                break;
            }
            default:
                // should never happen
                newValue = null;
                break;
            }
            // Set the variable to the value we got from the dialog box.
            if (newValue != null) {
                results.put(vs.name, newValue.trim());
                allAssignments.append(vs.name + "=" + newValue.trim() + " ## ");
            }
        }
        if (cp.tabVarSpec != null) {
            results.put(cp.tabVarSpec.name, allAssignments.toString());
        }
    }

    return results; // success

    // for debugging:
    //return debugOutput(varSpecs);
}

From source file:net.sourceforge.fenixedu.presentationTier.docs.academicAdministrativeOffice.DegreeFinalizationCertificate.java

static final public String getDegreeFinalizationGrade(final Integer finalAverage, final Locale locale) {
    final StringBuilder result = new StringBuilder();

    result.append(", ").append(
            BundleUtil.getString(Bundle.ACADEMIC, locale, "documents.registration.final.arithmetic.mean"));
    result.append(SINGLE_SPACE).append(BundleUtil.getString(Bundle.ACADEMIC, locale, "label.of.both"));
    result.append(SINGLE_SPACE).append(finalAverage);
    result.append(" (").append(BundleUtil.getString(Bundle.ENUMERATION, locale, finalAverage.toString()));
    result.append(") ").append(BundleUtil.getString(Bundle.ACADEMIC, locale, "values"));

    return result.toString();
}

From source file:com.topsec.tsm.common.message.CommandHandlerUtil.java

public static Serializable handleGetUserRule(Serializable obj, EventRuleService eventRuleService,
        EventResponseService eventResponseService) {
    try {//from   ww w  .j a v a2s . co  m
        List<EventRule> eventRules = eventRuleService.getEnableRuleInRuleGroup();
        if (eventRules != null && eventRules.size() != 0) {
            final List<EventRuleGroup> eventRuleGroups = eventRuleService.getEnableRuleGroup();
            final List<EventRuleDispatch> eventRuleGroupDispatchs = eventRuleService
                    .getEnableEventRuleDispatch();
            final List<EventRuleGroupResp> ruleGroupResps = eventRuleService.getAllRuleGroupResp();
            final CorrRuleBuilder groupBuilder = new CorrRuleBuilder();
            final EventResponseService responseService = eventResponseService;
            RuleBuilder ruleBuilder = new RuleBuilder() {
                @Override
                public Response getReponse(String responseId) {
                    return responseService.getResponse(responseId);
                }

                @Override
                public Rule convertXMLRule(EventRule eventRule) {
                    Rule rule = super.convertXMLRule(eventRule);
                    List<Group> groups = new ArrayList<Group>();
                    Map<String, Integer> sizeMap = new HashMap<String, Integer>();
                    if (eventRuleGroups != null) {
                        for (EventRuleDispatch eventRuleDispatch : eventRuleGroupDispatchs) {
                            Integer ruleId = eventRule.getId();
                            Integer groupId = eventRuleDispatch.getGroupId();
                            Integer count = sizeMap.get(groupId.toString());
                            sizeMap.put(groupId.toString(), (count == null ? 1 : ++count));
                            if (ruleId.intValue() == eventRuleDispatch.getRuleId().intValue()) {
                                Integer order = eventRuleDispatch.getOrder();
                                String groupName = null;
                                Integer alarmState = 0;
                                Integer priority = 0;
                                String category1 = null;
                                String category2 = null;
                                String desc = null;
                                long timeout = 0;
                                for (EventRuleGroup eventRuleGroup : eventRuleGroups) {
                                    if (eventRuleGroup.getGroupId().intValue() == groupId.intValue()) {
                                        groupName = eventRuleGroup.getGroupName();
                                        alarmState = eventRuleGroup.getAlarmState();
                                        timeout = eventRuleGroup.getTimeout();
                                        priority = eventRuleGroup.getPriority();
                                        category1 = eventRuleGroup.getCat1id();
                                        category2 = eventRuleGroup.getCat2id();
                                        desc = eventRuleGroup.getDesc();
                                        break;
                                    }
                                }
                                if (groupName != null) {
                                    groupBuilder.setDispatch(eventRuleDispatch);
                                    Integer dtimeout = eventRuleDispatch.getTimeout();
                                    State state = new State(dtimeout);
                                    Group group = new Group(groupId.toString(), groupName, order, alarmState,
                                            state);
                                    group.setTimeout(timeout);
                                    group.setPriority(priority == null ? -1 : priority);
                                    group.setDesc(desc);
                                    groupBuilder.rebuild(group);
                                    List<String> respIdList = new ArrayList<String>();
                                    for (EventRuleGroupResp eventRuleGroupResp : ruleGroupResps) {
                                        if (eventRuleGroupResp.getGroupId().intValue() == groupId.intValue()) {
                                            String responseId = eventRuleGroupResp.getResponseId();
                                            respIdList.add(responseId);
                                        }
                                    }
                                    if (category1 != null) {
                                        group.setCategory1(category1);
                                    }
                                    if (category2 != null) {
                                        group.setCategory2(category2);
                                    }

                                    String[] responseIds = new String[respIdList.size()];
                                    respIdList.toArray(responseIds);
                                    group.setResponseIds(responseIds);
                                    String[] responsecfgkeys = new String[respIdList.size()];
                                    String[] responsecfgNames = new String[respIdList.size()];

                                    for (int i = 0; i < responseIds.length; i++) {
                                        Response response = this.getReponse(responseIds[i]);
                                        if (response != null) {
                                            responsecfgkeys[i] = response.getCfgKey();
                                            responsecfgNames[i] = response.getName();
                                        }
                                    }
                                    group.setResponsecfgkeys(responsecfgkeys);
                                    group.setResponsecfgNames(responsecfgNames);
                                    groups.add(group);
                                }
                            }
                        }

                        for (Group group : groups) {
                            String groupId = group.getGroupId();
                            Integer size = sizeMap.get(groupId);
                            if (size.intValue() < group.getOrder()) {
                                throw new RuntimeException("![groupId=" + groupId + "],[size="
                                        + size + "],[order=" + group.getOrder() + "]");
                            }
                            group.setSize(size);
                        }
                        rule.setBelongGroups(groups);
                    }
                    return rule;
                }
            };

            EventRule[] ruleEventRules = new EventRule[eventRules.size()];
            eventRules.toArray(ruleEventRules);
            ruleBuilder.rebuildEventRule(ruleEventRules);
        } else {
            return new ArrayList<EventRule>();
        }
        return (Serializable) eventRules;
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.nridge.core.base.std.StrUtl.java

/**
 * Convenience method that converts a generic ArrayList of
 * Objects into an array of string values.
 *
 * @param anArrayList Array of value object instances.
 *
 * @return An array of values extracted from the array list.
 *///from   ww w . j a v  a2s. c om
public static String[] convertToMulti(ArrayList<?> anArrayList) {
    if ((anArrayList == null) || (anArrayList.size() == 0)) {
        String[] emptyList = new String[1];
        emptyList[0] = StringUtils.EMPTY;
        return emptyList;
    }

    int offset = 0;
    String[] multiValues = new String[anArrayList.size()];

    for (Object arrayObject : anArrayList) {
        if (arrayObject instanceof Integer) {
            Integer integerValue = (Integer) arrayObject;
            multiValues[offset++] = integerValue.toString();
        } else if (arrayObject instanceof Long) {
            Long longValue = (Long) arrayObject;
            multiValues[offset++] = longValue.toString();
        } else if (arrayObject instanceof Float) {
            Float floatValue = (Float) arrayObject;
            multiValues[offset++] = floatValue.toString();
        } else if (arrayObject instanceof Double) {
            Double doubleValue = (Double) arrayObject;
            multiValues[offset++] = doubleValue.toString();
        } else if (arrayObject instanceof Date) {
            Date dateValue = (Date) arrayObject;
            multiValues[offset++] = Field.dateValueFormatted(dateValue, Field.FORMAT_DATETIME_DEFAULT);
        } else
            multiValues[offset++] = arrayObject.toString();
    }

    return multiValues;
}

From source file:de.willuhn.jameica.hbci.server.KontoauszugPdfUtil.java

/**
 * Erzeugt den Pfad fuer den zu speichernden Kontoauszug.
 * @param k das Konto./* w  w w .  j a  v a  2 s  . c  om*/
 * @param ka der Kontoauszug. Optional. Wenn er fehlt, werden Default-Werte verwendet.
 * @param path Ordner, in dem die Kontoauszuege gespeichert werden.
 * @param folder Template fuer den Unterordner.
 * @param name Template fuer den Dateinamen.
 * @return der Pfad.
 * @throws RemoteException
 * @throws ApplicationException
 */
public static String createPath(Konto k, Kontoauszug ka, String path, String folder, String name)
        throws RemoteException, ApplicationException {
    if (k == null)
        throw new ApplicationException(i18n.tr("Kein Konto angegeben"));

    Map<String, Object> ctx = new HashMap<String, Object>();

    {
        String iban = StringUtils.trimToNull(k.getIban());
        if (iban == null)
            iban = StringUtils.trimToEmpty(k.getKontonummer());

        ctx.put("iban", iban.replaceAll(" ", ""));
    }

    {
        String bic = StringUtils.trimToNull(k.getBic());
        if (bic == null)
            bic = StringUtils.trimToEmpty(k.getBLZ());

        ctx.put("bic", bic.replaceAll(" ", ""));
    }

    {
        Calendar cal = Calendar.getInstance();
        if (ka != null) {
            if (ka.getErstellungsdatum() != null)
                cal.setTime(ka.getErstellungsdatum());
            else if (ka.getAusfuehrungsdatum() != null)
                cal.setTime(ka.getAusfuehrungsdatum());
        }

        Integer i = ka != null && ka.getJahr() != null ? ka.getJahr() : null;
        ctx.put("jahr", i != null ? i.toString() : Integer.toString(cal.get(Calendar.YEAR)));
        ctx.put("monat", String.format("%02d", cal.get(Calendar.MONTH) + 1));
        ctx.put("tag", String.format("%02d", cal.get(Calendar.DATE)));
        ctx.put("stunde", String.format("%02d", cal.get(Calendar.HOUR_OF_DAY)));
        ctx.put("minute", String.format("%02d", cal.get(Calendar.MINUTE)));
    }

    {
        Integer i = ka != null && ka.getNummer() != null ? ka.getNummer() : null;
        ctx.put("nummer", String.format("%03d", i != null ? i.intValue() : 1));
    }

    VelocityService velocity = Application.getBootLoader().getBootable(VelocityService.class);
    StringBuilder sb = new StringBuilder();

    /////////////////////////////
    // Pfad
    {
        if (path == null || path.length() == 0)
            path = Application.getPluginLoader().getPlugin(HBCI.class).getResources().getWorkPath();
        sb.append(path);

        if (!path.endsWith(File.separator))
            sb.append(File.separator);
    }
    //
    /////////////////////////////

    /////////////////////////////
    // Unter-Ordner
    {
        if (folder != null && folder.length() > 0) {
            try {
                // Velocity-Escaping machen wir. Das sollte der User nicht selbst machen muessen
                // Eigentlich wird hier nur "\$" gegen "\\$" ersetzt. Die zusaetzlichen
                // Die extra Escapings sind fuer Java selbst in String-Literalen.
                folder = folder.replace("\\$", "\\\\$");
                folder = velocity.merge(folder, ctx);
            } catch (Exception e) {
                Logger.error("folder template invalid: \"" + folder + "\"", e);
            }
            sb.append(folder);
            if (!folder.endsWith(File.separator))
                sb.append(File.separator);
        }
    }
    //
    /////////////////////////////

    /////////////////////////////
    // Dateiname
    {
        if (name == null || name.length() == 0 && ka != null)
            name = ka.getDateiname();

        if (name == null || name.length() == 0)
            name = MetaKey.KONTOAUSZUG_TEMPLATE_NAME.getDefault();

        try {
            name = velocity.merge(name, ctx);
        } catch (Exception e) {
            Logger.error("name template invalid: \"" + name + "\"", e);
        }
        sb.append(name);

        // Dateiendung noch anhaengen.
        Format f = Format.find(ka != null ? ka.getFormat() : null);
        if (f == null)
            f = Format.PDF;

        sb.append(".");
        sb.append(f.getExtention());
    }

    return sb.toString();
}

From source file:ips1ap101.lib.base.util.ObjUtils.java

public static String toString(Object o) {
    if (o == null) {
        return null;
    } else if (invalidUIInput(o)) {
        return null;
    } else if (o instanceof Checkbox) {
        return trimToNull(((Checkbox) o).getSelected());
    } else if (o instanceof DropDown) {
        return trimToNull(((DropDown) o).getSelected());
    } else if (o instanceof TextField) {
        return trimToNull(((TextField) o).getText());
    } else if (o instanceof PasswordField) {
        return trimToNull(((PasswordField) o).getPassword());
    } else if (o instanceof CampoArchivo) {
        return StringUtils.trimToNull(((CampoArchivo) o).getServerFileName());
    } else if (o instanceof CampoArchivoMultiPart) {
        return StringUtils.trimToNull(((CampoArchivoMultiPart) o).getServerFileName());
    } else if (o instanceof RecursoCodificable) {
        return StringUtils.trimToNull(((RecursoCodificable) o).getCodigoRecurso());
    } else if (o instanceof RecursoNombrable) {
        return StringUtils.trimToNull(((RecursoNombrable) o).getNombreRecurso());
    } else if (o instanceof RecursoIdentificable) {
        Long id = ((RecursoIdentificable) o).getIdentificacionRecurso();
        return id == null ? null : id.toString();
    } else if (o instanceof RecursoEnumerable) {
        Integer numero = ((RecursoEnumerable) o).getNumeroRecurso();
        return numero == null ? null : numero.toString();
    }//from  www  .j  a va2  s.  c  o  m
    return o.toString();
}

From source file:com.opengamma.analytics.financial.provider.curve.MulticurveBuildingDiscountingDiscountUSD2Test.java

private static ZonedDateTimeDoubleTimeSeries[] getTSSwapFixedIbor(final Boolean withToday, final Integer unit) {
    //REVIEW is it intended that the first two branches of the switch statement do the same thing
    switch (unit) {
    case 0://www .j  a v a 2  s  .c  om
        return withToday ? TS_FIXED_IBOR_USD3M_WITH_TODAY : TS_FIXED_IBOR_USD3M_WITHOUT_TODAY;
    case 1:
        return withToday ? TS_FIXED_IBOR_USD3M_WITH_TODAY : TS_FIXED_IBOR_USD3M_WITHOUT_TODAY;
    default:
        throw new IllegalArgumentException(unit.toString());
    }
}

From source file:com.hpcloud.daas.ec2.AwsConsoleApp.java

public static void AddSecurityPorts(List<Integer> ports, String securityGroupName) throws Exception {
    for (Integer port : ports) {
        try {/*w  w w  .  j  a  v a2s.  co m*/
            AuthorizeSecurityGroupIngressRequest securityPortsRequest = new AuthorizeSecurityGroupIngressRequest();
            securityPortsRequest.setFromPort(port);
            securityPortsRequest.setIpProtocol("tcp");
            securityPortsRequest.setToPort(port);
            securityPortsRequest.setGroupName(securityGroupName);

            ec2.authorizeSecurityGroupIngress(securityPortsRequest);

            System.out.println("Added Access to port " + port.toString());

        } catch (AmazonServiceException ase) {
            System.out.println("Error : Adding access to port " + port.toString());
            System.out.println("Caught Exception: " + ase.getMessage());
            System.out.println("Reponse Status Code: " + ase.getStatusCode());
            System.out.println("Error Code: " + ase.getErrorCode());
            System.out.println("Request ID: " + ase.getRequestId());
        }
    }
}

From source file:com.ecofactor.qa.automation.dao.util.DataUtil.java

/**
 * Prints the spo job data json.//from   w ww.j  a  v a 2s  . c o  m
 * @param jsonArray the json array
 */
public static void printSPOJobDataJson(JSONArray jsonArray) {

    DriverConfig.setLogString("Json Grid", true);
    DriverConfig.setLogString(
            "=============================================================================================================================",
            true);
    DriverConfig.setLogString(
            "|        Start Time         |         End Time         |  Delta EE  |  MO BlackOut  |        MO Cuttoff        | MO Recovery |",
            true);
    DriverConfig.setLogString(
            "=============================================================================================================================",
            true);
    int loopVal = 0;
    for (int i = 0; i < jsonArray.length(); i++) {
        try {

            if (loopVal != 0) {
                DriverConfig.setLogString(
                        "=============================================================================================================================",
                        true);
            }
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            String startCal = (String) jsonObj.get("start");
            String endcal = (String) jsonObj.get("end");
            Double deltaEE = (Double) jsonObj.get("deltaEE");
            Integer moBlackOut = (Integer) jsonObj.get("moBlackOut");
            String moCutoff = (String) jsonObj.get("moCutoff");
            Double moRecovery = (Double) jsonObj.get("moRecovery");

            DriverConfig.setLogString(
                    "| " + addSpace(startCal, 26) + "| " + addSpace(endcal, 25) + "| "
                            + addSpace(deltaEE.toString(), 11) + "| " + addSpace(moBlackOut.toString(), 14)
                            + "| " + addSpace(moCutoff, 25) + "| " + addSpace(moRecovery.toString(), 12) + "|",
                    true);
            loopVal++;

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    DriverConfig.setLogString(
            "=============================================================================================================================",
            true);
}