Example usage for java.util Formatter Formatter

List of usage examples for java.util Formatter Formatter

Introduction

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

Prototype

public Formatter() 

Source Link

Document

Constructs a new formatter.

Usage

From source file:net.sourceforge.fenixedu.domain.candidacy.PersonalInformationBean.java

public String getFormattedValues() {
    Formatter result = new Formatter();

    final Student student = getStudent();
    result.format("Student Number: %d\n", student.getNumber());
    result.format("Name: %s\n", student.getPerson().getName());
    if (hasPhdIndividualProgramProcess()) {
        result.format("Degree: %s\n", getPhdIndividualProgramProcess().getDisplayName());
    } else {//  ww  w.  ja v  a 2 s.c  om
        result.format("Degree: %s\n", getRegistration().getDegree().getPresentationName());
    }

    return result.toString();
}

From source file:edu.ku.brc.af.ui.forms.formatters.DataObjFieldFormatMgr.java

/**
 * Format a data object using a named formatter
 * @param dataObj the data object for which fields will be formatted for it
 * @return the string result of the format
 *//*from   www  .j  a va  2s  .  c  om*/
protected String formatInternal(final DataObjDataFieldFormatIFace format, final Object dataObj) {
    String restricted = FormHelper.checkForRestrictedValue(dataObj);
    if (restricted != null) {
        return restricted;
    }

    if (format != null) {
        if (format.isDirectFormatter()) {
            return format.format(dataObj);
        }

        DataObjectGettable getter = DataObjectGettableFactory.get(format.getDataClass().getName(),
                FormHelper.DATA_OBJ_GETTER);

        if (getter != null) {
            StringBuilder strBuf = new StringBuilder(128);
            for (DataObjDataField field : format.getFields()) {
                Class<?> fieldClass = field.getType();

                Object[] values = getFieldValues(new String[] { field.getName() }, dataObj, getter);
                Object value = values != null ? values[0] : null;

                // NOTE: if the field was a Date or Calendar object it has already been reformatted to a String
                // so we change the fieldClass to string so everything works out.
                if (fieldClass == Date.class || fieldClass == Calendar.class) {
                    fieldClass = String.class;
                }

                if (value != null) {
                    if (AppContextMgr.isSecurityOn() && value instanceof FormDataObjIFace) {
                        DBTableInfo tblInfo = DBTableIdMgr.getInstance()
                                .getByShortClassName(value.getClass().getSimpleName());
                        if (tblInfo != null) {
                            PermissionSettings perm = tblInfo.getPermissions();
                            if (perm != null) {
                                if (!perm.canView()) {
                                    return "";
                                }
                            }
                        }
                    }

                    if (field.getDataObjFormatterName() != null) {
                        String fmtStr = formatInternal(getDataFormatter(value, field.getDataObjFormatterName()),
                                value);
                        if (fmtStr != null) {
                            strBuf.append(fmtStr);
                        }

                    } else if (field.getUiFieldFormatterName() != null) {
                        UIFieldFormatterIFace fmt = UIFieldFormatterMgr.getInstance()
                                .getFormatter(field.getUiFieldFormatterName());
                        DBTableInfo tblInfo = DBTableIdMgr.getInstance()
                                .getByShortClassName(dataObj.getClass().getSimpleName());
                        if (tblInfo != null) {
                            DBFieldInfo fi = tblInfo.getFieldByName(field.getName());
                            if (fi != null && fi.getFormatter() != null) {
                                fmt = fi.getFormatter();
                            }
                        }

                        if (fmt != null) {
                            strBuf.append(fmt.formatToUI(value));
                        } else {
                            strBuf.append(value);
                        }

                    } else if (value.getClass() == fieldClass) {
                        // When format is null then it is a string
                        if (fieldClass == String.class && (field.getFormat() == null || format.equals("%s"))) {
                            if (field.getSep() != null) {
                                strBuf.append(field.getSep());
                            }
                            strBuf.append(value.toString());
                        } else {
                            String sep = field.getSep();
                            if (sep != null) {
                                strBuf.append(sep);
                            }
                            //log.debug("["+value+"]["+format+"]");
                            if (field.getFormat() != null) {
                                Object[] arg = { value };
                                Formatter formatter = new Formatter();
                                formatter.format(field.getFormat(), arg);
                                strBuf.append(formatter.toString());

                            } else {
                                strBuf.append(value.toString());
                            }
                        }
                    } else {
                        log.error("Mismatch of types data retrieved as class["
                                + (value != null ? value.getClass().getSimpleName() : "N/A")
                                + "] and the format requires ["
                                + (field != null ? (fieldClass != null ? fieldClass.getSimpleName() : "N/A 2")
                                        : "N/A")
                                + "]");
                    }
                }
            }
            return strBuf.toString();
        }
    }
    return "";
}

From source file:org.gumtree.vis.plot1d.KLogarithmicAxis.java

protected List getAllTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) {
    List ticks = new java.util.ArrayList();

    //get lower bound value:
    double lowerBoundVal = getRange().getLowerBound();
    //if small log values and lower bound value too small
    // then set to a small value (don't allow <= 0):
    if (this.smallLogFlag && lowerBoundVal < SMALL_LOG_VALUE) {
        lowerBoundVal = SMALL_LOG_VALUE;
    }/*from  w w  w.ja  v  a  2  s.  c om*/
    //get upper bound value
    double upperBoundVal = getRange().getUpperBound();

    //get log10 version of lower bound and round to integer:
    int iBegCount = (int) Math.rint(switchedLog10(lowerBoundVal));
    //get log10 version of upper bound and round to integer:
    int iEndCount = (int) Math.rint(switchedLog10(upperBoundVal));

    if (iBegCount == iEndCount && iBegCount > 0 && Math.pow(10, iBegCount) > lowerBoundVal) {
        //only 1 power of 10 value, it's > 0 and its resulting
        // tick value will be larger than lower bound of data
        --iBegCount; //decrement to generate more ticks
    }

    int numberOfGrids = 0;
    int numberOfTicks = 0;
    NumberTick lastTick = null;
    double tickVal;
    String tickLabel;
    //        tickVal = lowerBoundVal;
    //        
    //        tickLabel = Long.toString((long) Math.rint(tickVal));
    //        ticks.add(new NumberTick(new Double(tickVal), tickLabel,
    //              TextAnchor.CENTER_RIGHT, TextAnchor.CENTER_RIGHT, 0.0));
    boolean zeroTickFlag = false;
    for (int i = iBegCount; i <= iEndCount; i++) {
        //for each tick with a label to be displayed
        int jEndCount = 10;
        if (i == iEndCount) {
            //                jEndCount = 1;
        }

        for (int j = 0; j < jEndCount; j++) {
            //for each tick to be displayed
            if (this.smallLogFlag) {
                //small log values in use
                tickVal = Math.pow(10, i) + (Math.pow(10, i) * j);
                //first tick of group; create label text
                if (this.log10TickLabelsFlag) {
                    //if flag then
                    tickLabel = "10^" + i; //create "log10"-type label
                } else { //not "log10"-type label
                    if (this.expTickLabelsFlag) {
                        //if flag then
                        tickLabel = "1e" + i; //create "1e#"-type label
                    } else { //not "1e#"-type label
                        if (i >= 0) { // if positive exponent then
                                      // make integer
                            NumberFormat format = getNumberFormatOverride();
                            if (format != null) {
                                tickLabel = format.format(tickVal);
                            } else {
                                tickLabel = Long.toString((long) Math.rint(tickVal));
                            }
                        } else {
                            //negative exponent; create fractional value
                            //set exact number of fractional digits to
                            // be shown:
                            this.numberFormatterObj.setMaximumFractionDigits(-i);
                            //create tick label:
                            tickLabel = this.numberFormatterObj.format(tickVal);
                        }
                    }
                }
            } else { //not small log values in use; allow for values <= 0
                if (zeroTickFlag) { //if did zero tick last iter then
                    --j;
                } //decrement to do 1.0 tick now
                tickVal = (i >= 0) ? Math.pow(10, i) + (Math.pow(10, i) * j)
                        : -(Math.pow(10, -i) - (Math.pow(10, -i - 1) * j));
                if (!zeroTickFlag) { // did not do zero tick last
                                     // iteration
                    if (i > iBegCount && i < iEndCount && Math.abs(tickVal - 1.0) < 0.0001) {
                        // not first or last tick on graph and value
                        // is 1.0
                        tickVal = 0.0; //change value to 0.0
                        zeroTickFlag = true; //indicate zero tick
                        tickLabel = "0"; //create label for tick
                    } else {
                        //first or last tick on graph or value is 1.0
                        //create label for tick:
                        tickLabel = createTickLabel(tickVal, i);
                    }
                } else { // not first tick of group
                    tickLabel = createTickLabel(tickVal, i);
                }
            }

            if (tickVal > upperBoundVal) {
                if (lastTick != null) {
                    String lastTickText = lastTick.getText();
                    if (lastTickText == null || lastTickText.trim().length() == 0) {
                        ticks.remove(lastTick);
                        ticks.add(new NumberTick(lastTick.getValue(),
                                createTickLabel(lastTick.getValue(), i - 1), lastTick.getTextAnchor(),
                                lastTick.getRotationAnchor(), lastTick.getAngle()));
                    }
                }
                if (ticks.size() < 2) {
                    double definition = Math.abs(lowerBoundVal - upperBoundVal);
                    int numberOfDigits = 0;
                    if (definition >= 1)
                        numberOfDigits = 0;
                    else {
                        numberOfDigits = (int) Math.ceil((-Math.log10(definition)));
                    }
                    tickVal = lowerBoundVal;
                    if (definition > 1)
                        tickLabel = Long.toString((long) Math.rint(tickVal));
                    else
                        tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
                    ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.CENTER_RIGHT,
                            TextAnchor.CENTER_RIGHT, 0.0));
                    tickVal = upperBoundVal;
                    if (definition > 1)
                        tickLabel = Long.toString((long) Math.rint(tickVal));
                    else
                        tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
                    ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.CENTER_RIGHT,
                            TextAnchor.CENTER_RIGHT, 0.0));
                }
                return ticks; //if past highest data value then exit method
            }

            if (tickVal >= lowerBoundVal - SMALL_LOG_VALUE) {
                //tick value not below lowest data value
                TextAnchor anchor = null;
                TextAnchor rotationAnchor = null;
                double angle = 0.0;
                if (isVerticalTickLabels()) {
                    if (edge == RectangleEdge.LEFT) {
                        anchor = TextAnchor.BOTTOM_CENTER;
                        rotationAnchor = TextAnchor.BOTTOM_CENTER;
                        angle = -Math.PI / 2.0;
                    } else {
                        anchor = TextAnchor.BOTTOM_CENTER;
                        rotationAnchor = TextAnchor.BOTTOM_CENTER;
                        angle = Math.PI / 2.0;
                    }
                } else {
                    if (edge == RectangleEdge.LEFT) {
                        anchor = TextAnchor.CENTER_RIGHT;
                        rotationAnchor = TextAnchor.CENTER_RIGHT;
                    } else {
                        anchor = TextAnchor.CENTER_LEFT;
                        rotationAnchor = TextAnchor.CENTER_LEFT;
                    }
                }
                //create tick object and add to list:
                lastTick = new NumberTick(new Double(tickVal), tickLabel, anchor, rotationAnchor, angle);
                ticks.add(lastTick);
                if (tickLabel != null && tickLabel.trim().length() > 0)
                    numberOfTicks++;
                numberOfGrids++;
            }
        }
    }
    if (ticks.size() < 2) {
        double definition = Math.abs(lowerBoundVal - upperBoundVal);
        int numberOfDigits = 0;
        if (definition >= 1)
            numberOfDigits = 0;
        else {
            numberOfDigits = (int) Math.ceil((-Math.log10(definition)));
        }
        tickVal = lowerBoundVal;
        if (definition > 1)
            tickLabel = Long.toString((long) Math.rint(tickVal));
        else
            tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
        ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.CENTER_RIGHT,
                TextAnchor.CENTER_RIGHT, 0.0));
        tickVal = upperBoundVal;
        if (definition > 1)
            tickLabel = Long.toString((long) Math.rint(tickVal));
        else
            tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
        ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.CENTER_RIGHT,
                TextAnchor.CENTER_RIGHT, 0.0));
    }
    return ticks;
}

From source file:edu.ku.brc.af.ui.forms.formatters.DataObjFieldFormatMgr.java

/**
 * Format a data object using a named formatter
 * @param dataObj the data object for which fields will be formatted for it
 * @return the string result of the format
 *///w  ww  .  j a  va2 s  .co m
protected String formatInternal(final DataObjDataFieldFormat format, final Object[] dataObjs) {
    if (format != null) {
        DataObjectGettable getter = DataObjectGettableFactory.get(format.getDataClass().getName(),
                FormHelper.DATA_OBJ_GETTER);
        if (getter != null) {
            StringBuilder strBuf = new StringBuilder(128);

            if (dataObjs.length == format.getFields().length) {
                int inx = 0;
                for (DataObjDataField field : format.getFields()) {
                    Object value = dataObjs[inx++];
                    if (value != null) {
                        if (field.getDataObjFormatterName() != null) {
                            String fmtStr = formatInternal(
                                    getDataFormatter(value, field.getDataObjFormatterName()), value);
                            if (fmtStr != null) {
                                strBuf.append(fmtStr);
                            }

                        } else if (field.getUiFieldFormatterName() != null) {
                            UIFieldFormatterIFace fmt = UIFieldFormatterMgr.getInstance()
                                    .getFormatter(field.getUiFieldFormatterName());
                            if (fmt != null) {
                                strBuf.append(fmt.formatToUI(value));
                            } else {
                                strBuf.append(value);
                            }

                        } else if (value.getClass() == field.getType()) {
                            // When format is null then it is a string
                            if (field.getType() == String.class
                                    && (field.getFormat() == null || format.equals("%s"))) {
                                if (field.getSep() != null) {
                                    strBuf.append(field.getSep());
                                }
                                strBuf.append(value.toString());
                            } else {
                                Object[] arg = { value };
                                Formatter formatter = new Formatter();
                                formatter.format(format.getFormat(), arg);
                                strBuf.append(formatter.toString());
                            }
                        } else {
                            log.error("Mismatch of types data retrieved as class["
                                    + value.getClass().getSimpleName() + "] and the format requires ["
                                    + field.getType().getSimpleName() + "]");
                        }
                    }
                }
            } else {
                log.error("Data Array sent to formatter is not the same length [" + dataObjs.length
                        + "] as the formatter [" + format.getFields().length + "]");
            }
            return strBuf.toString();
        }
    }
    return "";
}

From source file:fll.web.scoreEntry.ScoreEntry.java

/**
 * Convert a polynomial to a string. Handles both {@link BasicPolynomial} and
 * {@link ComplexPolynomial}.//from w w  w .j  a  v a2 s .  co  m
 * 
 * @param poly the polynomial
 * @return the string that represents the polynomial
 * @throws ParseException
 */
private static String polyToString(final BasicPolynomial poly) throws ParseException {
    final Formatter formatter = new Formatter();

    boolean first = true;
    for (final Term term : poly.getTerms()) {
        if (!first) {
            formatter.format(" + ");
        } else {
            first = false;
        }

        final double coefficient = term.getCoefficient();

        final Formatter termFormatter = new Formatter();
        termFormatter.format("%f", coefficient);

        for (final GoalRef goalRef : term.getGoals()) {
            final String goal = goalRef.getGoalName();
            final GoalScoreType scoreType = goalRef.getScoreType();
            final String varName;
            switch (scoreType) {
            case RAW:
                varName = getVarNameForRawScore(goal);
                break;
            case COMPUTED:
                varName = getVarNameForComputedScore(goal);
                break;
            default:
                throw new RuntimeException("Expected 'raw' or 'computed', but found: " + scoreType);
            }
            termFormatter.format("* %s", varName);
        }

        for (final VariableRef varRef : term.getVariables()) {
            final String var = varRef.getVariableName();
            final String varName = getComputedGoalLocalVarName(var);
            termFormatter.format("* %s", varName);
        }

        formatter.format("%s", termFormatter.toString());
    }

    final FloatingPointType floatingPoint = poly.getFloatingPoint();
    return applyFloatingPoint(formatter.toString(), floatingPoint);
}

From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java

/**
 * @param hash//  www. j  a  v a 2 s . c  o  m
 * @return
 */
private String byteArray2Hex(byte[] hash) {
    Formatter formatter = new Formatter();
    for (byte b : hash) {
        formatter.format("%02x", b);
    }
    String s = formatter.toString();
    formatter.close();
    return s;
}

From source file:jeplus.JEPlusProject.java

public String[][] getLHSJobList(int LHSsize, Random randomsrc) {

    if (randomsrc == null)
        randomsrc = RandomSource.getRandomGenerator();

    String[][] JobList = new String[LHSsize][];

    // Get all parameters (inc. idf and weather) and their distributions
    if (ParamTree != null) {
        // Create sample for each parameter
        String[][] SampledValues = getSampleInEqualProbSegments(LHSsize, randomsrc);
        // debug/*from w w w.j a va  2s . co  m*/
        logger.debug(Arrays.deepToString(SampledValues));
        //
        int length = SampledValues.length;
        // Shuffle the sample value vector of each parameter
        for (int i = 1; i < length; i++) {
            Collections.shuffle(Arrays.asList(SampledValues[i]), randomsrc);
        }
        // n jobs are created by taking a value from each parameter's vector 
        // sequentially
        for (int i = 0; i < LHSsize; i++) {
            JobList[i] = new String[length];
            JobList[i][0] = new Formatter().format("LHS-%06d", i).toString(); // Job id
            for (int j = 1; j < length; j++) {
                JobList[i][j] = SampledValues[j][i];
            }
        }
        return JobList;
    }
    return null;
}

From source file:fll.scheduler.SchedulerUI.java

/**
 * Load the specified schedule file and select the schedule tab.
 * /*from   w  ww . j  av a2 s. co m*/
 * @param selectedFile
 * @param subjectiveStations if not null, use as the subjective stations,
 *          otherwise prompt the user for the subjective stations
 */
private void loadScheduleFile(final File selectedFile, final List<SubjectiveStation> subjectiveStations) {
    FileInputStream fis = null;
    try {
        final boolean csv = selectedFile.getName().endsWith("csv");
        final CellFileReader reader;
        final String sheetName;
        if (csv) {
            reader = new CSVCellReader(selectedFile);
            sheetName = null;
        } else {
            sheetName = promptForSheetName(selectedFile);
            if (null == sheetName) {
                return;
            }
            fis = new FileInputStream(selectedFile);
            reader = new ExcelCellReader(fis, sheetName);
        }

        final List<SubjectiveStation> newSubjectiveStations;
        if (null == subjectiveStations) {
            final ColumnInformation columnInfo = TournamentSchedule.findColumns(reader,
                    new LinkedList<String>());
            newSubjectiveStations = gatherSubjectiveStationInformation(SchedulerUI.this, columnInfo);
        } else {
            newSubjectiveStations = subjectiveStations;
        }

        if (null != fis) {
            fis.close();
            fis = null;
        }

        mSchedParams = new SchedParams(newSubjectiveStations, SchedParams.DEFAULT_PERFORMANCE_MINUTES,
                SchedParams.MINIMUM_CHANGETIME_MINUTES, SchedParams.MINIMUM_PERFORMANCE_CHANGETIME_MINUTES);
        final List<String> subjectiveHeaders = new LinkedList<String>();
        for (final SubjectiveStation station : newSubjectiveStations) {
            subjectiveHeaders.add(station.getName());
        }

        final String name = Utilities.extractBasename(selectedFile);

        final TournamentSchedule schedule;
        if (csv) {
            schedule = new TournamentSchedule(name, selectedFile, subjectiveHeaders);
        } else {
            fis = new FileInputStream(selectedFile);
            schedule = new TournamentSchedule(name, fis, sheetName, subjectiveHeaders);
        }
        mScheduleFile = selectedFile;
        mScheduleSheetName = sheetName;
        setScheduleData(schedule);

        setTitle(BASE_TITLE + " - " + mScheduleFile.getName() + ":" + mScheduleSheetName);

        mWriteSchedulesAction.setEnabled(true);
        mDisplayGeneralScheduleAction.setEnabled(true);
        mRunOptimizerAction.setEnabled(true);
        mReloadFileAction.setEnabled(true);
        mScheduleFilename.setText(mScheduleFile.getName());

        mTabbedPane.setSelectedIndex(1);
    } catch (final ParseException e) {
        final Formatter errorFormatter = new Formatter();
        errorFormatter.format("Error reading file %s: %s", selectedFile.getAbsolutePath(), e.getMessage());
        LOGGER.error(errorFormatter, e);
        JOptionPane.showMessageDialog(SchedulerUI.this, errorFormatter, "Error reading file",
                JOptionPane.ERROR_MESSAGE);
        return;
    } catch (final IOException e) {
        final Formatter errorFormatter = new Formatter();
        errorFormatter.format("Error reading file %s: %s", selectedFile.getAbsolutePath(), e.getMessage());
        LOGGER.error(errorFormatter, e);
        JOptionPane.showMessageDialog(SchedulerUI.this, errorFormatter, "Error reading file",
                JOptionPane.ERROR_MESSAGE);
        return;
    } catch (final InvalidFormatException e) {
        final Formatter errorFormatter = new Formatter();
        errorFormatter.format("Unknown file format %s: %s", selectedFile.getAbsolutePath(), e.getMessage());
        LOGGER.error(errorFormatter, e);
        JOptionPane.showMessageDialog(SchedulerUI.this, errorFormatter, "Error reading file",
                JOptionPane.ERROR_MESSAGE);
        return;
    } catch (final ScheduleParseException e) {
        final Formatter errorFormatter = new Formatter();
        errorFormatter.format("Error parsing file %s: %s", selectedFile.getAbsolutePath(), e.getMessage());
        LOGGER.error(errorFormatter, e);
        JOptionPane.showMessageDialog(SchedulerUI.this, errorFormatter, "Error parsing file",
                JOptionPane.ERROR_MESSAGE);
        return;
    } catch (final FLLRuntimeException e) {
        final Formatter errorFormatter = new Formatter();
        errorFormatter.format("Error parsing file %s: %s", selectedFile.getAbsolutePath(), e.getMessage());
        LOGGER.error(errorFormatter, e);
        JOptionPane.showMessageDialog(SchedulerUI.this, errorFormatter, "Error parsing file",
                JOptionPane.ERROR_MESSAGE);
        return;
    } finally {
        try {
            if (null != fis) {
                fis.close();
            }
        } catch (final IOException e) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Error closing stream", e);
            }
        }
    }
}

From source file:jeplus.JEPlusProject.java

public String[][] getSobolJobList(int LHSsize, Random randomsrc) {

    if (randomsrc == null)
        randomsrc = RandomSource.getRandomGenerator();

    String[][] JobList = new String[LHSsize][];

    // Get all parameters (inc. idf and weather) and their distributions
    if (ParamTree != null) {
        // Create sample for each parameter
        String[][] SampledValues = getSampleInEqualProbSegments(LHSsize, randomsrc);
        int length = SampledValues.length;
        // Generate Sobol sequence
        SobolSequenceGenerator SSG = new SobolSequenceGenerator(length - 1);
        // SSG.skipTo(1000);
        // Shuffle the sample value vector of each parameter
        //            for (int i=1; i<length; i++) {
        //                Collections.shuffle(Arrays.asList(SampledValues[i]), randomsrc);
        //            }
        // n jobs are created by taking a value from each parameter's vector 
        // sequentially
        for (int i = 0; i < LHSsize; i++) {
            double[] vector = SSG.nextVector();
            JobList[i] = new String[length];
            JobList[i][0] = new Formatter().format("SOBOL-%06d", i).toString(); // Job id
            for (int j = 1; j < length; j++) {
                JobList[i][j] = SampledValues[j][Math.round((float) vector[j - 1] * LHSsize)];
            }/* w  w  w  .j  a  va2s  . c o m*/
        }
        return JobList;
    }
    return null;
}

From source file:com.zimbra.cs.util.ProxyConfOverride.java

@Override
public void update() throws ServiceException, ProxyConfException {
    ArrayList<String> servers = new ArrayList<String>();
    int numFailedHandlers = 0;

    String[] handlerNames = serverSource.getMultiAttr("zimbraReverseProxyAvailableLookupTargets");
    if (handlerNames.length > 0) {
        for (String handlerName : handlerNames) {
            Server s = mProv.getServerByName(handlerName);
            if (s != null) {
                String sn = s.getAttr(Provisioning.A_zimbraServiceHostname, "");
                int port = s.getIntAttr(Provisioning.A_zimbraExtensionBindPort, 7072);
                String proto = "http://";
                int major = s.getIntAttr(Provisioning.A_zimbraServerVersionMajor, 0);
                int minor = s.getIntAttr(Provisioning.A_zimbraServerVersionMinor, 0);
                if ((major == 8 && minor >= 7) || (major > 8)) {
                    proto = "https://";
                }//from w  w w  .  ja  va2 s . c  o m
                boolean isTarget = s.getBooleanAttr(Provisioning.A_zimbraReverseProxyLookupTarget, false);
                if (isTarget) {
                    try {
                        InetAddress ip = ProxyConfUtil.getLookupTargetIPbyIPMode(sn);
                        Formatter f = new Formatter();
                        if (ip instanceof Inet4Address) {
                            f.format("%s%s:%d", proto, ip.getHostAddress(), port);
                        } else {
                            f.format("%s[%s]:%d", proto, ip.getHostAddress(), port);
                        }
                        servers.add(f.toString());
                        f.close();
                        mLog.debug("Route Lookup: Added server " + ip);
                    } catch (ProxyConfException pce) {
                        numFailedHandlers++;
                        mLog.error("Error resolving service host name: '" + sn + "'", pce);
                    }
                }
            } else {
                mLog.warn("Invalid value found in 'zimbraReverseProxyAvailableLookupTargets': " + handlerName
                        + "\nPlease correct and run zmproxyconfgen again");
            }
        }
    } else {
        List<Server> allServers = mProv.getAllServers();

        for (Server s : allServers) {
            String sn = s.getAttr(Provisioning.A_zimbraServiceHostname, "");
            int port = s.getIntAttr(Provisioning.A_zimbraExtensionBindPort, 7072);
            String proto = "http://";
            int major = s.getIntAttr(Provisioning.A_zimbraServerVersionMajor, 0);
            int minor = s.getIntAttr(Provisioning.A_zimbraServerVersionMinor, 0);
            if ((major == 8 && minor >= 7) || (major > 8)) {
                proto = "https://";
            }
            boolean isTarget = s.getBooleanAttr(Provisioning.A_zimbraReverseProxyLookupTarget, false);
            if (isTarget) {
                try {
                    InetAddress ip = ProxyConfUtil.getLookupTargetIPbyIPMode(sn);
                    Formatter f = new Formatter();
                    if (ip instanceof Inet4Address) {
                        f.format("%s%s:%d", proto, ip.getHostAddress(), port);
                    } else {
                        f.format("%s[%s]:%d", proto, ip.getHostAddress(), port);
                    }
                    servers.add(f.toString());
                    f.close();
                    mLog.debug("Route Lookup: Added server " + ip);
                } catch (ProxyConfException pce) {
                    numFailedHandlers++;
                    mLog.error("Error resolving service host name: '" + sn + "'", pce);
                }
            }
        }
    }
    if (servers.isEmpty()) {
        if (numFailedHandlers > 0) {
            throw new ProxyConfException("No available nginx lookup handlers could be contacted");
        } else {
            mLog.warn("No available nginx lookup handlers could be found");
        }
    }
    mValue = servers;
}