List of usage examples for java.io OutputStreamWriter append
@Override public Writer append(CharSequence csq) throws IOException
From source file:dev.ukanth.ufirewall.Api.java
public static boolean saveSharedPreferencesToFile(Context ctx) { boolean res = false; File sdCard = Environment.getExternalStorageDirectory(); if (isExternalStorageWritable()) { File dir = new File(sdCard.getAbsolutePath() + "/afwall/"); dir.mkdirs();/* w ww. j ava2 s . c o m*/ File file = new File(dir, "backup.json"); try { FileOutputStream fOut = new FileOutputStream(file); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); //default Profile - current one JSONObject obj = new JSONObject(getCurrentRulesAsMap(ctx)); JSONArray jArray = new JSONArray("[" + obj.toString() + "]"); myOutWriter.append(jArray.toString()); res = true; myOutWriter.close(); fOut.close(); } catch (FileNotFoundException e) { Log.e(TAG, e.getLocalizedMessage()); } catch (JSONException e) { Log.e(TAG, e.getLocalizedMessage()); } catch (IOException e) { Log.e(TAG, e.getLocalizedMessage()); } } return res; }
From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java
@Override public InputStream setChanges(final InputStream toBeChanged, final Map<String, InputStream> properties) throws Exception { XMLEventReader reader = getEventReader(toBeChanged); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLOutputFactory xof = XMLOutputFactory.newInstance(); XMLEventWriter writer = xof.createXMLEventWriter(bos); // --------------------------------- // add property changes // --------------------------------- Map.Entry<Integer, XmlElement> propertyElement = getAtomElement(reader, writer, PROPERTIES, null, 0, 2, 3, false);/*from w w w .j av a 2 s . com*/ writer.flush(); ByteArrayOutputStream pbos = new ByteArrayOutputStream(); OutputStreamWriter pwriter = new OutputStreamWriter(pbos); final XMLEventReader propertyReader = propertyElement.getValue().getContentReader(); try { while (true) { final XmlElement property = getAtomElement(propertyReader, null, null); final String name = property.getStart().getName().getLocalPart(); if (properties.containsKey(name)) { // replace final InputStream replacement = properties.get(name); properties.remove(property.getStart().getName().getLocalPart()); pwriter.append(IOUtils.toString(replacement)); IOUtils.closeQuietly(replacement); } else { pwriter.append(IOUtils.toString(property.toStream())); } } } catch (Exception ignore) { // end } for (Map.Entry<String, InputStream> remains : properties.entrySet()) { if (!remains.getKey().startsWith("[LINK]")) { pwriter.append(IOUtils.toString(remains.getValue())); IOUtils.closeQuietly(remains.getValue()); } } pwriter.flush(); pwriter.close(); writer.add(propertyElement.getValue().getStart()); writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray()))); writer.add(propertyElement.getValue().getEnd()); IOUtils.closeQuietly(pbos); writer.add(reader); reader.close(); writer.flush(); writer.close(); // --------------------------------- // --------------------------------- // add navigationm changes // --------------------------------- // remove existent links for (Map.Entry<String, InputStream> remains : properties.entrySet()) { if (remains.getKey().startsWith("[LINK]")) { reader = getEventReader(new ByteArrayInputStream(bos.toByteArray())); bos.reset(); writer = xof.createXMLEventWriter(bos); try { final String linkName = remains.getKey().substring(remains.getKey().indexOf("]") + 1); getAtomElement(reader, writer, LINK, Collections.<Map.Entry<String, String>>singleton( new SimpleEntry<String, String>("title", linkName)), 0, 2, 2, false); writer.add(reader); } catch (Exception ignore) { // ignore } writer.flush(); writer.close(); } } reader = getEventReader(new ByteArrayInputStream(bos.toByteArray())); bos.reset(); writer = xof.createXMLEventWriter(bos); propertyElement = getAtomElement(reader, writer, CONTENT, null, 0, 2, 2, false); writer.flush(); pbos.reset(); pwriter = new OutputStreamWriter(pbos); for (Map.Entry<String, InputStream> remains : properties.entrySet()) { if (remains.getKey().startsWith("[LINK]")) { pwriter.append(IOUtils.toString(remains.getValue())); IOUtils.closeQuietly(remains.getValue()); } } pwriter.flush(); pwriter.close(); writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray()))); IOUtils.closeQuietly(pbos); writer.add(propertyElement.getValue().getStart()); writer.add(propertyElement.getValue().getContentReader()); writer.add(propertyElement.getValue().getEnd()); writer.add(reader); reader.close(); writer.flush(); writer.close(); // --------------------------------- return new ByteArrayInputStream(bos.toByteArray()); }
From source file:org.opendatakit.briefcase.util.ExportToCsv.java
private boolean processInstance(File instanceDir) { File submission = new File(instanceDir, "submission.xml"); if (!submission.exists() || !submission.isFile()) { EventBus.publish(new ExportProgressEvent( "Submission not found for instance directory: " + instanceDir.getPath())); return false; }/*from w w w.j a v a 2 s.c o m*/ EventBus.publish(new ExportProgressEvent("Processing instance: " + instanceDir.getName())); // If we are encrypted, be sure the temporary directory // that will hold the unencrypted files is created and empty. // If we aren't encrypted, the temporary directory // is the same as the instance directory. File unEncryptedDir; if (briefcaseLfd.isFileEncryptedForm()) { // create or clean-up the temp directory that will hold the unencrypted // files. Do this in the outputDir so that the briefcase storage location // can be a read-only network mount. issue 676. unEncryptedDir = new File(outputDir, ".temp"); if (unEncryptedDir.exists()) { // silently delete it... try { FileUtils.deleteDirectory(unEncryptedDir); } catch (IOException e) { e.printStackTrace(); EventBus.publish(new ExportProgressEvent( "Unable to delete stale temp directory: " + unEncryptedDir.getAbsolutePath())); return false; } } if (!unEncryptedDir.mkdirs()) { EventBus.publish(new ExportProgressEvent( "Unable to create temp directory: " + unEncryptedDir.getAbsolutePath())); return false; } } else { unEncryptedDir = instanceDir; } // parse the xml document (this is the manifest if encrypted)... Document doc; boolean isValidated = false; try { doc = XmlManipulationUtils.parseXml(submission); } catch (ParsingException e) { e.printStackTrace(); EventBus.publish(new ExportProgressEvent( "Error parsing submission " + instanceDir.getName() + " Cause: " + e.toString())); return false; } catch (FileSystemException e) { e.printStackTrace(); EventBus.publish(new ExportProgressEvent( "Error parsing submission " + instanceDir.getName() + " Cause: " + e.toString())); return false; } String submissionDate = null; // extract the submissionDate, if present, from the attributes // of the root element of the submission or submission manifest (if encrypted). submissionDate = doc.getRootElement().getAttributeValue(null, "submissionDate"); if (submissionDate == null || submissionDate.length() == 0) { submissionDate = null; } else { Date theDate = WebUtils.parseDate(submissionDate); DateFormat formatter = DateFormat.getDateTimeInstance(); submissionDate = formatter.format(theDate); // just return true to skip records out of range if (startDate != null && theDate.before(startDate)) { log.info("Submission date is before specified, skipping: " + instanceDir.getName()); return true; } if (endDate != null && theDate.after(endDate)) { log.info("Submission date is after specified, skipping: " + instanceDir.getName()); return true; } // don't export records without dates if either date is set if ((startDate != null || endDate != null) && submissionDate == null) { log.info("No submission date found, skipping: " + instanceDir.getName()); return true; } } // Beyond this point, we need to have a finally block that // will clean up any decrypted files whenever there is any // failure. try { if (briefcaseLfd.isFileEncryptedForm()) { // Decrypt the form and all its media files into the // unEncryptedDir and validate the contents of all // those files. // NOTE: this changes the value of 'doc' try { FileSystemUtils.DecryptOutcome outcome = FileSystemUtils.decryptAndValidateSubmission(doc, briefcaseLfd.getPrivateKey(), instanceDir, unEncryptedDir); doc = outcome.submission; isValidated = outcome.isValidated; } catch (ParsingException e) { e.printStackTrace(); EventBus.publish(new ExportProgressEvent( "Error decrypting submission " + instanceDir.getName() + " Cause: " + e.toString())); return false; } catch (FileSystemException e) { e.printStackTrace(); EventBus.publish(new ExportProgressEvent( "Error decrypting submission " + instanceDir.getName() + " Cause: " + e.toString())); return false; } catch (CryptoException e) { e.printStackTrace(); EventBus.publish(new ExportProgressEvent( "Error decrypting submission " + instanceDir.getName() + " Cause: " + e.toString())); return false; } } String instanceId = null; String base64EncryptedFieldKey = null; // find an instanceId to use... try { FormInstanceMetadata sim = XmlManipulationUtils.getFormInstanceMetadata(doc.getRootElement()); instanceId = sim.instanceId; base64EncryptedFieldKey = sim.base64EncryptedFieldKey; } catch (ParsingException e) { e.printStackTrace(); EventBus.publish(new ExportProgressEvent("Could not extract metadata from submission: " + submission.getAbsolutePath() + " Cause: " + e.toString())); return false; } if (instanceId == null || instanceId.length() == 0) { // if we have no instanceID, and there isn't any in the file, // use the checksum as the id. // NOTE: encrypted submissions always have instanceIDs. // This is for legacy non-OpenRosa forms. long checksum; try { checksum = FileUtils.checksumCRC32(submission); } catch (IOException e1) { e1.printStackTrace(); EventBus.publish(new ExportProgressEvent("Failed during computing of crc: " + e1.getMessage())); return false; } instanceId = "crc32:" + Long.toString(checksum); } if (terminationFuture.isCancelled()) { EventBus.publish(new ExportProgressEvent("ABORTED")); return false; } EncryptionInformation ei = null; if (base64EncryptedFieldKey != null) { try { ei = new EncryptionInformation(base64EncryptedFieldKey, instanceId, briefcaseLfd.getPrivateKey()); } catch (CryptoException e) { e.printStackTrace(); EventBus.publish(new ExportProgressEvent("Error establishing field decryption for submission " + instanceDir.getName() + " Cause: " + e.toString())); return false; } } // emit the csv record... try { OutputStreamWriter osw = fileMap.get(briefcaseLfd.getSubmissionElement()); emitString(osw, true, submissionDate); emitSubmissionCsv(osw, ei, doc.getRootElement(), briefcaseLfd.getSubmissionElement(), briefcaseLfd.getSubmissionElement(), false, instanceId, unEncryptedDir); emitString(osw, false, instanceId); if (briefcaseLfd.isFileEncryptedForm()) { emitString(osw, false, Boolean.toString(isValidated)); if (!isValidated) { EventBus.publish(new ExportProgressEvent("Decrypted submission " + instanceDir.getName() + " may be missing attachments and could not be validated.")); } } osw.append("\n"); return true; } catch (IOException e) { e.printStackTrace(); EventBus.publish(new ExportProgressEvent("Failed writing csv: " + e.getMessage())); return false; } } finally { if (briefcaseLfd.isFileEncryptedForm()) { // destroy the temp directory and its contents... try { FileUtils.deleteDirectory(unEncryptedDir); } catch (IOException e) { e.printStackTrace(); EventBus.publish( new ExportProgressEvent("Unable to remove decrypted files: " + e.getMessage())); return false; } } } }
From source file:org.apache.olingo.fit.utils.AbstractXMLUtilities.java
@Override public InputStream setChanges(final InputStream toBeChanged, final Map<String, InputStream> properties) throws Exception { XMLEventReader reader = getEventReader(toBeChanged); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); XMLEventWriter writer = getEventWriter(bos); // --------------------------------- // add property changes // --------------------------------- Map.Entry<Integer, XmlElement> propertyElement = extractElement(reader, writer, Collections.<String>singletonList(PROPERTIES), 0, 2, 3); writer.flush();//from www. ja va2s . co m ByteArrayOutputStream pbos = new ByteArrayOutputStream(); OutputStreamWriter pwriter = new OutputStreamWriter(pbos); final XMLEventReader propertyReader = propertyElement.getValue().getContentReader(); try { while (true) { final XmlElement property = extractElement(propertyReader, null, null, 0, -1, -1).getValue(); final String name = property.getStart().getName().getLocalPart(); if (properties.containsKey(name)) { // replace final InputStream replacement = properties.get(name); properties.remove(property.getStart().getName().getLocalPart()); pwriter.append(IOUtils.toString(replacement)); IOUtils.closeQuietly(replacement); } else { pwriter.append(IOUtils.toString(property.toStream())); } } } catch (Exception ignore) { // end } for (Map.Entry<String, InputStream> remains : properties.entrySet()) { if (!remains.getKey().startsWith("[LINK]")) { pwriter.append(IOUtils.toString(remains.getValue())); IOUtils.closeQuietly(remains.getValue()); } } pwriter.flush(); pwriter.close(); writer.add(propertyElement.getValue().getStart()); writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray()))); writer.add(propertyElement.getValue().getEnd()); IOUtils.closeQuietly(pbos); writer.add(reader); reader.close(); writer.flush(); writer.close(); // --------------------------------- // --------------------------------- // add navigationm changes // --------------------------------- // remove existent links for (Map.Entry<String, InputStream> remains : properties.entrySet()) { if (remains.getKey().startsWith("[LINK]")) { reader = getEventReader(new ByteArrayInputStream(bos.toByteArray())); bos.reset(); writer = getEventWriter(bos); try { final String linkName = remains.getKey().substring(remains.getKey().indexOf("]") + 1); extractElement(reader, writer, Collections.<String>singletonList(LINK), Collections.<Map.Entry<String, String>>singleton( new SimpleEntry<String, String>("title", linkName)), false, 0, 2, 2); writer.add(reader); } catch (Exception ignore) { // ignore } writer.flush(); writer.close(); } } reader = getEventReader(new ByteArrayInputStream(bos.toByteArray())); bos.reset(); writer = getEventWriter(bos); propertyElement = extractElement(reader, writer, Collections.<String>singletonList(CONTENT), 0, 2, 2); writer.flush(); pbos.reset(); pwriter = new OutputStreamWriter(pbos); for (Map.Entry<String, InputStream> remains : properties.entrySet()) { if (remains.getKey().startsWith("[LINK]")) { pwriter.append(IOUtils.toString(remains.getValue())); IOUtils.closeQuietly(remains.getValue()); } } pwriter.flush(); pwriter.close(); writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray()))); IOUtils.closeQuietly(pbos); writer.add(propertyElement.getValue().getStart()); writer.add(propertyElement.getValue().getContentReader()); writer.add(propertyElement.getValue().getEnd()); writer.add(reader); reader.close(); writer.flush(); writer.close(); // --------------------------------- return new ByteArrayInputStream(bos.toByteArray()); }
From source file:com.ibm.bi.dml.test.utils.TestUtils.java
public static String processMultiPartCSVForR(String csvFile) throws IOException { File csv = new File(csvFile); if (csv.isDirectory()) { File[] parts = csv.listFiles(); int count = 0; int index = -1; for (int i = 0; i < parts.length; i++) { File f = parts[i];//from w w w . j a va 2 s . c om String path = f.getPath(); if (path.startsWith(".") && path.endsWith(".crc")) continue; count++; index = i; } if (count == 1) { csvFile = parts[index].toString(); } else if (count > 1) { File tmp = new File(csvFile + "_temp.csv"); OutputStreamWriter out = null; try { out = new OutputStreamWriter(new FileOutputStream(tmp), "UTF-8"); // Directory listing may contain .crc files or may be in the // wrong order. Sanitize the list of names. ArrayList<String> partNames = new ArrayList<String>(); for (File part : parts) { String partName = part.getName(); if (false == partName.endsWith(".crc")) { partNames.add(partName); } } Collections.sort(partNames); for (String name : partNames) { File part = new File(csv, name); // Assume that each file fits into memory. String fileContents = FileUtils.readFileToString(part, "UTF-8"); out.append(fileContents); } } finally { if (null != out) out.close(); } csvFile = tmp.getCanonicalPath(); } else { throw new RuntimeException("Unexpected error while reading a CSV file in R: " + count); } } return csvFile; }
From source file:com.ezac.gliderlogs.FlightOverviewActivity.java
@SuppressLint("SimpleDateFormat") public void GliderLogToCSV(String DB, String device_id) { // format date's SimpleDateFormat CSV = new SimpleDateFormat("yyyyMMdd_kkss"); SimpleDateFormat DIR = new SimpleDateFormat("yyyy/MM_dd"); Date myDate = new Date(); String TS_DB = CSV.format(myDate); String TS_DIR = DIR.format(myDate); // to internal sdcard File dir = new File(Environment.getExternalStorageDirectory() + "/Download/" + TS_DIR); if (!dir.exists() || !dir.isDirectory()) { dir.mkdir();//from www . ja va 2 s .c o m } File myFile = new File(Environment.getExternalStorageDirectory() + "/Download/" + TS_DIR + "/" + device_id.toUpperCase(Locale.US) + "_" + TS_DB + ".csv"); try { myFile.createNewFile(); FileOutputStream fOut = new FileOutputStream(myFile); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); myOutWriter.append( "datum;start;landing;duur;soort;registratie;piloot;piloot_id;tweede;tweede_id;instructie;opmerking;methode"); myOutWriter.append("\n"); Uri uri = FlightsContentProvider.CONTENT_URI_FLIGHT; String[] projection = { GliderLogTables.F_DATE, GliderLogTables.F_STARTED, GliderLogTables.F_LANDED, GliderLogTables.F_DURATION, GliderLogTables.F_TYPE, GliderLogTables.F_REGISTRATION, GliderLogTables.F_PILOT, GliderLogTables.F_PILOT_ID, GliderLogTables.F_COPILOT, GliderLogTables.F_COPILOT_ID, GliderLogTables.F_INSTRUCTION, GliderLogTables.F_NOTES, GliderLogTables.F_LAUNCH }; Cursor cur_go = getContentResolver().query(uri, projection, null, null, null); if (cur_go != null) { //Log.d(TAG,"cnt " + cursor.getCount()); try { if ((cur_go.getCount()) > 0) { cur_go.moveToFirst(); do { myOutWriter.append(cur_go .getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_DATE)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_STARTED)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_LANDED)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_DURATION)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_TYPE)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_REGISTRATION)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_PILOT)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_PILOT_ID)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_COPILOT)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_COPILOT_ID)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_INSTRUCTION)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_NOTES)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_LAUNCH))); myOutWriter.append("\n"); // Log.d(TAG,"gld " + cursor // .getColumnIndexOrThrow(GliderLogTables.F_REGISTRATION)); } while (cur_go.moveToNext()); } } finally { if (!cur_go.isClosed()) { cur_go.close(); } } } myOutWriter.close(); fOut.close(); } catch (IOException ioe) { Log.e(TAG, "Could not open/write the csv file, error: " + ioe.getMessage()); } catch (SQLiteException e) { Log.e(TAG, "SQLiteException:" + e.getMessage()); } catch (Exception e) { Log.e(TAG, "Could not open/read the DB, error: " + e.getMessage()); } }
From source file:openscience.crowdsource.experiments.MainActivity.java
/*************************************************************************/ /* read one string file */ private boolean save_one_string_file(String fname, String text) { FileOutputStream o = null;//from w ww . j ava2s . co m try { o = new FileOutputStream(fname, false); } catch (FileNotFoundException e) { return false; } OutputStreamWriter oo = new OutputStreamWriter(o); try { oo.append(text); oo.flush(); oo.close(); } catch (IOException e) { return false; } return true; }
From source file:org.rascalmpl.library.Prelude.java
private void writeFileEnc(ISourceLocation sloc, IString charset, IList V, boolean append, IEvaluatorContext ctx) {/*from w ww . ja v a2 s. c om*/ sloc = ctx.getHeap().resolveSourceLocation(sloc); OutputStreamWriter out = null; if (!Charset.forName(charset.getValue()).canEncode()) { throw RuntimeExceptionFactory.illegalArgument(charset, null, null); } try { out = new UnicodeOutputStreamWriter(ctx.getResolverRegistry().getOutputStream(sloc.getURI(), append), charset.getValue(), append); for (IValue elem : V) { if (elem.getType().isString()) { out.append(((IString) elem).getValue()); } else if (elem.getType().isSubtypeOf(Factory.Tree)) { out.append(TreeAdapter.yield((IConstructor) elem)); } else { out.append(elem.toString()); } } } catch (FileNotFoundException fnfex) { throw RuntimeExceptionFactory.pathNotFound(sloc, ctx.getCurrentAST(), null); } catch (IOException ioex) { throw RuntimeExceptionFactory.io(values.string(ioex.getMessage()), ctx.getCurrentAST(), null); } finally { if (out != null) { try { out.close(); } catch (IOException ioex) { throw RuntimeExceptionFactory.io(values.string(ioex.getMessage()), ctx.getCurrentAST(), null); } } } return; }
From source file:dev.ukanth.ufirewall.Api.java
public static boolean saveAllPreferencesToFile(Context ctx) { boolean res = false; File sdCard = Environment.getExternalStorageDirectory(); if (isExternalStorageWritable()) { File dir = new File(sdCard.getAbsolutePath() + "/afwall/"); dir.mkdirs();/*from w w w. j a va 2 s . c o m*/ File file = new File(dir, "backup_all.json"); try { FileOutputStream fOut = new FileOutputStream(file); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); JSONObject exportObject = new JSONObject(); //if multiprofile is enabled if (G.enableMultiProfile()) { JSONObject profileObject = new JSONObject(); //store all the profile settings for (String profile : G.profiles) { Map<String, JSONObject> exportMap = new HashMap<String, JSONObject>(); final SharedPreferences prefs = ctx.getSharedPreferences(profile, Context.MODE_PRIVATE); updatePackage(ctx, prefs.getString(PREF_WIFI_PKG_UIDS, ""), exportMap, WIFI_EXPORT); updatePackage(ctx, prefs.getString(PREF_3G_PKG_UIDS, ""), exportMap, DATA_EXPORT); updatePackage(ctx, prefs.getString(PREF_ROAMING_PKG_UIDS, ""), exportMap, ROAM_EXPORT); updatePackage(ctx, prefs.getString(PREF_VPN_PKG_UIDS, ""), exportMap, VPN_EXPORT); updatePackage(ctx, prefs.getString(PREF_LAN_PKG_UIDS, ""), exportMap, LAN_EXPORT); profileObject.put(profile, new JSONObject(exportMap)); } exportObject.put("profiles", profileObject); //if any additional profiles int defaultProfileCount = 3; JSONObject addProfileObject = new JSONObject(); for (String profile : G.getAdditionalProfiles()) { defaultProfileCount++; Map<String, JSONObject> exportMap = new HashMap<String, JSONObject>(); final SharedPreferences prefs = ctx .getSharedPreferences("AFWallProfile" + defaultProfileCount, Context.MODE_PRIVATE); updatePackage(ctx, prefs.getString(PREF_WIFI_PKG_UIDS, ""), exportMap, WIFI_EXPORT); updatePackage(ctx, prefs.getString(PREF_3G_PKG_UIDS, ""), exportMap, DATA_EXPORT); updatePackage(ctx, prefs.getString(PREF_ROAMING_PKG_UIDS, ""), exportMap, ROAM_EXPORT); updatePackage(ctx, prefs.getString(PREF_VPN_PKG_UIDS, ""), exportMap, VPN_EXPORT); updatePackage(ctx, prefs.getString(PREF_LAN_PKG_UIDS, ""), exportMap, LAN_EXPORT); addProfileObject.put(profile, new JSONObject(exportMap)); } exportObject.put("additional_profiles", addProfileObject); } else { //default Profile - current one JSONObject obj = new JSONObject(getCurrentRulesAsMap(ctx)); exportObject.put("default", obj); } //now gets all the preferences exportObject.put("prefs", getAllAppPreferences(ctx, G.gPrefs)); myOutWriter.append(exportObject.toString()); res = true; myOutWriter.close(); fOut.close(); } catch (FileNotFoundException e) { Log.d(TAG, e.getLocalizedMessage()); } catch (IOException e) { Log.d(TAG, e.getLocalizedMessage()); } catch (JSONException e) { Log.d(TAG, e.getLocalizedMessage()); } } return res; }
From source file:Admin_Thesaurus.ImportData.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (SystemIsLockedForAdministrativeJobs(request, response)) { return;/* w ww. ja va 2 s . co m*/ } String basePath = request.getSession().getServletContext().getRealPath(""); // ---------------------- LOCK SYSTEM ---------------------- ConfigDBadmin config = new ConfigDBadmin(basePath); DBAdminUtilities dbAdminUtils = new DBAdminUtilities(); dbAdminUtils.LockSystemForAdministrativeJobs(config); response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); HttpSession session = request.getSession(); ServletContext context = session.getServletContext(); SessionWrapperClass sessionInstance = new SessionWrapperClass(); init(request, response, sessionInstance); PrintWriter out = response.getWriter(); OutputStreamWriter logFileWriter = null; try { // check for previous logon but because of ajax usage respond with Session Invalidate str UserInfoClass SessionUserInfo = (UserInfoClass) sessionInstance.getAttribute("SessionUser"); if (SessionUserInfo == null || !SessionUserInfo.servletAccessControl(this.getClass().getName())) { out.println("Session Invalidate"); response.sendRedirect("Index"); return; } //tools Utilities u = new Utilities(); DBGeneral dbGen = new DBGeneral(); DBImportData dbImport = new DBImportData(); DBMergeThesauri dbMerge = new DBMergeThesauri(); StringObject translatedMsgObj = new StringObject(""); Vector<String> thesauriNames = new Vector<String>(); CommonUtilsDBadmin common_utils = new CommonUtilsDBadmin(config); StringObject resultObj = new StringObject(""); String initiallySelectedThesaurus = SessionUserInfo.selectedThesaurus; //Parameters String xmlFilePath = request.getParameter("importXMLfilename"); //String importSchemaName = request.getParameter("schematype"); String importSchemaName = ConstantParameters.xmlschematype_THEMAS; String importThesaurusName = request.getParameter("Import_Thesaurus_NewName_NAME"); String importMethodChoice = request.getParameter("ImportThesaurusMode");//thesaurusImport or bulkImport String importHierarchyName = u .getDecodedParameterValue(request.getParameter("Import_Thesaurus_HierarchyName")); String pathToErrorsXML = context.getRealPath("/translations/Consistencies_Error_Codes.xml"); String language = context.getInitParameter("LocaleLanguage"); String country = context.getInitParameter("LocaleCountry"); String WebAppUsersFileName = request.getSession().getServletContext() .getRealPath("/" + UsersClass.WebAppUsersXMLFilePath); String logPath = context.getRealPath("/" + ConstantParameters.LogFilesFolderName); String logFileNamePath = logPath; String webAppSaveResults_Folder = Parameters.Save_Results_Folder; String pathToSaveScriptingAndLocale = context .getRealPath("/translations/SaveAll_Locale_And_Scripting.xml"); Locale targetLocale = new Locale(language, country); if ((importMethodChoice.equals("thesaurusImport") && (importThesaurusName != null)) || (importMethodChoice.equals("bulkImport") && importHierarchyName != null)) { UpDownFiles fup = new UpDownFiles(); String[] formData = new String[10]; FileItem[] dom = fup.prepareToUpBinary(request, formData); //Hashtable initParams = UpDownFiles.uploadParams; if (dom[0] != null) { String filename = xmlFilePath; ///String caption = (String) initParams.get("caption"); filename = filename.substring(filename.lastIndexOf(File.separator) + 1); String fileType = filename.substring(filename.lastIndexOf(".") + 1); String userFileName = filename.substring(0, filename.lastIndexOf(".")); filename = userFileName + "(" + getDate() + " " + getTime() + ")." + fileType; String fullPath = getServletContext().getRealPath("/Uploads") + "/" + filename; xmlFilePath = fullPath; if (fup.writeBinary(dom[0], fullPath)) { //mode = 1; } else { //mode = -1; } } else { //mode = -1; } } QClass Q = new QClass(); TMSAPIClass TA = new TMSAPIClass(); IntegerObject sis_session = new IntegerObject(); IntegerObject tms_session = new IntegerObject(); //open connection and start transaction if (dbGen.openConnectionAndStartQueryOrTransaction(Q, TA, sis_session, null, null, true) == QClass.APIFail) { Utils.StaticClass .webAppSystemOutPrintln("OPEN CONNECTION ERROR @ servlet " + this.getServletName()); return; } dbGen.GetExistingThesaurus(false, thesauriNames, Q, sis_session); if (importMethodChoice.equals("thesaurusImport")) { //Format Name Of import Thesaurus importThesaurusName = importThesaurusName.trim(); importThesaurusName = importThesaurusName.replaceAll(" ", "_"); importThesaurusName = importThesaurusName.toUpperCase(); if (thesauriNames.contains(importThesaurusName)) { resultObj.setValue(u.translateFromMessagesXML("root/ImportData/importThesaurusNameFailure", new String[] { importThesaurusName })); //resultObj.setValue("Thesaurus '" + importThesaurusName + "' already exists in database. Please choose a different name for the Thesaurus."); Vector<String> allHierarchies = new Vector<String>(); Vector<String> allGuideTerms = new Vector<String>(); dbGen.getDBAdminHierarchiesStatusesAndGuideTermsXML(SessionUserInfo, Q, sis_session, allHierarchies, allGuideTerms); //end query and close connection Q.free_all_sets(); Q.TEST_end_query(); //Q.TEST_abort_transaction(); dbGen.CloseDBConnection(Q, null, sis_session, null, false); StringBuffer xml = new StringBuffer(); xml.append(u.getXMLStart(ConstantParameters.LMENU_THESAURI)); xml.append(u.getDBAdminHierarchiesStatusesAndGuideTermsXML(allHierarchies, allGuideTerms, targetLocale)); xml.append(getXMLMiddle(thesauriNames, u.translateFromMessagesXML("root/ImportData/ImportFunctionFailure", null) + resultObj.getValue(), importMethodChoice)); xml.append(u.getXMLUserInfo(SessionUserInfo)); xml.append(u.getXMLEnd()); u.XmlPrintWriterTransform(out, xml, sessionInstance.path + "/xml-xsl/page_contents.xsl"); // ---------------------- UNLOCK SYSTEM ---------------------- dbAdminUtils.UnlockSystemForAdministrativeJobs(); return; } } else if (importMethodChoice.equals("bulkImport")) { importThesaurusName = SessionUserInfo.selectedThesaurus; if (thesauriNames.contains(importThesaurusName) == false) { //String pathToMessagesXML = context.getRealPath("/translations/Messages.xml"); //StringObject resultMessageObj = new StringObject(); StringObject resultMessageObj_2 = new StringObject(); //Vector<String> errorArgs = new Vector<String>(); resultObj.setValue(u.translateFromMessagesXML("root/ImportData/ThesaurusDoesNotExist", new String[] { importThesaurusName })); //resultObj.setValue("Thesaurus '" + importThesaurusName + "' does not exist in database. Please choose a different thesaurus if this one still exists."); Vector<String> allHierarchies = new Vector<String>(); Vector<String> allGuideTerms = new Vector<String>(); dbGen.getDBAdminHierarchiesStatusesAndGuideTermsXML(SessionUserInfo, Q, sis_session, allHierarchies, allGuideTerms); //end query and close connection Q.free_all_sets(); Q.TEST_end_query(); //Q.TEST_abort_transaction(); dbGen.CloseDBConnection(Q, null, sis_session, null, false); StringBuffer xml = new StringBuffer(); xml.append(u.getXMLStart(ConstantParameters.LMENU_THESAURI)); xml.append(u.getDBAdminHierarchiesStatusesAndGuideTermsXML(allHierarchies, allGuideTerms, targetLocale)); resultMessageObj_2 .setValue(u.translateFromMessagesXML("root/ImportData/InsertionFailure", null)); xml.append(getXMLMiddle(thesauriNames, resultMessageObj_2.getValue() + resultObj.getValue(), importMethodChoice)); //xml.append(getXMLMiddle(thesauriNames, "Data insertion failure. " + resultObj.getValue(),importMethodChoice)); xml.append(u.getXMLUserInfo(SessionUserInfo)); xml.append(u.getXMLEnd()); u.XmlPrintWriterTransform(out, xml, sessionInstance.path + "/xml-xsl/page_contents.xsl"); // ---------------------- UNLOCK SYSTEM ---------------------- dbAdminUtils.UnlockSystemForAdministrativeJobs(); return; } } //end query and close connection Q.free_all_sets(); Q.TEST_end_query(); dbGen.CloseDBConnection(Q, null, sis_session, null, false); Utils.StaticClass.closeDb(); StringObject DBbackupFileNameCreated = new StringObject(""); long startTime = Utilities.startTimer(); String time = Utilities.GetNow(); String Filename = "Import_Thesaurus_" + importThesaurusName + "_" + time; logFileNamePath += "/" + Filename + ".xml"; try { OutputStream fout = new FileOutputStream(logFileNamePath); OutputStream bout = new BufferedOutputStream(fout); logFileWriter = new OutputStreamWriter(bout, "UTF-8"); logFileWriter.append(ConstantParameters.xmlHeader);//+ "\r\n" //logFileWriter.append("<?xml-stylesheet type=\"text/xsl\" href=\"../" + webAppSaveResults_Folder + "/ImportCopyMergeThesaurus_Report.xsl" + "\"?>\r\n"); logFileWriter.append("<page language=\"" + Parameters.UILang + "\" primarylanguage=\"" + Parameters.PrimaryLang.toLowerCase() + "\">\r\n"); logFileWriter.append("<title>" + u.translateFromMessagesXML("root/ImportData/ReportTitle", new String[] { importThesaurusName, time }) + "</title>\r\n" + "<pathToSaveScriptingAndLocale>" + pathToSaveScriptingAndLocale + "</pathToSaveScriptingAndLocale>\r\n"); //logFileWriter.append("<!--"+time + " LogFile for data import in thesaurus: " + importThesaurusName +".-->\r\n"); Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix + time + " LogFile for data import in thesaurus: " + importThesaurusName + "."); } catch (Exception exc) { Utils.StaticClass.webAppSystemOutPrintln( Parameters.LogFilePrefix + "Error in opening file: " + exc.getMessage()); Utils.StaticClass.handleException(exc); } if (importMethodChoice.equals("thesaurusImport")) { if (dbImport.thesaurusImportActions(SessionUserInfo, common_utils, config, targetLocale, pathToErrorsXML, xmlFilePath, importSchemaName, importThesaurusName, "backup_before_import_data_to_thes_" + importThesaurusName, DBbackupFileNameCreated, resultObj, logFileWriter) == false) { abortActions(request, sessionInstance, context, targetLocale, common_utils, initiallySelectedThesaurus, importThesaurusName, DBbackupFileNameCreated, resultObj, out); return; } } else if (importMethodChoice.equals("bulkImport")) { /* //open connection and start Transaction if(dbGen.openConnectionAndStartQueryOrTransaction(Q, TA, sis_session, tms_session, SessionUserInfo.selectedThesaurus, false)==QClass.APIFail) { Utils.StaticClass.webAppSystemOutPrintln("OPEN CONNECTION ERROR @ servlet " + this.getServletName()); return; } */ if (dbImport.bulkImportActions(sessionInstance, context, common_utils, config, targetLocale, pathToErrorsXML, xmlFilePath, importThesaurusName, importHierarchyName, "backup_before_import_data_to_thes_" + importThesaurusName, DBbackupFileNameCreated, resultObj, logFileWriter) == false) { abortActions(request, sessionInstance, context, targetLocale, common_utils, initiallySelectedThesaurus, importThesaurusName, DBbackupFileNameCreated, resultObj, out); return; } } commitActions(request, WebAppUsersFileName, sessionInstance, context, targetLocale, importThesaurusName, out, Filename.concat(".html")); //ReportSuccessMessage logFileWriter .append("\r\n<creationInfo>" + u.translateFromMessagesXML("root/ImportData/ReportSuccessMessage", new String[] { importThesaurusName, xmlFilePath, ((Utilities.stopTimer(startTime)) / 60) + "" }) + "</creationInfo>\r\n"); if (logFileWriter != null) { logFileWriter.append("</page>"); logFileWriter.flush(); logFileWriter.close(); } //Now XSL should be found and java xsl transformation should be performed String XSL = context.getRealPath("/" + webAppSaveResults_Folder) + "/ImportCopyMergeThesaurus_Report.xsl"; u.XmlFileTransform(logFileNamePath, XSL, logPath + "/" + Filename.concat(".html")); } catch (Exception e) { Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix + ".Exception catched in servlet " + getServletName() + ". Message:" + e.getMessage()); Utils.StaticClass.handleException(e); if (logFileWriter != null) { logFileWriter.append("</page>"); logFileWriter.flush(); logFileWriter.close(); } } finally { out.flush(); out.close(); sessionInstance.writeBackToSession(session); } }