List of usage examples for java.util Formatter format
public Formatter format(Locale l, String format, Object... args)
From source file:org.kuali.student.enrollment.class2.scheduleofclasses.service.impl.ScheduleOfClassesViewHelperServiceImpl.java
public String getTermStartEndDate(TermInfo term) { // Return Term as String display like 'FALL 2020 (9/26/2020-12/26/2020)' StringBuilder stringBuilder = new StringBuilder(); Formatter formatter = new Formatter(stringBuilder, Locale.US); String displayString = ""; if (term != null) { String startDate = DateFormatters.MONTH_DAY_YEAR_DATE_FORMATTER.format(term.getStartDate()); String endDate = DateFormatters.MONTH_DAY_YEAR_DATE_FORMATTER.format(term.getEndDate()); formatter.format("%s - %s", startDate, endDate); displayString = stringBuilder.toString(); }// w w w . j av a 2s . c o m return displayString; }
From source file:org.apache.poi.ss.format.CellNumberFormatter.java
private void writeSingleInteger(String fmt, int num, StringBuffer output, List<Special> numSpecials, Set<StringMod> mods) { StringBuffer sb = new StringBuffer(); Formatter formatter = new Formatter(sb); formatter.format(LOCALE, fmt, num); writeInteger(sb, output, numSpecials, mods, false); }
From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java
/** Called when the activity is first created. */ @Override//from w w w. j a va2s .c o m public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); fixScreenOrientation(); DoCommand dc = new DoCommand(getApplication()); Log.i("SUTAgentAndroid", dc.prgVersion); dc.FixDataLocalPermissions(); // Get configuration settings from "ini" file File dir = getFilesDir(); File iniFile = new File(dir, "SUTAgent.ini"); String sIniFile = iniFile.getAbsolutePath(); String lc = dc.GetIniData("General", "LogCommands", sIniFile); if (lc != "" && Integer.parseInt(lc) == 1) { SUTAgentAndroid.LogCommands = true; } SUTAgentAndroid.RegSvrIPAddr = dc.GetIniData("Registration Server", "IPAddr", sIniFile); SUTAgentAndroid.RegSvrIPPort = dc.GetIniData("Registration Server", "PORT", sIniFile); SUTAgentAndroid.HardwareID = dc.GetIniData("Registration Server", "HARDWARE", sIniFile); SUTAgentAndroid.Pool = dc.GetIniData("Registration Server", "POOL", sIniFile); SUTAgentAndroid.sTestRoot = dc.GetIniData("Device", "TestRoot", sIniFile); SUTAgentAndroid.Abi = android.os.Build.CPU_ABI; log(dc, "onCreate"); dc.SetTestRoot(SUTAgentAndroid.sTestRoot); Log.i("SUTAgentAndroid", "Test Root: " + SUTAgentAndroid.sTestRoot); tv = (TextView) this.findViewById(R.id.Textview01); if (getLocalIpAddress() == null) setUpNetwork(sIniFile); String macAddress = "Unknown"; if (android.os.Build.VERSION.SDK_INT > 8) { try { NetworkInterface iface = NetworkInterface .getByInetAddress(InetAddress.getAllByName(getLocalIpAddress())[0]); if (iface != null) { byte[] mac = iface.getHardwareAddress(); if (mac != null) { StringBuilder sb = new StringBuilder(); Formatter f = new Formatter(sb); for (int i = 0; i < mac.length; i++) { f.format("%02x%s", mac[i], (i < mac.length - 1) ? ":" : ""); } macAddress = sUniqueID = sb.toString(); } } } catch (UnknownHostException ex) { } catch (SocketException ex) { } } else { // Fall back to getting info from wifiman on older versions of Android, // which don't support the NetworkInterface interface WifiManager wifiMan = (WifiManager) getSystemService(Context.WIFI_SERVICE); if (wifiMan != null) { WifiInfo wifi = wifiMan.getConnectionInfo(); if (wifi != null) macAddress = wifi.getMacAddress(); if (macAddress != null) sUniqueID = macAddress; } } if (sUniqueID == null) { BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter(); if ((ba != null) && (ba.isEnabled() != true)) { ba.enable(); while (ba.getState() != BluetoothAdapter.STATE_ON) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } sUniqueID = ba.getAddress(); ba.disable(); while (ba.getState() != BluetoothAdapter.STATE_OFF) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } else { if (ba != null) { sUniqueID = ba.getAddress(); sUniqueID.toLowerCase(); } } } if (sUniqueID == null) { TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); if (mTelephonyMgr != null) { sUniqueID = mTelephonyMgr.getDeviceId(); if (sUniqueID == null) { sUniqueID = "0011223344556677"; } } } String hwid = getHWID(this); sLocalIPAddr = getLocalIpAddress(); Toast.makeText(getApplication().getApplicationContext(), "SUTAgent [" + sLocalIPAddr + "] ...", Toast.LENGTH_LONG).show(); String sConfig = dc.prgVersion + lineSep; sConfig += "Test Root: " + sTestRoot + lineSep; sConfig += "Unique ID: " + sUniqueID + lineSep; sConfig += "HWID: " + hwid + lineSep; sConfig += "ABI: " + Abi + lineSep; sConfig += "OS Info" + lineSep; sConfig += "\t" + dc.GetOSInfo() + lineSep; sConfig += "Screen Info" + lineSep; int[] xy = dc.GetScreenXY(); sConfig += "\t Width: " + xy[0] + lineSep; sConfig += "\t Height: " + xy[1] + lineSep; sConfig += "Memory Info" + lineSep; sConfig += "\t" + dc.GetMemoryInfo() + lineSep; sConfig += "Network Info" + lineSep; sConfig += "\tMac Address: " + macAddress + lineSep; sConfig += "\tIP Address: " + sLocalIPAddr + lineSep; displayStatus(sConfig); sRegString = "NAME=" + sUniqueID; sRegString += "&IPADDR=" + sLocalIPAddr; sRegString += "&CMDPORT=" + 20701; sRegString += "&DATAPORT=" + 20700; sRegString += "&OS=Android-" + dc.GetOSInfo(); sRegString += "&SCRNWIDTH=" + xy[0]; sRegString += "&SCRNHEIGHT=" + xy[1]; sRegString += "&BPP=8"; sRegString += "&MEMORY=" + dc.GetMemoryConfig(); sRegString += "&HARDWARE=" + HardwareID; sRegString += "&POOL=" + Pool; sRegString += "&ABI=" + Abi; String sTemp = Uri.encode(sRegString, "=&"); sRegString = "register " + sTemp; pruneCommandLog(dc.GetSystemTime(), dc.GetTestRoot()); if (!bNetworkingStarted) { Thread thread = new Thread(null, doStartService, "StartServiceBkgnd"); thread.start(); bNetworkingStarted = true; Thread thread2 = new Thread(null, doRegisterDevice, "RegisterDeviceBkgnd"); thread2.start(); } monitorBatteryState(); // If we are returning from an update let'em know we're back Thread thread3 = new Thread(null, doUpdateCallback, "UpdateCallbackBkgnd"); thread3.start(); final Button goButton = (Button) findViewById(R.id.Button01); goButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { finish(); } }); }
From source file:ch.entwine.weblounge.kernel.command.SiteCommand.java
/** * Does a search using the terms from the arguments and displays the search * hits on the console./*from w ww . ja va 2 s .co m*/ * * @param site * the site * @param args * search terms */ private void search(Site site, String[] args) { if (args.length == 0) { System.out.println("Please specify a search term"); System.err.println("Usage: site <id> search <terms>"); return; } // Build the search expression // TODO: Use AND? String text = StringUtils.join(args, " "); // Get hold of the content repository ContentRepository repository = site.getContentRepository(); SearchQuery query = new SearchQueryImpl(site); query.withVersion(Resource.LIVE); query.withFulltext(text.toString()); // Is it a page? Formatter formatter = null; try { SearchResult result = repository.find(query); // Format the output formatter = new Formatter(System.out); StringBuffer format = new StringBuffer(); int padding = Long.toString(result.getDocumentCount()).length(); format.append("%1$#").append(padding).append("s. %2$s\n"); // List results int i = 1; for (SearchResultItem item : result.getItems()) { formatter.format(format.toString(), i++, item.getUrl()); } System.out .println("Found " + result.getDocumentCount() + " results (" + result.getSearchTime() + " ms)"); } catch (ContentRepositoryException e) { System.err.println("Error trying to access the content repository"); e.printStackTrace(System.err); } finally { IOUtils.closeQuietly(formatter); } }
From source file:org.apache.poi.ss.format.CellNumberFormatter.java
/** {@inheritDoc} */ public void formatValue(StringBuffer toAppendTo, Object valueObject) { double value = ((Number) valueObject).doubleValue(); value *= scale;//from w ww . j a va 2s.c om // the '-' sign goes at the front, always, so we pick it out boolean negative = value < 0; if (negative) value = -value; // Split out the fractional part if we need to print a fraction double fractional = 0; if (slash != null) { if (improperFraction) { fractional = value; value = 0; } else { fractional = value % 1.0; //noinspection SillyAssignment value = (long) value; } } Set<StringMod> mods = new TreeSet<>(); StringBuffer output = new StringBuffer(desc); if (exponent != null) { writeScientific(value, output, mods); } else if (improperFraction) { writeFraction(value, null, fractional, output, mods); } else { StringBuffer result = new StringBuffer(); Formatter f = new Formatter(result); f.format(LOCALE, printfFmt, value); if (numerator == null) { writeFractional(result, output); writeInteger(result, output, integerSpecials, mods, integerCommas); } else { writeFraction(value, result, fractional, output, mods); } } // Now strip out any remaining '#'s and add any pending text ... ListIterator<Special> it = specials.listIterator(); Iterator<StringMod> changes = mods.iterator(); StringMod nextChange = (changes.hasNext() ? changes.next() : null); int adjust = 0; BitSet deletedChars = new BitSet(); // records chars already deleted while (it.hasNext()) { Special s = it.next(); int adjustedPos = s.pos + adjust; if (!deletedChars.get(s.pos) && output.charAt(adjustedPos) == '#') { output.deleteCharAt(adjustedPos); adjust--; deletedChars.set(s.pos); } while (nextChange != null && s == nextChange.special) { int lenBefore = output.length(); int modPos = s.pos + adjust; int posTweak = 0; switch (nextChange.op) { case StringMod.AFTER: // ignore adding a comma after a deleted char (which was a '#') if (nextChange.toAdd.equals(",") && deletedChars.get(s.pos)) break; posTweak = 1; //noinspection fallthrough case StringMod.BEFORE: output.insert(modPos + posTweak, nextChange.toAdd); break; case StringMod.REPLACE: int delPos = s.pos; // delete starting pos in original coordinates if (!nextChange.startInclusive) { delPos++; modPos++; } // Skip over anything already deleted while (deletedChars.get(delPos)) { delPos++; modPos++; } int delEndPos = nextChange.end.pos; // delete end point in original if (nextChange.endInclusive) delEndPos++; int modEndPos = delEndPos + adjust; // delete end point in current if (modPos < modEndPos) { if (nextChange.toAdd == "") output.delete(modPos, modEndPos); else { char fillCh = nextChange.toAdd.charAt(0); for (int i = modPos; i < modEndPos; i++) output.setCharAt(i, fillCh); } deletedChars.set(delPos, delEndPos); } break; default: throw new IllegalStateException("Unknown op: " + nextChange.op); } adjust += output.length() - lenBefore; if (changes.hasNext()) nextChange = changes.next(); else nextChange = null; } } // Finally, add it to the string if (negative) toAppendTo.append('-'); toAppendTo.append(output); }
From source file:org.efaps.esjp.accounting.util.data.ImportDetails.java
protected List<Document> checkAccounts(final Parameter _parameter, final File _file, final Map<String, Instance> _docMap, final DateTime _date, final Boolean _inverse) throws IOException, EFapsException { final List<Document> ret = new ArrayList<>(); final CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(_file), "UTF-8")); final List<String[]> entries = reader.readAll(); reader.close();/*from w w w . jav a 2 s. c o m*/ entries.remove(0); int i = 1; final Map<String, Document> map = new HashMap<>(); for (final String[] row : entries) { i++; final String docNumber = row[0]; final String ruc = row[1]; final String dateStr = row[2]; final String accountStr = row[5]; final String accountDesc = row[4]; final DecimalFormat formater = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN); formater.setParseBigDecimal(true); final String amountMEStr = row[6]; final String amountMNStr = row[7]; final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.AccountAbstract); queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.Name, accountStr.trim()); final InstanceQuery query = queryBldr.getQuery(); query.executeWithoutAccessCheck(); if (query.next()) { ImportDetails.LOG.info("Found account: '{}' ", accountStr); final String[] docSplit = docNumber.split("-"); if (docSplit.length != 2 && _docMap != null) { ImportDetails.LOG.warn( "Document '{}' - Line: {} has no '-' to distinguish SerialNumber and No.", docNumber, i); } else { try { final Formatter criteria = new Formatter(); String name = docNumber; if (_docMap != null) { final String serialNo = docSplit[0]; final String docNo = docSplit[1]; final int serial = Integer.parseInt(serialNo.trim().replaceAll("\\D", "")); final int no = Integer.parseInt(docNo.trim().replaceAll("\\D", "")); criteria.format("%03d-%06d", serial, no); name = criteria.toString(); } Document doc; if (map.containsKey(name)) { doc = map.get(name); } else { if (_docMap != null && _docMap.containsKey(name)) { doc = new Document(name, _docMap.get(name), ruc, dateStr, accountDesc); } else { doc = new Document(name, null, ruc, dateStr, accountDesc); } } BigDecimal amountME = (BigDecimal) formater.parse(amountMEStr); BigDecimal amountMN = (BigDecimal) formater.parse(amountMNStr); if (_inverse) { amountME = amountME.negate(); amountMN = amountMN.negate(); } if (amountMN.compareTo(BigDecimal.ZERO) >= 0) { doc.addAmountMECredit(amountME); doc.addAmountMNCredit(amountMN); } else { doc.addAmountMEDebit(amountME); doc.addAmountMNDebit(amountMN); } final Map<String, Account> accounts = doc.getAccounts(); Account acc; if (accounts.containsKey(accountStr)) { acc = accounts.get(accountStr); } else { acc = new Account(accountStr, accountDesc); accounts.put(accountStr, acc); } acc.addAmountME(amountME); acc.addAmountMN(amountMN); acc.setInstance(query.getCurrentValue()); map.put(name, doc); criteria.close(); } catch (final NumberFormatException e) { ImportDetails.LOG.error("wrong format for document '{}'", docNumber); } catch (final ParseException e) { ImportDetails.LOG.error("wrong format for amounts '{}' - '{}'", amountMEStr, amountMNStr); } } } else { ImportDetails.LOG.error("Not found account: {}", accountStr); } } final Instance periodInst = getPeriodInstance(); for (final Document doc : map.values()) { final BigDecimal amountCreditMN = doc.getAmountMNCredit() != null ? doc.getAmountMNCredit() : BigDecimal.ZERO; final BigDecimal amountDebitMN = doc.getAmountMNDebit() != null ? doc.getAmountMNDebit() : BigDecimal.ZERO; final BigDecimal amountMN = amountCreditMN.add(amountDebitMN); final BigDecimal amountCreditME = doc.getAmountMECredit() != null ? doc.getAmountMECredit() : BigDecimal.ZERO; final BigDecimal amountDebitME = doc.getAmountMEDebit() != null ? doc.getAmountMEDebit() : BigDecimal.ZERO; final BigDecimal amountME = amountCreditME.add(amountDebitME); if (BigDecimal.ZERO.compareTo(amountMN) == 0 && BigDecimal.ZERO.compareTo(amountME) == 0) { ImportDetails.LOG.info( "For Document: '{}'. Sum of Credit with Debit Amount (ME): '{}' + '{}' and Credit with Debit Amount (MN): '{}' + '{}' are Zero (0)", doc.getName(), amountCreditME, amountDebitME, amountCreditMN, amountDebitMN); } else { ImportDetails.LOG.error( "For Document: '{}'. Sum of Credit with Debit Amount (ME): '{}' + '{}' = '{}' and Credit with Debit Amount (MN): '{}' + '{}' = '{}'", doc.getName(), amountCreditME, amountDebitME, amountME, amountCreditMN, amountDebitMN, amountMN); } final Insert insert = new Insert(CIAccounting.TransactionOpeningBalance); insert.add(CIAccounting.TransactionOpeningBalance.Date, _date); final StringBuilder descBldr = new StringBuilder() .append(doc.getInstance() != null ? doc.getInstance().getType().getLabel() : "Sin Documento") .append(": ").append(doc.getName()).append(" - RUC: ").append(doc.getRuc()).append(" - ") .append(doc.getDate()).append(" - ").append(doc.getDesc()); insert.add(CIAccounting.TransactionOpeningBalance.Description, descBldr.toString()); insert.add(CIAccounting.TransactionOpeningBalance.Status, Status.find(CIAccounting.TransactionStatus.Open)); insert.add(CIAccounting.TransactionOpeningBalance.PeriodLink, periodInst); insert.executeWithoutAccessCheck(); if (_docMap != null) { final Instance instance = insert.getInstance(); new Create().connectDocs2Transaction(_parameter, instance, doc.getInstance()); } final Map<String, Account> accounts = doc.getAccounts(); final Instance basCur = Currency.getBaseCurrency(); for (final Account acc : accounts.values()) { final Insert insertpos = new Insert( acc.getAmountMN().compareTo(BigDecimal.ZERO) > 0 ? CIAccounting.TransactionPositionCredit : CIAccounting.TransactionPositionDebit); insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance()); insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN()); insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur); insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject()); insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME()); insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1); insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance()); insertpos.executeWithoutAccessCheck(); } if (amountCreditMN.compareTo(amountDebitMN.abs()) != 0 && amountCreditMN.subtract(amountDebitMN.abs()).abs().compareTo(new BigDecimal("0.05")) <= 0) { Insert insertpos = null; Account acc = null; if (amountCreditMN.compareTo(amountDebitMN.abs()) > 0) { acc = getRoundingAccount(AccountingSettings.PERIOD_ROUNDINGDEBIT); acc.addAmountMN(amountCreditMN.subtract(amountDebitMN.abs()).negate()); acc.addAmountME(amountCreditME.subtract(amountDebitME.abs()).negate()); insertpos = new Insert(CIAccounting.TransactionPositionDebit); } else { acc = getRoundingAccount(AccountingSettings.PERIOD_ROUNDINGCREDIT); acc.addAmountMN(amountDebitMN.abs().subtract(amountCreditMN)); acc.addAmountME(amountDebitME.abs().subtract(amountCreditME)); insertpos = new Insert(CIAccounting.TransactionPositionCredit); } insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance()); insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN()); insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur); insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject()); insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME()); insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1); insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance()); insertpos.executeWithoutAccessCheck(); } else if (amountCreditMN.compareTo(amountDebitMN.abs()) != 0 && amountCreditMN.subtract(amountDebitMN.abs()).abs().compareTo(new BigDecimal("0.05")) > 0) { Insert insertpos = null; final Account acc = getRoundingAccount(AccountingSettings.PERIOD_TRANSFERACCOUNT); ; if (amountCreditMN.compareTo(amountDebitMN.abs()) > 0) { acc.addAmountMN(amountCreditMN.subtract(amountDebitMN.abs()).negate()); acc.addAmountME(amountCreditME.subtract(amountDebitME.abs()).negate()); insertpos = new Insert(CIAccounting.TransactionPositionDebit); } else { acc.addAmountMN(amountDebitMN.abs().subtract(amountCreditMN)); acc.addAmountME(amountDebitME.abs().subtract(amountCreditME)); insertpos = new Insert(CIAccounting.TransactionPositionCredit); } insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance()); insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN()); insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur); insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject()); insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME()); insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1); insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance()); insertpos.executeWithoutAccessCheck(); } } return ret; }
From source file:fll.scheduler.SchedulerUI.java
/** * Load the specified schedule file and select the schedule tab. * /*from w w w . j a v a 2 s.c o 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:org.kalypso.kalypsomodel1d2d.conv.Control1D2DConverter.java
/** * Writes the Control Data Block of the RMAKalypso controlFile (*.R10) into the PrintWriter *//*from ww w . j a va 2 s .c om*/ private void writeR10ControlDataBlock(final Formatter formatter) throws CoreException, IOException { // This value is not used at all during the steady calculation, // so if user did not selected unsteady, instead of first time step we will take current date/time (see method // getFirstTimeStep()) final Date firstDate = getFirstTimeStep(); final Calendar calendarForFirstTimeStep = Calendar.getInstance(); calendarForFirstTimeStep.setTime(firstDate); /* FILES DATA BLOCK */ formatter.format("OUTFIL %s%s%n", RESULT_DIR_NAME, RESULT_FILE_BASE); //$NON-NLS-1$ formatter.format("INKALYPSmodel.2d%n"); //$NON-NLS-1$ formatter.format("CONTROL A %4d 2d 0%n", m_controlModel.getIaccyc()); //$NON-NLS-1$ if (m_controlModel.getRestart()) formatter.format("RESTART%n"); //$NON-NLS-1$ /* Write W/Q file, even if it is empty. */ formatter.format("STFLFIL %s%n", ISimulation1D2DConstants.BC_WQ_File); //$NON-NLS-1$ /* We always write a building file, even if it is empty. */ formatter.format("INCSTR %s%n", ISimulation1D2DConstants.BUILDING_File); //$NON-NLS-1$ /* We only write a wind field, if we want to consider wind */ if (m_controlModel.getHasWindDrag()) { formatter.format("AWINDIN3%s%n", ISimulation1D2DConstants.WIND_RMA10_File); //$NON-NLS-1$ formatter.format("INSRCORD%s%n", ISimulation1D2DConstants.WIND_RMA10_COORDS_File); //$NON-NLS-1$ } /* We always write a building file, even if it is empty. */ // formatter.format( "INSSTR %s%n", ISimulation1D2DConstants.SURFACE_TRACTTION_File ); //$NON-NLS-1$ formatter.format("ENDFIL%n"); //$NON-NLS-1$ // TODO: @Nico -> hard coded defaults could be got from the schema, how? // default value: 1500 if (m_controlModel.getMFW() != 1500) formatter.format("MAXFRONT %8d%n", m_controlModel.getMFW()); //$NON-NLS-1$ // default value: 10.000.000 if (m_controlModel.getBUFFSIZ() != 20000000) formatter.format("BUFFSIZL%16d%n", m_controlModel.getBUFFSIZ()); //$NON-NLS-1$ /* CONTROL DATA BLOCK */ final String controlModelName = m_controlModel.getName(); final String projectName = controlModelName == null ? Messages.getString("org.kalypso.kalypsomodel1d2d.conv.Control1D2DConverter.8") //$NON-NLS-1$ : controlModelName; formatter.format("TI %30s%n", projectName); //$NON-NLS-1$ // // C0 Double tbfact = 0.0; if (m_controlModel.getIEDSW() == 2 || m_controlModel.getIEDSW() == 13 || m_controlModel.getIEDSW() == 14) { tbfact = m_controlModel.getTBFACT(); } else { tbfact = m_controlModel.getTBFACT_ESCUDIER(); } final Object[] c0Props = new Object[] { 0, m_controlModel.getIDNOPT(), calendarForFirstTimeStep.get(Calendar.YEAR), calendarForFirstTimeStep.get(Calendar.DAY_OF_YEAR), getTimeInPercentage(calendarForFirstTimeStep), m_controlModel.getIEDSW(), tbfact, m_controlModel.getTBMIN(), 1 }; formatter.format("C0%14d%8d%8d%8d%8.2f%8d%8.3f%8.2f%8d%n", c0Props); //$NON-NLS-1$ // C1 formatter.format("C1%14d%8d%8d%8d%8d%8d%8d%8d%8d%n", 0, 1, 0, 0, 0, 0, 0, 0, 1); //$NON-NLS-1$ // C2 // TODO: P_BOTTOM still not implemented, ask Nico formatter.format("C2%14.2f%8.3f%8.1f%8.1f%8.1f%8d%8.2f%n", m_controlModel.getOMEGA(), //$NON-NLS-1$ m_controlModel.getELEV(), 1.0, 1.0, 1.0, 1, m_controlModel.get_P_BOTTOM()); // C3 formatter.format("C3%14.3f%8.3f%8.3f%8.1f%8.3f%8.3f%8.3f%n", 1.0, 1.0, m_controlModel.getUNOM(), //$NON-NLS-1$ m_controlModel.getUDIR(), m_controlModel.getHMIN(), m_controlModel.getDSET(), m_controlModel.getDSETD()); // C4 final boolean artImpulsstromBeiwert = m_controlModel.getBeient(); formatter.format("C4%14.1f%8.1f%8.1f%40d%n", 0.0, 20.0, 0.0, artImpulsstromBeiwert ? 1 : 0); //$NON-NLS-1$ // C5 formatter.format("C5%14d%8d%16d%8d%8d%8d%8d%8d%8d%n", m_controlModel.getNITI(), m_controlModel.getNITN(), //$NON-NLS-1$ m_controlModel.getNCYC(), 0, 0, 1, 0, 1, 1); // C6 if (m_controlModel.getIcpu() != 0) formatter.format("C6%14d%8d%8d%8d%8.5f%8d%n", 0, 0, 0, m_controlModel.getIcpu(), //$NON-NLS-1$ m_controlModel.getHasWindDrag() ? m_controlModel.getChi() : 0.0, m_controlModel.getMarshFrictionDistr()); // C7 formatter.format("C7%14d%8d%8d%n", 0, 0, m_controlModel.getPercentCheck() ? 1 : 0); //$NON-NLS-1$ // CV formatter.format("CV%14.2g%8.2g%8.2g%8.2g%8.2g%16d%8.2f%n", m_controlModel.getCONV_1(), //$NON-NLS-1$ m_controlModel.getCONV_2(), m_controlModel.getCONV_3(), 0.05, 0.05, m_controlModel.getIDRPT(), m_controlModel.getDRFACT()); // IOP line deleted because Nico said that it is an ugly, baaad line... :) // (IOP has something to do with reordering, and this is not working properly with 1D-2D coupling) // formatter.format( "IOP%n" ); // VEGETA if (m_controlModel.getVegeta()) formatter.format("VEGETA%n"); //$NON-NLS-1$ formatter.format("ENERGY%n"); //$NON-NLS-1$ formatter.format("KAL_BC%n"); //$NON-NLS-1$ FormatterUtils.checkIoException(formatter); }
From source file:org.kalypso.kalypsomodel1d2d.conv.Control1D2DConverterSWAN.java
/** * Formats the lines for boundary condition ( Wave boundaries... ). */// w w w. j a v a2s . c om private void formatBoundConds(final Formatter pFormatter, final int pIntContiLineId) throws IOException { for (final IBoundaryCondition boundaryCondition : m_unitBoundaryConditions) { if (boundaryCondition.getTypeByLocation().equals(IBoundaryCondition.PARENT_TYPE_LINE1D2D)) { final IObservation<TupleResult> obs = boundaryCondition.getObservation(); final TupleResult obsResult = obs.getResult(); final IComponent abscissaComponent = TupleResultUtilities.findComponentById(obsResult, Kalypso1D2DDictConstants.DICT_COMPONENT_TIME); final IComponent ordinateComponent = TupleResultUtilities.findComponentById(obsResult, Kalypso1D2DDictConstants.DICT_COMPONENT_WAVE_HSIG); if (abscissaComponent != null && ordinateComponent != null) { IFELine lContiLineAct = null; try { lContiLineAct = m_discretisationModel.findContinuityLine(boundaryCondition.getPosition(), 0.01); } catch (final Exception e) { continue; } if (m_mapContiLinesWithConditions.get(lContiLineAct) != pIntContiLineId) { continue; } if (obsResult.size() == 0 || boundaryCondition.isAbsolute()) { pFormatter.format("BOUN SIDE %d %s\n", pIntContiLineId, //$NON-NLS-1$ boundaryCondition.getStationaryCondition()); return; } final String lStrBoundFileNameAct = ISimulation1D2DConstants.SWAN_BOUNDARY_FILE_PREFIX + pIntContiLineId + ISimulation1D2DConstants.SIM_SWAN_DATA_FILE_EXT; final Formatter lFormatter = getFormatter(lStrBoundFileNameAct); lFormatter.format("TPAR\n"); //$NON-NLS-1$ final IComponent lComponentTime = TupleResultUtilities.findComponentById(obsResult, Kalypso1D2DDictConstants.DICT_COMPONENT_TIME); final IComponent lComponentHsig = TupleResultUtilities.findComponentById(obsResult, Kalypso1D2DDictConstants.DICT_COMPONENT_WAVE_HSIG); final IComponent lComponentPer = TupleResultUtilities.findComponentById(obsResult, Kalypso1D2DDictConstants.DICT_COMPONENT_WAVE_PER); final IComponent lComponentDir = TupleResultUtilities.findComponentById(obsResult, Kalypso1D2DDictConstants.DICT_COMPONENT_WAVE_DIR); final IComponent lComponentDD = TupleResultUtilities.findComponentById(obsResult, Kalypso1D2DDictConstants.DICT_COMPONENT_WAVE_DD); if (lComponentTime == null || lComponentHsig == null) continue; final TupleResultIndex tupleResultIndex = new TupleResultIndex(obsResult, lComponentTime); final Iterator<IRecord> tupleIterator = tupleResultIndex.getIterator(); boolean lBoolWrittenBnd = false; final int lIndexTime = obsResult.indexOfComponent(lComponentTime); final int lIndexHsig = obsResult.indexOfComponent(lComponentHsig); final int lIndexPer = obsResult.indexOfComponent(lComponentPer); final int lIndexDir = obsResult.indexOfComponent(lComponentDir); final int lIndexDD = obsResult.indexOfComponent(lComponentDD); while (tupleIterator.hasNext()) { final IRecord record = tupleIterator.next(); final XMLGregorianCalendar lGregCalendar = (XMLGregorianCalendar) record .getValue(lIndexTime); final Date lDateAct = DateUtilities.toDate(lGregCalendar); if (m_calculatedSteps[0].getTime() <= lDateAct.getTime() && m_calculatedSteps[m_calculatedSteps.length - 1].getTime() >= lDateAct .getTime()) { final String lStrTime = SWANDataConverterHelper .getTimeStringFormatedForSWANInput(lDateAct); final BigDecimal lBDHsig = (BigDecimal) record.getValue(lIndexHsig); final BigDecimal lBDPer = (BigDecimal) record.getValue(lIndexPer); final BigDecimal lBDDir = (BigDecimal) record.getValue(lIndexDir); final BigDecimal lBDDD = (BigDecimal) record.getValue(lIndexDD); lFormatter.format("%s %.2f %.2f %.2f %.2f\n", lStrTime, lBDHsig, lBDPer, lBDDir, lBDDD); //$NON-NLS-1$ lBoolWrittenBnd = true; } } if (lBoolWrittenBnd) { pFormatter.format("BOUN SIDE %d CON FILE '%s'\n$\n", pIntContiLineId, lStrBoundFileNameAct); //$NON-NLS-1$ } else { pFormatter.format("BOUN SIDE %d %s\n$\n", pIntContiLineId, //$NON-NLS-1$ boundaryCondition.getStationaryCondition()); } FormatterUtils.checkIoException(lFormatter); lFormatter.close(); } } FormatterUtils.checkIoException(pFormatter); } }
From source file:com.zimbra.cs.util.ProxyConfOverride.java
@Override public void update() throws ServiceException, ProxyConfException { ArrayList<String> servers = new ArrayList<String>(); /* $(zmprov gamcs) */ List<Server> mcs = mProv.getAllServers(Provisioning.SERVICE_MEMCACHED); for (Server mc : mcs) { String serverName = mc.getAttr(Provisioning.A_zimbraServiceHostname, ""); int serverPort = mc.getIntAttr(Provisioning.A_zimbraMemcachedBindPort, 11211); try {/*from w w w . j a v a2s . c o m*/ InetAddress ip = ProxyConfUtil.getLookupTargetIPbyIPMode(serverName); Formatter f = new Formatter(); if (ip instanceof Inet4Address) { f.format("%s:%d", ip.getHostAddress(), serverPort); } else { f.format("[%s]:%d", ip.getHostAddress(), serverPort); } servers.add(f.toString()); f.close(); } catch (ProxyConfException pce) { mLog.error("Error resolving memcached host name: '" + serverName + "'", pce); } } if (servers.isEmpty()) { throw new ProxyConfException("No available memcached servers could be contacted"); } mValue = servers; }