List of usage examples for java.util Locale setDefault
public static synchronized void setDefault(Locale newLocale)
From source file:de.tudarmstadt.tk.statistics.importer.ExternalResultsReader.java
public static void readLODPipelineTrainTest(String pathToDirectory) { Locale.setDefault(Locale.ENGLISH); String[] semanticFeatures = new String[] { "Baseline", "+ALL", "+LOC", "+TIME", "+LOD", "+LOC+TIME", "+LOC+LOD", "+TIME+LOD", "+TYPES", "+CAT" }; String[] measures = new String[] { "Percent Correct", "Weighted Precision", "Weighted Recall", "Weighted F-Measure" }; String outFileName = "AggregatedCVRandom.csv"; logger.log(Level.INFO, String.format("Importing data from directory %s.", pathToDirectory)); // Method requires input directory. Check this condition. File directory = new File(pathToDirectory); if (!directory.isDirectory()) { System.err.println("Please specify a directory with the source .csv files. Aborting."); return;/*from w w w . j av a 2s . c o m*/ } //Empty previous output file, if there was one File outputFile = new File(directory, outFileName); if (outputFile.exists()) { outputFile.delete(); } try { String header = "Train;Test;Classifier;FeatureSet;Measure;Value"; PrintWriter out = new PrintWriter(new FileWriter(outputFile, true)); out.println(header); out.close(); } catch (IOException e) { System.err.println("Error while writing aggregated Train-Test file."); e.printStackTrace(); } // prepare files lists HashMap<String, ArrayList<File>> filesMap = new HashMap<>(); // read all subdirectories that match the city names File[] subdirs = directory.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY); //Iterate all subdirectories for (File subDirectory : subdirs) { // get train set name String trainSetName = subDirectory.getName(); // iterate all files in directory File[] filesInDirectory = subDirectory.listFiles(); List<File> fileList = Arrays.asList(filesInDirectory); for (File subDirFile : fileList) { // get name of test data set String[] filenameTokens = subDirFile.getName().split("To"); //String testDataName = filenameTokens[1].substring(0, filenameTokens[1].length() - 11); String testDataName; // if only this string is left, then CV if (filenameTokens[1].equals("Results.csv")) { testDataName = trainSetName; } else { testDataName = filenameTokens[1].split("Results.csv")[0]; testDataName = testDataName.split("2C.csv|4C.csv|.csv")[0]; } // put current file to test data name -> this way all files // corresponding to the same test set are in one map if (filesMap.get(testDataName) != null) { // get existing list and add file ArrayList<File> currentFileList = filesMap.get(testDataName); currentFileList.add(subDirFile); } else { // create new list and add current file ArrayList<File> newFileList = new ArrayList<>(); newFileList.add(subDirFile); filesMap.put(testDataName, newFileList); } } ArrayList<String> outputRows = new ArrayList<String>(); int nrDifferentClassifiers = 0; // iterate all files of one map Iterator<Entry<String, ArrayList<File>>> it = filesMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); String testSetName = (String) pairs.getKey(); ArrayList<File> testFiles = (ArrayList<File>) pairs.getValue(); nrDifferentClassifiers = testFiles.size(); // initialize data store ArrayList<HashMap<String, Object>> values = new ArrayList<>(); // get rows for first file to initialize store List<String[]> inputRowsFirstFile = readAndCheckCSV(testFiles.get(0).getAbsolutePath(), ';'); for (int i = 0; i < inputRowsFirstFile.size(); i++) { HashMap<String, Object> currentRowValues = new HashMap<>(); currentRowValues.put("semanticFeature", ""); currentRowValues.put("classifierParameters", ""); currentRowValues.put("aggregatedMeasureValues", new double[measures.length]); currentRowValues.put("nGrams", ""); values.add(currentRowValues); } // get results from other files for (File testFile : testFiles) { // Only analyse files with .csv extension if (!FilenameUtils.getExtension(testFile.getName().toLowerCase()).equals("csv") || testFile.getName().equals("AggregatedTrainTest.csv")) { continue; } // check file for consistency List<String[]> inputRows = readAndCheckCSV(testFile.getAbsolutePath(), ';'); // check if length matches first file if (!(inputRows.size() == values.size())) { // TODO error message } else { for (int i = 0; i < inputRows.size(); i++) { String[] inputCells = inputRows.get(i); // read current values and compare with entries String semanticFeature = semanticFeatures[i % semanticFeatures.length]; if (values.get(i).get("semanticFeature") == "") { values.get(i).put("semanticFeature", semanticFeature); } else { if (values.get(i).get("semanticFeature").equals(semanticFeature) == false) { System.err.println("Semantic Features do not match."); System.exit(1); } } // needs rework as we do aggregation here // String classifierParameters = inputCells[0]; // // if (values.get(i).get("classifierParameters") == // "") // { // values.get(i).put("classifierParameters", // classifierParameters); // } // else // { // if // (values.get(i).get("classifierParameters").equals(classifierParameters) // == false) // { // System.err.println("Classifier parameters do not match."); // System.exit(1); // } // } String nGrams = inputCells[12]; if (values.get(i).get("nGrams") == "") { values.get(i).put("nGrams", nGrams); } else { if (values.get(i).get("nGrams").equals(nGrams) == false) { System.err.println("N Gram Length does not match."); System.exit(1); } } // get and aggregate values for (int j = 0; j < measures.length; j++) { if (j == 0) { //double currentValue = ((double[]) values.get(i).get("aggregatedMeasureValues"))[j]; double valueInFile = Double.parseDouble(inputCells[j + 16]) / 100; ((double[]) values.get(i).get("aggregatedMeasureValues"))[j] += valueInFile; } else { //double currentValue = ((double[]) values.get(i).get("aggregatedMeasureValues"))[j]; double valueInFile = Double.parseDouble(inputCells[j + 16]); ((double[]) values.get(i).get("aggregatedMeasureValues"))[j] += valueInFile; } } } } } // write aggregated results to file for (HashMap<String, Object> currentValues : values) { String semFeature = (String) currentValues.get("semanticFeature"); String nGrams = (String) currentValues.get("nGrams"); String featureSet = String.format("%s, nGrams: %s", semFeature, nGrams); for (int j = 0; j < measures.length; j++) { String outputRow = String.format("%s;%s;%s;%s;%s;%f", trainSetName, testSetName, "0", featureSet, measures[j], ((double[]) currentValues.get("aggregatedMeasureValues"))[j] / nrDifferentClassifiers); outputRows.add(outputRow); } } // avoids a ConcurrentModificationException it.remove(); } // Write aggregated data to a new file try { PrintWriter out = new PrintWriter(new FileWriter(outputFile, true)); for (String s : outputRows) { out.println(s); } out.close(); } catch (IOException e) { System.err.println("Error while writing aggregated Train-Test file."); e.printStackTrace(); } } logger.log(Level.INFO, String.format("Finished import. The aggregated data was written to %s.", outFileName)); }
From source file:ch.itemis.xdocker.ui.view.XdockerImageBrowserView.java
@Override protected void processResult(XdockerJobStatus status) { if (status.isOK() && status.getArgument() instanceof List<?>) { if (isLocal()) { @SuppressWarnings("unchecked") List<Image> images = (List<Image>) status.getArgument(); Locale defLocale = Locale.getDefault(); try { Locale.setDefault(Locale.UK); // we support only English! PrettyTime pt = new PrettyTime(); for (Object obj : images) { Image image = obj instanceof Image ? (Image) obj : null; if (image == null) return; TableItem item = new TableItem(table, SWT.NONE); List<String> elements = new ArrayList<String>(); String tagFragment = image.getRepoTags() != null && image.getRepoTags().length > 0 ? image.getRepoTags()[0] : null;/*from ww w. ja va2s.c o m*/ String[] repoTag = tagFragment != null ? image.getRepoTags()[0].split(":") : null; if (repoTag != null) { if (repoTag.length > 0) elements.add(repoTag[0]); if (repoTag.length > 1) elements.add(repoTag[1]); } if (image.getId() != null && image.getId().length() >= 12) elements.add(image.getId().substring(0, 12)); elements.add(pt.format(new Date(image.getCreated() * 1000))); elements.add(String.valueOf(image.getVirtualSize())); item.setText(elements.toArray(new String[] {})); } } finally { Locale.setDefault(defLocale); // restore to default... } } else { @SuppressWarnings("unchecked") List<SearchItem> images = (List<SearchItem>) status.getArgument(); for (Object obj : images) { SearchItem image = obj instanceof SearchItem ? (SearchItem) obj : null; if (image == null) return; TableItem item = new TableItem(table, SWT.NONE); List<String> elements = new ArrayList<String>(); elements.add(image.getName()); elements.add(image.getDescription()); elements.add(String.valueOf(image.getStarCount())); elements.add(String.valueOf(image.isOfficial())); elements.add(String.valueOf(image.isTrusted())); item.setText(elements.toArray(new String[] {})); } } // resize columns for (int i = 0, n = table.getColumnCount(); i < n; i++) { if (isLocal() || i != 1) { // skip description because could be too long... table.getColumn(i).pack(); } } } }
From source file:facturas.PDF.CommandLineOptions.java
private int parseLanguageOption(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (args[i + 1].charAt(0) == '-')) { throw new FOPException("if you use '-l', you must specify a language"); } else {/*from w ww . j av a 2 s . co m*/ Locale.setDefault(new Locale(args[i + 1], "")); return 1; } }
From source file:com.nec.harvest.controller.PettyCashbookReportController.java
/** * ????PDF?// ww w. j ava2s . c o m * * @param orgCode * String * @param response * HttpServletResponse * @param device * Device * @param model * Model * @param pettyCashBookForm * PettyCashBookForm * @return JSONBean */ @RequestMapping(value = "/area", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody JSONBean getDistrictInformation(@RequestBody final PettyCashBookForm pettyCashBookForm, final HttpServletResponse response, final Device device, final Model model) { if (logger.isDebugEnabled()) { logger.debug("Trying to rendering report..."); } PettyCashBookReport pettyCashBook = null; // ?? try { pettyCashBook = organizationService.findDistrictByShop(pettyCashBookForm.getShopCode()); if (pettyCashBook != null) { logger.info("There is a organization {} in the DB", pettyCashBook.getStrCode()); } } catch (IllegalArgumentException | ObjectNotFoundException ex) { logger.warn(ex.getMessage()); // Ignore this CASE. If the database is not exist then can be showed empty pettyCashBook = new PettyCashBookReport(); } catch (ServiceException ex) { logger.error(ex.getMessage(), ex); // ??????????? return new JSONBean(Boolean.FALSE, -1, getSystemError()); } List<PettyCashbookReportBean> pettyCashBookTmpLst = pettyCashBookForm.getPettyCashbookReportBean(); Map<String, Object> parameterMap = new HashMap<String, Object>(); response.setCharacterEncoding(HttpServletContentType.DEFAULT_ENCODING); // PDF generate UUID final String PDF_UUID = GenerateUUID.randomUUID(); // ??DD/MM/YYYY???? Locale locale = new Locale("en", "EN", "EN"); parameterMap.put(JRParameter.REPORT_LOCALE, locale); // List<PettyCashbookReportBean> pettyCashFlLst = new ArrayList<PettyCashbookReportBean>( pettyCashBookTmpLst.size()); PettyCashbookReportBean ptRptBean; // ?? Map<String, String> grpItem = new HashMap<String, String>(); // ?? Double tmpKingaku = 0.0; // x,xxx??? DecimalFormat formatter = new DecimalFormat("#,###"); for (PettyCashbookReportBean subPtCh : pettyCashBookTmpLst) { if (!grpItem.containsKey(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName()))) { if (StringUtils.isEmpty(subPtCh.getCltAmount())) { grpItem.put(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName()), "0"); } else { // Modified by SONDN 2014-08-22 // Fixing bug CT-005: Allow end user input minus number // grpItem.put(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName()), // formatter.format(Double.valueOf(subPtCh.getCltAmount().replaceAll("[^0-9]", StringUtils.EMPTY)))); grpItem.put(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName()), formatter.format(Double.valueOf(StringUtil.removeCommaChar(subPtCh.getCltAmount())))); } } else { // Modified by SONDN 2014-08-22 // Fixing bug CT-005: Allow end user input minus number // tmpKingaku = Double.valueOf(grpItem.get(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName())).replaceAll("[^0-9]", StringUtils.EMPTY)); // if (!StringUtils.isEmpty(subPtCh.getCltAmount())) { // tmpKingaku = tmpKingaku + Double.valueOf(subPtCh.getCltAmount().replaceAll("[^0-9]", StringUtils.EMPTY)); // } tmpKingaku = Double.valueOf(StringUtil.removeCommaChar( grpItem.get(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName())))); if (!StringUtils.isEmpty(subPtCh.getCltAmount())) { tmpKingaku = tmpKingaku + Double.valueOf(subPtCh.getCltAmount()); } grpItem.put(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName()), formatter.format(tmpKingaku)); } } StringBuilder tmpStrDate; for (PettyCashbookReportBean childPtCh : pettyCashBookTmpLst) { ptRptBean = new PettyCashbookReportBean(); // ptRptBean.setKamokuCode(childPtCh.getCltItemCode()); // ?? String cltItemName = childPtCh.getCltItemName(); if (StringUtils.isNotEmpty(cltItemName)) { ptRptBean.setKamokuName(SPACE_FULL.concat(cltItemName.substring(1))); } else { ptRptBean.setKamokuName(StringUtils.EMPTY); } // ? String cltAmount = childPtCh.getCltAmount(); if (StringUtils.isNotEmpty(cltAmount)) { ptRptBean.setKingaku(formatter.format(Double.valueOf(cltAmount))); } else { ptRptBean.setKingaku(StringUtils.EMPTY); } // ?? ptRptBean.setNaiyou(childPtCh.getCltContent()); ptRptBean.setShito(childPtCh.getCltRemark()); // String cltDate = childPtCh.getCltDate(); if (StringUtils.isNotEmpty(cltDate)) { tmpStrDate = new StringBuilder(cltDate.substring(5)); if (ZERO_CHAR == tmpStrDate.charAt(0)) { tmpStrDate.deleteCharAt(0); } int zeroCharPos = tmpStrDate.length() - 2; if (ZERO_CHAR == tmpStrDate.charAt(zeroCharPos)) { tmpStrDate.deleteCharAt(zeroCharPos); } ptRptBean.setSrDate(tmpStrDate.toString()); } else { ptRptBean.setSrDate(StringUtils.EMPTY); } // ? ptRptBean.setSumPrice(StringUtils.EMPTY); // ptRptBean.setGrpFlg(Boolean.FALSE); ptRptBean.setGrpItemCode(StringUtils.EMPTY); ptRptBean.setGrpItemName(StringUtils.EMPTY); ptRptBean.setGrpCash(StringUtils.EMPTY); ptRptBean.setDetailLine(Boolean.FALSE); pettyCashFlLst.add(ptRptBean); } pettyCashFlLst.get(pettyCashFlLst.size() - 1).setDetailLine(Boolean.FALSE); // ? ptRptBean = new PettyCashbookReportBean(); ptRptBean.setSumPrice(pettyCashBookForm.getVerticalTotal()); ptRptBean.setGrpFlg(Boolean.FALSE); ptRptBean.setDetailLine(Boolean.FALSE); pettyCashFlLst.add(ptRptBean); // ptRptBean = new PettyCashbookReportBean(); ptRptBean.setGrpFlg(Boolean.FALSE); //ptRptBean.setDetailLine(Boolean.TRUE); ptRptBean.setDetailLine(Boolean.FALSE); pettyCashFlLst.add(ptRptBean); // ptRptBean = new PettyCashbookReportBean(); ptRptBean.setGrpFlg(Boolean.TRUE); ptRptBean.setDetailLine(Boolean.TRUE); pettyCashFlLst.add(ptRptBean); // ???? SortedSet<String> grpItemSorted = new TreeSet<String>(grpItem.keySet()); for (String key : grpItemSorted) { ptRptBean = new PettyCashbookReportBean(); ptRptBean.setGrpItemCode(key.split(PDF_UUID)[0]); ptRptBean.setGrpItemName(SPACE_FULL.concat(key.split(PDF_UUID)[1])); ptRptBean.setGrpCash(grpItem.get(key)); ptRptBean.setGrpFlg(Boolean.FALSE); ptRptBean.setDetailLine(Boolean.FALSE); pettyCashFlLst.add(ptRptBean); } JRDataSource JRdataSource = new JRBeanCollectionDataSource(pettyCashFlLst); // ? parameterMap.put("screenTitle", REPORT_TITLE); // try { // ?????? Locale.setDefault(new Locale("ja", "JP", "JP")); Date gregorianDate = new SimpleDateFormat("yyyy", Locale.ENGLISH).parse(pettyCashBookForm.getYear()); SimpleDateFormat format = new SimpleDateFormat("GGGGyyyy"); // String tmpYearOriginal = format.format(gregorianDate); if (tmpYearOriginal.length() > 2) { parameterMap.put("year", tmpYearOriginal.substring(0, tmpYearOriginal.length() - 2)); parameterMap.put("yearName", tmpYearOriginal.substring(tmpYearOriginal.length() - 2)); } else { parameterMap.put("year", StringUtils.EMPTY); parameterMap.put("yearName", StringUtils.EMPTY); // logger.warn("Original year {} is null or empty", tmpYearOriginal); } } catch (ParseException ex) { logger.warn("There is error happend when convert to Japanese's calendar format" + ex.getMessage()); // Reset the locale Locale.setDefault(new Locale("en", "EN", "EN")); } catch (Exception ex) { logger.warn(ex.getMessage()); // Reset the locale Locale.setDefault(new Locale("en", "EN", "EN")); return new JSONBean(Boolean.FALSE, -1, getSystemError()); } // parameterMap.put("month", pettyCashBookForm.getMonth()); parameterMap.put("jRdataSource", JRdataSource); // parameterMap.put("districtCode", pettyCashBook.getStrCode()); // ?? if (pettyCashBook.getStrNameR() != null && !StringUtils.isEmpty(pettyCashBook.getStrNameR())) { parameterMap.put("districtName", pettyCashBook.getStrNameR().length() > 10 ? pettyCashBook.getStrNameR().subSequence(0, 10) : pettyCashBook.getStrNameR()); } else { parameterMap.put("districtName", StringUtils.EMPTY); } // parameterMap.put("shopCode", pettyCashBookForm.getShopCode()); // ?? parameterMap.put("shopName", pettyCashBookForm.getShopName()); // ??? String totalDefault = pettyCashBookForm.getTotalDefault(); parameterMap.put("settingAmount", StringUtils.isNotEmpty(totalDefault) ? totalDefault.substring(1) : StringUtils.EMPTY); // parameterMap.put("Atotal", pettyCashBookForm.getVerticalTotal()); // String balance = pettyCashBookForm.getBalance(); parameterMap.put("Abalance", StringUtils.isNotEmpty(balance) ? balance.substring(1) : StringUtils.EMPTY); Locale.setDefault(new Locale("en", "EN", "EN")); OutputStream output = null; try { JasperDesign jasperDesign = JRXmlLoader.load(getClass().getResourceAsStream(TEMPLATE_PATH)); JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameterMap, JRdataSource); reportToPdfFile = new File( jasperReportResolver.getReportPath() + File.separator + PDF_UUID + PDF_EXTENSION); if (logger.isDebugEnabled()) { logger.debug("Absolute path {}", reportToPdfFile.getAbsolutePath()); } output = new FileOutputStream(reportToPdfFile); // PDF?? JasperExportManager.exportReportToPdfStream(jasperPrint, output); } catch (JRException | IOException ex) { logger.error("PDF file doesn't exist", ex.getMessage()); // PDF???????? return new JSONBean(Boolean.FALSE, -1, "PDF????????"); } finally { try { if (output != null) { output.close(); } } catch (IOException ex) { logger.warn("?????", ex.getMessage()); // ????? return new JSONBean(Boolean.FALSE, -1, "?????"); } } String kindOfDevice = device.isTablet() ? DEVICE_TABLET : DEVICE_DESKTOP; // Successfully created PDF return new JSONBean(Boolean.TRUE, kindOfDevice, PDF_UUID); }
From source file:org.jfree.data.time.WeekTest.java
/** * Some checks for the getStart() method. *//* w ww . j a v a 2 s . c om*/ @Test public void testGetStart() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.ITALY); Calendar cal = Calendar.getInstance(Locale.ITALY); cal.set(2006, Calendar.JANUARY, 16, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Week w = new Week(3, 2006); assertEquals(cal.getTime(), w.getStart()); Locale.setDefault(saved); }
From source file:org.opencastproject.adminui.endpoint.SeriesEndpointTest.java
@BeforeClass public static void oneTimeSetUp() { Locale.setDefault(Locale.ENGLISH); rt.setUpServer(); }
From source file:axiom.main.Server.java
/** * initialize the server/*from w w w .j a va 2 s .com*/ */ public void init() { // set the log factory property String logFactory = sysProps.getProperty("loggerFactory", "axiom.util.Logging"); axiomLogging = "axiom.util.Logging".equals(logFactory); // remove comment below to control Jetty Logging, axiom.util.JettyLogger // is an implemention of the Jetty Log class, used for logging Jetty error messages System.setProperty("org.mortbay.log.class", "axiom.util.JettyLogger"); System.setProperty("org.apache.commons.logging.LogFactory", logFactory); // set the current working directory to the Axiom home dir. // note that this is not a real cwd, which is not supported // by java. It makes sure relative to absolute path name // conversion is done right, so for Axiom code, this should // work. System.setProperty("user.dir", axiomHome.getPath()); // from now on it's safe to call getLogger() because axiomHome is set up getLogger(); String startMessage = "Starting Axiom " + version + " on Java " + System.getProperty("java.version"); logger.info(startMessage); // also print a msg to System.out System.out.println(startMessage); logger.info("Setting Axiom Home to " + axiomHome); RequestLogHandler requestLogHandler = new RequestLogHandler(); handlers.setHandlers(new Handler[] { contexts, new AxiomHandler(), requestLogHandler }); if (this.sysProps.getProperty("enableRequestLog") == null || Boolean.parseBoolean(this.sysProps.getProperty("enableRequestLog"))) { String logDir = sysProps.getProperty("logdir", "log"); String requestLogName = sysProps.getProperty("requestLog", "axiom.server.request.log"); if (!requestLogName.endsWith(".log")) { requestLogName += ".log"; } NCSARequestLog requestLog = new NCSARequestLog(logDir + "/" + requestLogName); requestLog.setRetainDays(90); requestLog.setAppend(true); requestLog.setExtended(true); requestLog.setLogServer(true); requestLog.setLogTimeZone("GMT"); requestLogHandler.setRequestLog(requestLog); } // read db.properties file in Axiom home directory dbProps = new ResourceProperties(); dbProps.setIgnoreCase(false); dbProps.addResource(new FileResource(new File(axiomHome, "db.properties"))); DbSource.setDefaultProps(dbProps); String language = sysProps.getProperty("language"); String country = sysProps.getProperty("country"); String timezone = sysProps.getProperty("timezone"); if ((language != null) && (country != null)) { Locale.setDefault(new Locale(language, country)); } if (timezone != null) { TimeZone.setDefault(TimeZone.getTimeZone(timezone)); } dbSources = new Hashtable(); // try to load the extensions extensions = new Vector<AxiomExtension>(); initExtensions(); // start the default DB TCP Server with SSL enabled try { if (this.isDbHostServer()) { String h2port = this.sysProps.getProperty("db.port", "9092"); String dbhome = this.sysProps.getProperty("dbHome"); File dir; if (dbhome != null) { dir = new File(dbhome); } else { dir = new File(this.axiomHome, "db"); } dir = new File(dir, "TransactionsDB"); String baseDir = dir.getPath(); System.setProperty("h2.lobFilesPerDirectory", new Long(Long.MAX_VALUE).toString()); String[] args = new String[] { "-tcpPort", h2port, "-baseDir", baseDir }; this.defaultDbServer = org.h2.tools.Server.createTcpServer(args).start(); System.out.println("Starting H2 TCP Server on port " + h2port); } } catch (Exception sqle) { logger.error(ErrorReporter.errorMsg(this.getClass(), "init"), sqle); throw new RuntimeException( "FATAL ERROR::Could not start the default " + "H2 database server, " + sqle.getMessage()); } }
From source file:org.jfree.data.time.WeekTest.java
/** * Some checks for the getEnd() method./* ww w . j av a 2 s. co m*/ */ @Test public void testGetEnd() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.ITALY); Calendar cal = Calendar.getInstance(Locale.ITALY); cal.set(2006, Calendar.JANUARY, 8, 23, 59, 59); cal.set(Calendar.MILLISECOND, 999); Week w = new Week(1, 2006); assertEquals(cal.getTime(), w.getEnd()); Locale.setDefault(saved); }
From source file:com.vinexs.eeb.BaseActivity.java
/** * <p>The user should be pointed(through an intent) to the system settings to change it manually. * The application should handle its localization on its own just like described.</p> * <p>It should run in onCreate() method and before setContentView().</p> * <p><font color="red">Don't forget to add android:configChanges="layoutDirection|locale" to * every activity at AndroidManifest.</font></p> */// w ww . j av a 2s. co m public void setCustomSetting() { SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences(this); // Override application original locale. String defaultLocale = Locale.getDefault().toString(); String appLocale = sharePref.getString("locale", defaultLocale); if (!appLocale.isEmpty() && !defaultLocale.equals(appLocale)) { Locale locale; if (appLocale.contains("_")) { String[] localePart = appLocale.split("_"); locale = new Locale(localePart[0], localePart[1]); } else { locale = new Locale(appLocale); } Locale.setDefault(locale); Configuration config = getBaseContext().getResources().getConfiguration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); } // Override application original Theme. Integer appTheme = sharePref.getInt("theme", getBaseContext().getApplicationInfo().theme); currentTheme = appTheme; setTheme(appTheme); }
From source file:org.gtdfree.GTDFree.java
/** * @param args// w w w .ja v a 2 s .c o m */ @SuppressWarnings("static-access") public static void main(final String[] args) { //ApplicationHelper.changeDefaultFontSize(6, "TextField"); //ApplicationHelper.changeDefaultFontSize(6, "TextArea"); //ApplicationHelper.changeDefaultFontSize(6, "Table"); //ApplicationHelper.changeDefaultFontSize(6, "Tree"); //ApplicationHelper.changeDefaultFontStyle(Font.BOLD, "Tree"); final Logger logger = Logger.getLogger(GTDFree.class); logger.setLevel(Level.ALL); BasicConfigurator.configure(); Options op = new Options(); op.addOption("data", true, Messages.getString("GTDFree.Options.data")); //$NON-NLS-1$ //$NON-NLS-2$ op.addOption("eodb", true, Messages.getString("GTDFree.Options.eodb")); //$NON-NLS-1$ //$NON-NLS-2$ op.addOption("exml", true, Messages.getString("GTDFree.Options.exml")); //$NON-NLS-1$ //$NON-NLS-2$ op.addOption("h", "help", false, Messages.getString("GTDFree.Options.help")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ op.addOption("log", true, Messages.getString("GTDFree.Options.log")); //$NON-NLS-1$ //$NON-NLS-2$ Options op2 = new Options(); op2.addOption(OptionBuilder.hasArg().isRequired(false) .withDescription(new MessageFormat(Messages.getString("GTDFree.Options.lang")) //$NON-NLS-1$ .format(new Object[] { "'en'", "'de', 'en'" })) //$NON-NLS-1$ //$NON-NLS-2$ .withArgName("de|en") //$NON-NLS-1$ .withLongOpt("Duser.language") //$NON-NLS-1$ .withValueSeparator('=').create()); op2.addOption(OptionBuilder.hasArg().isRequired(false) .withDescription(new MessageFormat(Messages.getString("GTDFree.Options.laf")).format(new Object[] { //$NON-NLS-1$ "'com.jgoodies.looks.plastic.Plastic3DLookAndFeel', 'com.jgoodies.looks.plastic.PlasticLookAndFeel', 'com.jgoodies.looks.plastic.PlasticXPLookAndFeel', 'com.jgoodies.looks.windows.WindowsLookAndFeel' (only on MS Windows), 'com.sun.java.swing.plaf.gtk.GTKLookAndFeel' (only on Linux with GTK), 'com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel', 'javax.swing.plaf.metal.MetalLookAndFeel'" })) //$NON-NLS-1$ .withLongOpt("Dswing.crossplatformlaf") //$NON-NLS-1$ .withValueSeparator('=').create()); CommandLineParser clp = new GnuParser(); CommandLine cl = null; try { cl = clp.parse(op, args); } catch (ParseException e1) { logger.error("Parse error.", e1); //$NON-NLS-1$ } System.out.print("GTD-Free"); //$NON-NLS-1$ String ver = ""; //$NON-NLS-1$ try { System.out.println(" version " + (ver = ApplicationHelper.getVersion())); //$NON-NLS-1$ } catch (Exception e) { System.out.println(); // ignore } if (true) { // || cl.hasOption("help") || cl.hasOption("h")) { HelpFormatter hf = new HelpFormatter(); hf.printHelp("java [Java options] -jar gtd-free.jar [gtd-free options]" //$NON-NLS-1$ , "[gtd-free options] - " + Messages.getString("GTDFree.Options.appop") //$NON-NLS-1$ //$NON-NLS-2$ , op, "[Java options] - " + new MessageFormat(Messages.getString("GTDFree.Options.javaop")) //$NON-NLS-1$//$NON-NLS-2$ .format(new Object[] { "'-jar'" }) //$NON-NLS-1$ , false); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); hf.setLongOptPrefix("-"); //$NON-NLS-1$ hf.setWidth(88); hf.printOptions(pw, hf.getWidth(), op2, hf.getLeftPadding(), hf.getDescPadding()); String s = sw.getBuffer().toString(); s = s.replaceAll("\\A {3}", ""); //$NON-NLS-1$ //$NON-NLS-2$ s = s.replaceAll("\n {3}", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ s = s.replaceAll(" <", "=<"); //$NON-NLS-1$ //$NON-NLS-2$ System.out.print(s); } String val = cl.getOptionValue("data"); //$NON-NLS-1$ if (val != null) { System.setProperty(ApplicationHelper.DATA_PROPERTY, val); System.setProperty(ApplicationHelper.TITLE_PROPERTY, "1"); //$NON-NLS-1$ } else { System.setProperty(ApplicationHelper.TITLE_PROPERTY, "0"); //$NON-NLS-1$ } val = cl.getOptionValue("log"); //$NON-NLS-1$ if (val != null) { Level l = Level.toLevel(val, Level.ALL); logger.setLevel(l); } if (!ApplicationHelper.tryLock(null)) { System.out.println("Instance of GTD-Free already running, pushing it to be visible..."); //$NON-NLS-1$ remotePushVisible(); System.out.println("Instance of GTD-Free already running, exiting."); //$NON-NLS-1$ System.exit(0); } if (!"OFF".equalsIgnoreCase(val)) { //$NON-NLS-1$ RollingFileAppender f = null; try { f = new RollingFileAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN), ApplicationHelper.getLogFileName(), true); f.setMaxBackupIndex(3); BasicConfigurator.configure(f); f.rollOver(); } catch (IOException e2) { logger.error("Logging error.", e2); //$NON-NLS-1$ } } logger.info("GTD-Free " + ver + " started."); //$NON-NLS-1$ //$NON-NLS-2$ logger.debug("Args: " + Arrays.toString(args)); //$NON-NLS-1$ logger.info("Using data in: " + ApplicationHelper.getDataFolder()); //$NON-NLS-1$ if (cl.getOptionValue("exml") != null || cl.getOptionValue("eodb") != null) { //$NON-NLS-1$ //$NON-NLS-2$ GTDFreeEngine engine = null; try { engine = new GTDFreeEngine(); } catch (Exception e1) { logger.fatal("Fatal error, exiting.", e1); //$NON-NLS-1$ } val = cl.getOptionValue("exml"); //$NON-NLS-1$ if (val != null) { File f1 = new File(val); if (f1.isDirectory()) { f1 = new File(f1, "gtd-free-" + ApplicationHelper.formatLongISO(new Date()) + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$ } try { f1.getParentFile().mkdirs(); } catch (Exception e) { logger.error("Export error.", e); //$NON-NLS-1$ } try { engine.getGTDModel().exportXML(f1); logger.info("Data successfully exported as XML to " + f1.toString()); //$NON-NLS-1$ } catch (Exception e) { logger.error("Export error.", e); //$NON-NLS-1$ } } val = cl.getOptionValue("eodb"); //$NON-NLS-1$ if (val != null) { File f1 = new File(val); if (f1.isDirectory()) { f1 = new File(f1, "gtd-free-" + ApplicationHelper.formatLongISO(new Date()) + ".odb-xml"); //$NON-NLS-1$ //$NON-NLS-2$ } try { f1.getParentFile().mkdirs(); } catch (Exception e) { logger.error("Export error.", e); //$NON-NLS-1$ } try { GTDData data = engine.getGTDModel().getDataRepository(); if (data instanceof GTDDataODB) { try { ((GTDDataODB) data).exportODB(f1); } catch (Exception e) { logger.error("Export error.", e); //$NON-NLS-1$ } logger.info("Data successfully exported as ODB to " + f1.toString()); //$NON-NLS-1$ } else { logger.info("Data is not stored in ODB database, nothing is exported."); //$NON-NLS-1$ } } catch (Exception e) { logger.error("Export error.", e); //$NON-NLS-1$ } } try { engine.close(true, false); } catch (Exception e) { logger.error("Internal error.", e); //$NON-NLS-1$ } return; } logger.debug("Using OS '" + System.getProperty("os.name") + "', '" + System.getProperty("os.version") //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$ + "', '" + System.getProperty("os.arch") + "'."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ logger.debug("Using Java '" + System.getProperty("java.runtime.name") + "' version '" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + System.getProperty("java.runtime.version") + "'."); //$NON-NLS-1$ //$NON-NLS-2$ Locale[] supported = { Locale.ENGLISH, Locale.GERMAN }; String def = Locale.getDefault().getLanguage(); boolean toSet = true; for (Locale locale : supported) { toSet &= !locale.getLanguage().equals(def); } if (toSet) { logger.debug("System locale '" + def + "' not supported, setting to '" + Locale.ENGLISH.getLanguage() //$NON-NLS-1$//$NON-NLS-2$ + "'."); //$NON-NLS-1$ try { Locale.setDefault(Locale.ENGLISH); } catch (Exception e) { logger.warn("Setting default locale failed.", e); //$NON-NLS-1$ } } else { logger.debug("Using locale '" + Locale.getDefault().toString() + "'."); //$NON-NLS-1$ //$NON-NLS-2$ } try { //System.setProperty("swing.crossplatformlaf", "com.jgoodies.looks.plastic.PlasticXPLookAndFeel"); //System.setProperty("swing.crossplatformlaf", "com.jgoodies.looks.plastic.Plastic3DLookAndFeel"); //System.setProperty("swing.crossplatformlaf", "com.jgoodies.looks.plastic.PlasticLookAndFeel"); //System.setProperty("swing.crossplatformlaf", "javax.swing.plaf.metal.MetalLookAndFeel"); //System.setProperty("swing.crossplatformlaf", "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); if (System.getProperty("swing.crossplatformlaf") == null) { //$NON-NLS-1$ String osName = System.getProperty("os.name"); //$NON-NLS-1$ if (osName != null && osName.toLowerCase().indexOf("windows") != -1) { //$NON-NLS-1$ UIManager.setLookAndFeel("com.jgoodies.looks.windows.WindowsLookAndFeel"); //$NON-NLS-1$ } else { try { // we prefer to use native L&F, many systems support GTK, even if Java thinks it is not supported UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); //$NON-NLS-1$ } catch (Throwable e) { logger.debug("GTK L&F not supported.", e); //$NON-NLS-1$ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } } } } catch (Throwable e) { logger.warn("Setting L&F failed.", e); //$NON-NLS-1$ } logger.debug("Using L&F '" + UIManager.getLookAndFeel().getName() + "' by " //$NON-NLS-1$//$NON-NLS-2$ + UIManager.getLookAndFeel().getClass().getName()); try { final GTDFree application = new GTDFree(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { application.getJFrame(); application.restore(); //application.getJFrame().setVisible(true); application.pushVisible(); ApplicationHelper.executeInBackground(new Runnable() { @Override public void run() { if (SystemTray.isSupported() && application.getEngine().getGlobalProperties() .getBoolean(GlobalProperties.SHOW_TRAY_ICON, false)) { try { SystemTray.getSystemTray().add(application.getTrayIcon()); } catch (AWTException e) { logger.error("Failed to activate system tray icon.", e); //$NON-NLS-1$ } } } }); ApplicationHelper.executeInBackground(new Runnable() { @Override public void run() { application.exportRemote(); } }); if (application.getEngine().getGlobalProperties() .getBoolean(GlobalProperties.CHECK_FOR_UPDATE_AT_START, true)) { ApplicationHelper.executeInBackground(new Runnable() { @Override public void run() { application.checkForUpdates(false); } }); } } catch (Throwable t) { t.printStackTrace(); logger.fatal("Failed to start application, exiting.", t); //$NON-NLS-1$ if (application != null) { application.close(true); } System.exit(0); } } }); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { application.close(true); } catch (Exception e) { logger.warn("Failed to stop application.", e); //$NON-NLS-1$ } logger.info("Closed."); //$NON-NLS-1$ ApplicationHelper.releaseLock(); LogManager.shutdown(); } }); } catch (Throwable t) { logger.fatal("Initialization failed, exiting.", t); //$NON-NLS-1$ t.printStackTrace(); System.exit(0); } }