List of usage examples for javax.xml.parsers SAXParserFactory newSAXParser
public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;
From source file:cm.aptoide.pt.MainActivity.java
private void loadRecommended() { if (Login.isLoggedIn(mContext)) { ((TextView) featuredView.findViewById(R.id.recommended_text)).setVisibility(View.GONE); } else {//from w w w . jav a 2 s . c o m ((TextView) featuredView.findViewById(R.id.recommended_text)).setVisibility(View.VISIBLE); } new Thread(new Runnable() { private ArrayList<HashMap<String, String>> valuesRecommended; public void run() { loadUIRecommendedApps(); File f = null; try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); NetworkUtils utils = new NetworkUtils(); BufferedInputStream bis = new BufferedInputStream( utils.getInputStream("http://webservices.aptoide.com/webservices/listUserBasedApks/" + Login.getToken(mContext) + "/10/xml", null, null, mContext), 8 * 1024); f = File.createTempFile("abc", "abc"); OutputStream out = new FileOutputStream(f); byte buf[] = new byte[1024]; int len; while ((len = bis.read(buf)) > 0) out.write(buf, 0, len); out.close(); bis.close(); String hash = Md5Handler.md5Calc(f); ViewApk parent_apk = new ViewApk(); parent_apk.setApkid("recommended"); if (!hash.equals(db.getItemBasedApksHash(parent_apk.getApkid()))) { // Database.database.beginTransaction(); db.deleteItemBasedApks(parent_apk); sp.parse(f, new HandlerItemBased(parent_apk)); db.insertItemBasedApkHash(hash, parent_apk.getApkid()); // Database.database.setTransactionSuccessful(); // Database.database.endTransaction(); loadUIRecommendedApps(); } } catch (Exception e) { e.printStackTrace(); } if (f != null) f.delete(); } private void loadUIRecommendedApps() { valuesRecommended = db.getItemBasedApksRecommended("recommended"); runOnUiThread(new Runnable() { public void run() { LinearLayout ll = (LinearLayout) featuredView.findViewById(R.id.recommended_container); ll.removeAllViews(); LinearLayout llAlso = new LinearLayout(MainActivity.this); llAlso.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); llAlso.setOrientation(LinearLayout.HORIZONTAL); if (valuesRecommended.isEmpty()) { if (Login.isLoggedIn(mContext)) { TextView tv = new TextView(mContext); tv.setText(R.string.no_recommended_apps); tv.setTextAppearance(mContext, android.R.attr.textAppearanceMedium); tv.setPadding(10, 10, 10, 10); ll.addView(tv); } } else { for (int i = 0; i != valuesRecommended.size(); i++) { LinearLayout txtSamItem = (LinearLayout) getLayoutInflater() .inflate(R.layout.row_grid_item, null); ((TextView) txtSamItem.findViewById(R.id.name)) .setText(valuesRecommended.get(i).get("name")); ImageLoader.getInstance().displayImage(valuesRecommended.get(i).get("icon"), (ImageView) txtSamItem.findViewById(R.id.icon)); float stars = 0f; try { stars = Float.parseFloat(valuesRecommended.get(i).get("rating")); } catch (Exception e) { stars = 0f; } ((RatingBar) txtSamItem.findViewById(R.id.rating)).setIsIndicator(true); ((RatingBar) txtSamItem.findViewById(R.id.rating)).setRating(stars); txtSamItem.setPadding(10, 0, 0, 0); // ((TextView) // txtSamItem.findViewById(R.id.version)) // .setText(getString(R.string.version) +" "+ // valuesRecommended.get(i).get("vername")); ((TextView) txtSamItem.findViewById(R.id.downloads)) .setText("(" + valuesRecommended.get(i).get("downloads") + " " + getString(R.string.downloads) + ")"); txtSamItem.setTag(valuesRecommended.get(i).get("_id")); txtSamItem.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 100, 1)); // txtSamItem.setOnClickListener(featuredListener); txtSamItem.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent i = new Intent(MainActivity.this, ApkInfo.class); long id = Long.parseLong((String) arg0.getTag()); i.putExtra("_id", id); i.putExtra("top", true); i.putExtra("category", Category.ITEMBASED.ordinal()); startActivity(i); } }); txtSamItem.measure(0, 0); if (i % 2 == 0) { ll.addView(llAlso); llAlso = new LinearLayout(MainActivity.this); llAlso.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 100)); llAlso.setOrientation(LinearLayout.HORIZONTAL); llAlso.addView(txtSamItem); } else { llAlso.addView(txtSamItem); } } ll.addView(llAlso); } } }); } }).start(); }
From source file:cm.aptoide.pt.MainActivity.java
private void loadFeatured() { new Thread(new Runnable() { public void run() { loadUIEditorsApps();/*from w ww .j a v a 2s. c om*/ File f = null; try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); NetworkUtils utils = new NetworkUtils(); String url; f = File.createTempFile("tempFile", ""); String countryCode = Geolocation.getCountryCode(mContext); Log.d("Aptoide-Geolocation", "Using countrycode: " + countryCode); if (ApplicationAptoide.CUSTOMEDITORSCHOICE) { url = getEditorsChoiceURL(ApplicationAptoide.DEFAULTSTORENAME, countryCode); if (((HttpURLConnection) new URL(url).openConnection()).getResponseCode() != 200) { url = getEditorsChoiceURL("apps", countryCode); } } else { url = getEditorsChoiceURL("apps", countryCode); } long date = utils.getLastModified(new URL(url)); long cachedDate = db.getEditorsChoiceHash(); Log.d("Getting", "Date is " + date); Log.d("Getting", "CachedDate is " + cachedDate); if (cachedDate < date) { BufferedInputStream bis = new BufferedInputStream( utils.getInputStream(url, null, null, mContext), 8 * 1024); OutputStream out = new FileOutputStream(f); byte buf[] = new byte[1024]; int len; while ((len = bis.read(buf)) > 0) out.write(buf, 0, len); out.close(); bis.close(); Server server = new Server(); // Database.database.beginTransaction(); db.deleteEditorsChoice(); sp.parse(f, new HandlerEditorsChoice(server)); db.insertEditorsChoiceHash(date); // Database.database.setTransactionSuccessful(); // Database.database.endTransaction(); loadUIEditorsApps(); } } catch (SAXException e) { // Database.database.setTransactionSuccessful(); // Database.database.endTransaction(); } catch (Exception e) { e.printStackTrace(); } if (f != null) f.delete(); } private String getEditorsChoiceURL(String store, String countryCode) { if (countryCode.length() > 0) { return "http://" + store + ".store.aptoide.com/editors.xml?country=" + countryCode; } return "http://" + store + ".store.aptoide.com/editors.xml"; } }).start(); new Thread(new Runnable() { public void run() { loadUItopapps(); File f = null; try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); Server server = new Server(); server.id = 1; NetworkUtils utils = new NetworkUtils(); String url; if (ApplicationAptoide.CUSTOMEDITORSCHOICE) { url = "http://" + ApplicationAptoide.DEFAULTSTORENAME + ".store.aptoide.com/top.xml"; if (((HttpURLConnection) new URL(url).openConnection()).getResponseCode() != 200) { url = "http://apps.store.aptoide.com/top.xml"; } } else { url = "http://apps.store.aptoide.com/top.xml"; } long date = utils.getLastModified(new URL(url)); long cachedDate; try { cachedDate = Long.parseLong(db.getRepoHash(server.id, Category.TOPFEATURED)); } catch (Exception e) { cachedDate = 0; } if (cachedDate < date) { BufferedInputStream bis = new BufferedInputStream( utils.getInputStream(url, null, null, mContext), 8 * 1024); f = File.createTempFile("tempFile", ""); OutputStream out = new FileOutputStream(f); byte buf[] = new byte[1024]; int len; while ((len = bis.read(buf)) > 0) out.write(buf, 0, len); out.close(); bis.close(); // Database.database.beginTransaction(); db.deleteFeaturedTopApps(); sp.parse(f, new HandlerFeaturedTop(server)); db.insertFeaturedTopHash(date); loadUItopapps(); f.delete(); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { } catch (IOException e) { e.printStackTrace(); } if (f != null) f.delete(); } }).start(); }
From source file:cm.aptoide.pt.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { AptoideThemePicker.setAptoideTheme(this); super.onCreate(savedInstanceState); serviceDownloadManagerIntent = new Intent(this, ServiceDownloadManager.class); startService(serviceDownloadManagerIntent); mContext = this; File sdcard_file = new File(SDCARD); if (!sdcard_file.exists() || !sdcard_file.canWrite()) { View simpleView = LayoutInflater.from(mContext).inflate(R.layout.dialog_simple_layout, null); Builder dialogBuilder = new AlertDialog.Builder(mContext).setView(simpleView); final AlertDialog noSDDialog = dialogBuilder.create(); noSDDialog.setTitle(getText(R.string.remote_in_noSD_title)); noSDDialog.setIcon(android.R.drawable.ic_dialog_alert); TextView message = (TextView) simpleView.findViewById(R.id.dialog_message); message.setText(getText(R.string.remote_in_noSD)); noSDDialog.setCancelable(false); noSDDialog.setButton(Dialog.BUTTON_NEUTRAL, getString(android.R.string.ok), new Dialog.OnClickListener() { @Override// w w w. ja v a 2s . c o m public void onClick(DialogInterface arg0, int arg1) { finish(); } }); noSDDialog.show(); } else { StatFs stat = new StatFs(sdcard_file.getPath()); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getBlockCount(); long availableBlocks = stat.getAvailableBlocks(); long total = (blockSize * totalBlocks) / 1024 / 1024; long avail = (blockSize * availableBlocks) / 1024 / 1024; Log.d("Aptoide", "* * * * * * * * * *"); Log.d("Aptoide", "Total: " + total + " Mb"); Log.d("Aptoide", "Available: " + avail + " Mb"); if (avail < 10) { Log.d("Aptoide", "No space left on SDCARD..."); Log.d("Aptoide", "* * * * * * * * * *"); View simpleView = LayoutInflater.from(this).inflate(R.layout.dialog_simple_layout, null); Builder dialogBuilder = new AlertDialog.Builder(this).setView(simpleView); final AlertDialog noSpaceDialog = dialogBuilder.create(); noSpaceDialog.setIcon(android.R.drawable.ic_dialog_alert); TextView message = (TextView) simpleView.findViewById(R.id.dialog_message); message.setText(getText(R.string.remote_in_noSDspace)); noSpaceDialog.setButton(Dialog.BUTTON_NEUTRAL, getText(android.R.string.ok), new Dialog.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { finish(); } }); noSpaceDialog.show(); } else { SharedPreferences sPref = PreferenceManager.getDefaultSharedPreferences(mContext); editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit(); if (!sPref.contains("matureChkBox")) { editor.putBoolean("matureChkBox", ApplicationAptoide.MATURECONTENTSWITCHVALUE); SharedPreferences sPrefOld = getSharedPreferences("aptoide_prefs", MODE_PRIVATE); if (sPrefOld.getString("app_rating", "none").equals("Mature")) { editor.putBoolean("matureChkBox", false); } } if (!sPref.contains("version")) { ApplicationAptoide.setRestartLauncher(true); try { editor.putInt("version", getPackageManager().getPackageInfo(getPackageName(), 0).versionCode); } catch (NameNotFoundException e) { e.printStackTrace(); } } if (sPref.getString("myId", null) == null) { String rand_id = UUID.randomUUID().toString(); editor.putString("myId", rand_id); } if (sPref.getInt("scW", 0) == 0 || sPref.getInt("scH", 0) == 0) { DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); editor.putInt("scW", dm.widthPixels); editor.putInt("scH", dm.heightPixels); } editor.commit(); File file = new File(LOCAL_PATH + "/apks"); if (!file.exists()) { file.mkdirs(); } new Thread(new Runnable() { @Override public void run() { // Note the L that tells the compiler to interpret the // number as a Long final long MAXFILEAGE = 2678400000L; // 1 month in // milliseconds // Get file handle to the directory. In this case the // application files dir File dir = new File(LOCAL_PATH + "/apks"); // Optain list of files in the directory. // listFiles() returns a list of File objects to each // file found. File[] files = dir.listFiles(); // Loop through all files for (File f : files) { // Get the last modified date. Miliseconds since // 1970 long lastmodified = f.lastModified(); // Do stuff here to deal with the file.. // For instance delete files older than 1 month if (lastmodified + MAXFILEAGE < System.currentTimeMillis()) { f.delete(); } } } }).start(); db = Database.getInstance(); Intent i = new Intent(mContext, MainService.class); startService(i); bindService(i, conn, Context.BIND_AUTO_CREATE); order = Order.values()[PreferenceManager.getDefaultSharedPreferences(mContext).getInt("order_list", 0)]; registerReceiver(updatesReceiver, new IntentFilter("update")); registerReceiver(statusReceiver, new IntentFilter("status")); registerReceiver(loginReceiver, new IntentFilter("login")); registerReceiver(storePasswordReceiver, new IntentFilter("401")); registerReceiver(redrawInstalledReceiver, new IntentFilter("pt.caixamagica.aptoide.REDRAW")); if (!ApplicationAptoide.MULTIPLESTORES) { registerReceiver(parseFailedReceiver, new IntentFilter("PARSE_FAILED")); } registerReceiver(newRepoReceiver, new IntentFilter("pt.caixamagica.aptoide.NEWREPO")); registered = true; categoriesStrings = new HashMap<String, Integer>(); // categoriesStrings.put("Applications", R.string.applications); boolean serversFileIsEmpty = true; if (sPref.getBoolean("firstrun", true)) { // Intent shortcutIntent = new Intent(Intent.ACTION_MAIN); // shortcutIntent.setClassName("cm.aptoide.pt", // "cm.aptoide.pt.Start"); // final Intent intent = new Intent(); // intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, // shortcutIntent); // // intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, // getString(R.string.app_name)); // Parcelable iconResource = // Intent.ShortcutIconResource.fromContext(this, // R.drawable.ic_launcher); // // intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, // iconResource); // intent.putExtra("duplicate", false); // intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); // sendBroadcast(intent); if (new File(LOCAL_PATH + "/servers.xml").exists() && ApplicationAptoide.DEFAULTSTORENAME == null) { try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); MyappHandler handler = new MyappHandler(); sp.parse(new File(LOCAL_PATH + "/servers.xml"), handler); ArrayList<String> server = handler.getServers(); if (server.isEmpty()) { serversFileIsEmpty = true; } else { getIntent().putExtra("newrepo", server); } } catch (Exception e) { e.printStackTrace(); } } editor.putBoolean("firstrun", false); editor.putBoolean("orderByCategory", true); editor.commit(); } if (getIntent().hasExtra("newrepo")) { ArrayList<String> repos = (ArrayList<String>) getIntent().getSerializableExtra("newrepo"); for (final String uri2 : repos) { View simpleView = LayoutInflater.from(mContext).inflate(R.layout.dialog_simple_layout, null); Builder dialogBuilder = new AlertDialog.Builder(mContext).setView(simpleView); final AlertDialog addNewRepoDialog = dialogBuilder.create(); addNewRepoDialog.setTitle(getString(R.string.add_store)); addNewRepoDialog.setIcon(android.R.drawable.ic_menu_add); TextView message = (TextView) simpleView.findViewById(R.id.dialog_message); message.setText((getString(R.string.newrepo_alrt) + uri2 + " ?")); addNewRepoDialog.setCancelable(false); addNewRepoDialog.setButton(Dialog.BUTTON_POSITIVE, getString(android.R.string.yes), new Dialog.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { dialogAddStore(uri2, null, null); } }); addNewRepoDialog.setButton(Dialog.BUTTON_NEGATIVE, getString(android.R.string.no), new Dialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int arg1) { dialog.cancel(); } }); addNewRepoDialog.show(); } } else if (db.getStores(false).getCount() == 0 && ApplicationAptoide.DEFAULTSTORENAME == null && serversFileIsEmpty) { View simpleView = LayoutInflater.from(mContext).inflate(R.layout.dialog_simple_layout, null); Builder dialogBuilder = new AlertDialog.Builder(mContext).setView(simpleView); final AlertDialog addAppsRepoDialog = dialogBuilder.create(); addAppsRepoDialog.setTitle(getString(R.string.add_store)); addAppsRepoDialog.setIcon(android.R.drawable.ic_menu_add); TextView message = (TextView) simpleView.findViewById(R.id.dialog_message); message.setText(getString(R.string.myrepo_alrt) + "\n" + "http://apps.store.aptoide.com/"); addAppsRepoDialog.setCancelable(false); addAppsRepoDialog.setButton(Dialog.BUTTON_POSITIVE, getString(android.R.string.yes), new Dialog.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { dialogAddStore("http://apps.store.aptoide.com", null, null); } }); addAppsRepoDialog.setButton(Dialog.BUTTON_NEGATIVE, getString(android.R.string.no), new Dialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int arg1) { dialog.cancel(); } }); addAppsRepoDialog.show(); } new Thread(new Runnable() { @Override public void run() { try { getUpdateParameters(); if (getPackageManager().getPackageInfo(getPackageName(), 0).versionCode < Integer .parseInt(updateParams.get("versionCode"))) { runOnUiThread(new Runnable() { @Override public void run() { requestUpdateSelf(); } }); } } catch (Exception e) { e.printStackTrace(); } } }).start(); } featuredView = LayoutInflater.from(mContext).inflate(R.layout.page_featured, null); availableView = LayoutInflater.from(mContext).inflate(R.layout.page_available, null); updateView = LayoutInflater.from(mContext).inflate(R.layout.page_updates, null); banner = (LinearLayout) availableView.findViewById(R.id.banner); breadcrumbs = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.breadcrumb_container, null); installedView = new ListView(mContext); updatesListView = (ListView) updateView.findViewById(R.id.updates_list); availableListView = (ListView) availableView.findViewById(R.id.available_list); joinStores = (CheckBox) availableView.findViewById(R.id.join_stores); availableAdapter = new AvailableListAdapter(mContext, null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); installedAdapter = new InstalledAdapter(mContext, null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER, db); updatesAdapter = new UpdatesAdapter(mContext, null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); pb = (TextView) availableView.findViewById(R.id.loading_pb); addStoreButton = availableView.findViewById(R.id.add_store); bannerStoreAvatar = (ImageView) banner.findViewById(R.id.banner_store_avatar); bannerStoreName = (TextView) banner.findViewById(R.id.banner_store_name); bannerStoreDescription = (AutoScaleTextView) banner.findViewById(R.id.banner_store_description); } }
From source file:com.seajas.search.contender.service.modifier.ArchiveModifierService.java
/** * Handle the given archive's content by sending each entry to the given handler. * /*from w w w . j a v a 2 s . c o m*/ * @param archive * @param handler * @throws Exception */ public void handleArchive(final Archive archive, final ArchiveResultHandler handler) throws Exception { // Create a validating SAX parser final SAXParserFactory parserFactory = SAXParserFactory.newInstance(); parserFactory.setValidating(true); parserFactory.setNamespaceAware(true); // Create a common transformer per thread Transformer transformer = null; try { transformer = transformerCache.getTransformer(archive.getId(), "archive", archive.getModificationDate()); if (transformer == null) transformer = transformerCache.putContent(archive.getId(), "archive", archive.getModificationDate(), archive.getTransformerContent()); } catch (TransformerConfigurationException e) { logger.error("Unable to generate a (cached) transformer from the given content", e); return; } catch (TransformerFactoryConfigurationError e) { logger.error("Unable to generate a (cached) transformer from the given content", e); return; } // Store and process the files try { Map<File, String> storedResults = storeAndDecompressFiles(archive); List<String> deletedLinks = new ArrayList<String>(); // Only process deletes when a deletion expression has been provided if (StringUtils.hasText(archive.getDeletionExpression())) { // Process all entries beforehand, so to exclude deletes from the final result for (Map.Entry<File, String> storedResult : storedResults.entrySet()) { File storedResultsFolder = storedResult.getKey(); for (File entryLocation : storedResultsFolder.listFiles()) if (entryLocation.getName().matches(archive.getDeletionExpression())) { String deleteLink = entryLocation.getName().replaceAll(archive.getDeletionExpression(), archive.getInternalLink()); deletedLinks.add(deleteLink); // Delete the actual link cacheService .addDeleted(new CacheService.DeletedEntry(archive.getCollection(), deleteLink)); } } } // Now process the stored results themselves for (Map.Entry<File, String> storedResult : storedResults.entrySet()) { File storedResultsFolder = storedResult.getKey(); // Create the descriptions folder if it doesn't already exist File descriptionsFolderLocation = new File(storedResultsFolder, "descriptions"); if (!descriptionsFolderLocation.exists()) descriptionsFolderLocation.mkdirs(); for (File entryLocation : storedResultsFolder.listFiles()) { if (entryLocation.isDirectory()) { if (!entryLocation.getName().equals("descriptions")) logger.warn("Unknown folder '" + entryLocation.getName() + "'found in decompressed archive folder '" + storedResultsFolder.getAbsolutePath() + "'"); continue; } else if (StringUtils.hasText(archive.getDeletionExpression()) && entryLocation.getName().matches(archive.getDeletionExpression())) continue; InputStream transformationInputStream = null; try { transformationInputStream = new BufferedInputStream(new FileInputStream(entryLocation)); // Now determine the content type and create a reader in case of structured content MediaType entryMediaType = autoDetectParser.getDetector().detect(transformationInputStream, new Metadata()); if (!(entryMediaType.getSubtype().equals("xml") || entryMediaType.getSubtype().endsWith("+xml"))) { logger.warn("Archive entry " + entryLocation.getAbsolutePath() + " contains " + entryMediaType + " data which is unstructured, ignoring"); continue; } } catch (IOException e) { logger.error("Could not close input stream during archive processing", e); if (transformationInputStream != null) transformationInputStream.close(); continue; } // Process it as (semi-)structured content XmlReader transformationReader = new XmlReader(transformationInputStream, true); StringWriter transformationWriter = new StringWriter(); try { transformer.setOutputProperty(OutputKeys.ENCODING, "UTF8"); // Use a SAX reader for entity resolution XMLReader xmlReader = parserFactory.newSAXParser().getXMLReader(); InputSource inputSource = new InputSource(transformationReader); xmlReader.setEntityResolver(transformerCache.getEntityResolver()); inputSource.setSystemId("file://" + transformerCache.getDtdImportPath() + "/template.xsl"); // Perform the actual transformation transformer.setParameter("substituteUrl", archive.getInternalLink()); transformer.transform(new SAXSource(xmlReader, inputSource), new StreamResult(transformationWriter)); } catch (TransformerException e) { logger.error("Unable to perform content transformation for entry " + entryLocation.getAbsolutePath()); continue; } catch (SAXException e) { logger.error("Unable to perform content transformation for entry " + entryLocation.getAbsolutePath()); continue; } catch (ParserConfigurationException e) { logger.error("Unable to perform content transformation for entry " + entryLocation.getAbsolutePath()); continue; } finally { transformationInputStream.close(); transformationReader.close(); } // Create a syndication feed from the given result String resultContent = transformationWriter.toString(); SyndFeed resultFeed = null; try { SyndFeedInput feedInput = new SyndFeedInput(); resultFeed = feedInput.build(new StringReader(resultContent)); } catch (FeedException e) { logger.error("Could not parse the feed resulting from the archive entry transformation"); continue; } finally { transformationWriter.close(); } // Write the <description> content to a separate file and add it as an <enclosure> if (resultFeed.getEntries().size() > 0) { Integer entryNumber = 0; for (SyndEntry feedEntry : (Collection<SyndEntry>) resultFeed.getEntries()) { if (!deletedLinks.contains(feedEntry.getLink())) { String description = feedEntry.getDescription().getValue().trim(); File descriptionLocation = new File(descriptionsFolderLocation, stripExtension(entryLocation.getName()) + "-" + entryNumber++ + (feedEntry.getDescription().getType().equals("text/html") ? ".html" : ".xml")); Writer descriptionWriter = new OutputStreamWriter( new FileOutputStream(descriptionLocation), "UTF-8"); if (!description.endsWith("</html>")) descriptionWriter.write("<html>\n<head>\n\t<title>" + feedEntry.getTitle() + "</title>\n</head>\n<body>\n"); descriptionWriter.write(description); if (!description.endsWith("</html>")) descriptionWriter.write("\n</body>\n</html>"); descriptionWriter.flush(); descriptionWriter.close(); // Remove the link from the processed cache should it already be in there, taking care of updates cacheService.deleteElement(feedEntry.getLink()); // Then offer it up to the handler if (logger.isDebugEnabled()) logger.debug("Adding result content (" + entryNumber + ") for archive entry with path " + entryLocation.getAbsolutePath()); try { // NOTE: The encoding of 'UTF-8' is implied for archive-related files handler.process(new URI(feedEntry.getLink()), archive.getHostname(), feedEntry, resultFeed); } catch (FeedException e) { logger.error(String.format( "Could not offer feed entry with link '%s' - invalid entry", feedEntry.getLink()), e); } catch (URISyntaxException e) { logger.error(String.format( "Could not offer feed entry with link '%s' - invalid link", feedEntry.getLink()), e); } } else logger.info("Skipping over feed entry with link '" + feedEntry.getLink() + "' - marked for deletion"); } } else if (logger.isDebugEnabled()) logger.debug("No entries were found in archive entry with path " + entryLocation.getAbsolutePath()); } logger.info("Finished processing archive with name " + storedResult.getValue()); // Now archive the entry in the cache cacheService.addArchived(storedResult.getValue()); } logger.info("Finishing archive populator thread"); } catch (IOException e) { logger.error("Could not close input stream during archive processing", e); } }
From source file:ee.sk.digidoc.factory.SAXDigiDocFactory.java
/** * Reads in a DigiDoc file. One of fname or isSdoc must be given. * @param fname signed doc filename// w w w . j av a 2s . c o m * @param isSdoc opened stream with DigiDoc data * The user must open and close it. * @param errs list of errors to fill with parsing errors. If given * then attempt is made to continue parsing on errors and return them in this list. * If not given (null) then the first error found will be thrown. * @return signed document object if successfully parsed */ private SignedDoc readSignedDocOfType(String fname, InputStream isSdoc, boolean isBdoc, List errs) throws DigiDocException { // Use an instance of ourselves as the SAX event handler SAXDigiDocFactory handler = this; m_errs = errs; DigiDocVerifyFactory.initProvider(); SAXParserFactory factory = SAXParserFactory.newInstance(); if (m_logger.isDebugEnabled()) m_logger.debug("Start reading ddoc/bdoc " + ((fname != null) ? "from file: " + fname : "from stream") + " bdoc: " + isBdoc); if (fname == null && isSdoc == null) { throw new DigiDocException(DigiDocException.ERR_READ_FILE, "No input file", null); } if (fname != null) { File inFile = new File(fname); if (!inFile.canRead() || inFile.length() == 0) { throw new DigiDocException(DigiDocException.ERR_READ_FILE, "Empty or unreadable input file", null); } } ZipFile zf = null; ZipArchiveInputStream zis = null; ZipArchiveEntry ze = null; InputStream isEntry = null; File fTmp = null; try { factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); if (isBdoc) { // bdoc parsing // must be a bdoc document ? m_doc = new SignedDoc(); m_doc.setVersion(SignedDoc.BDOC_VERSION_1_0); m_doc.setFormat(SignedDoc.FORMAT_BDOC); Enumeration eFiles = null; if (fname != null) { zf = new ZipFile(fname, "UTF-8"); eFiles = zf.getEntries(); } else if (isSdoc != null) { zis = new ZipArchiveInputStream(isSdoc, "UTF-8", true, true); } ArrayList lSigFnames = new ArrayList(); ArrayList lDataFnames = new ArrayList(); // read all entries boolean bHasMimetype = false, bManifest1 = false; int nFil = 0; while ((zf != null && eFiles.hasMoreElements()) || (zis != null && ((ze = zis.getNextZipEntry()) != null))) { nFil++; // read entry if (zf != null) { // ZipFile ze = (ZipArchiveEntry) eFiles.nextElement(); isEntry = zf.getInputStream(ze); } else { // ZipArchiveInputStream int n = 0, nTot = 0; if ((ze.getName().equals(FILE_MIMETYPE) || ze.getName().equals(FILE_MANIFEST) || (ze.getName().startsWith(FILE_SIGNATURES) && ze.getName().endsWith(".xml"))) || (nMaxBdocFilCached <= 0 || (ze.getSize() < nMaxBdocFilCached && ze.getSize() >= 0))) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] data = new byte[2048]; while ((n = zis.read(data)) > 0) { bos.write(data, 0, n); nTot += n; } if (m_logger.isDebugEnabled()) m_logger.debug("Read: " + nTot + " bytes from zip"); data = bos.toByteArray(); bos = null; isEntry = new ByteArrayInputStream(data); } else { File fCacheDir = new File(ConfigManager.instance().getStringProperty( "DIGIDOC_DF_CACHE_DIR", System.getProperty("java.io.tmpdir"))); fTmp = File.createTempFile("bdoc-data", ".tmp", fCacheDir); FileOutputStream fos = new FileOutputStream(fTmp); byte[] data = new byte[2048]; while ((n = zis.read(data)) > 0) { fos.write(data, 0, n); nTot += n; } if (m_logger.isDebugEnabled()) m_logger.debug("Read: " + nTot + " bytes from zip to: " + fTmp.getAbsolutePath()); fos.close(); isEntry = new FileInputStream(fTmp); } } if (m_logger.isDebugEnabled()) m_logger.debug("Entry: " + ze.getName() + " nlen: " + ze.getName().length() + " size: " + ze.getSize() + " dir: " + ze.isDirectory() + " comp-size: " + ze.getCompressedSize()); // mimetype file if (ze.getName().equals(FILE_MIMETYPE)) { if (m_logger.isDebugEnabled()) m_logger.debug("Check mimetype!"); checkBdocMimetype(isEntry); bHasMimetype = true; m_doc.setComment(ze.getComment()); if (nFil != 1) { m_logger.error("mimetype file is " + nFil + " file but must be first"); handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML, "mimetype file is not first zip entry", null)); } } else if (ze.getName().equals(FILE_MANIFEST)) { // manifest.xml file if (m_logger.isDebugEnabled()) m_logger.debug("Read manifest"); if (!bManifest1 && isEntry != null) { bManifest1 = true; BdocManifestParser mfparser = new BdocManifestParser(m_doc); mfparser.readManifest(isEntry); } else { m_logger.error("Found multiple manifest.xml files!"); throw new DigiDocException(DigiDocException.ERR_MULTIPLE_MANIFEST_FILES, "Found multiple manifest.xml files!", null); } } else if (ze.getName().startsWith(FILE_SIGNATURES) && ze.getName().endsWith(".xml")) { // some signature m_fileName = ze.getName(); if (m_logger.isDebugEnabled()) m_logger.debug("Reading bdoc siganture: " + m_fileName); boolean bExists = false; for (int j = 0; j < lSigFnames.size(); j++) { String s1 = (String) lSigFnames.get(j); if (s1.equals(m_fileName)) bExists = true; } if (bExists) { m_logger.error("Duplicate signature filename: " + m_fileName); handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML, "Duplicate signature filename: " + m_fileName, null)); } else lSigFnames.add(m_fileName); SAXParser saxParser = factory.newSAXParser(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int n = 0; byte[] data = new byte[2048]; while ((n = isEntry.read(data)) > 0) bos.write(data, 0, n); data = bos.toByteArray(); bos = null; if (m_logger.isDebugEnabled()) m_logger.debug( "Parsing bdoc: " + m_fileName + " size: " + ((data != null) ? data.length : 0)); saxParser.parse(new SignatureInputStream(new ByteArrayInputStream(data)), this); if (m_logger.isDebugEnabled()) m_logger.debug("Parsed bdoc: " + m_fileName); Signature sig1 = m_doc.getLastSignature(); m_sigComment = ze.getComment(); if (sig1 != null) { sig1.setPath(m_fileName); sig1.setComment(ze.getComment()); } } else { // probably a data file if (m_logger.isDebugEnabled()) m_logger.debug("Read data file: " + ze.getName()); if (!ze.isDirectory()) { boolean bExists = false; for (int j = 0; j < lDataFnames.size(); j++) { String s1 = (String) lDataFnames.get(j); if (s1.equals(ze.getName())) bExists = true; } if (bExists) { m_logger.error("Duplicate datafile filename: " + ze.getName()); handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML, "Duplicate datafile filename: " + ze.getName(), null)); } else lDataFnames.add(ze.getName()); DataFile df = m_doc.findDataFileById(ze.getName()); if (df != null) { if (ze.getSize() > 0) df.setSize(ze.getSize()); df.setContentType(DataFile.CONTENT_BINARY); df.setFileName(ze.getName()); } else { df = new DataFile(ze.getName(), DataFile.CONTENT_BINARY, ze.getName(), "application/binary", m_doc); if (m_doc.getDataFiles() == null) m_doc.setDataFiles(new ArrayList()); m_doc.getDataFiles().add(df); //m_doc.addDataFile(df); // this does some intiailization work unnecessary here } // enable caching if requested if (isEntry != null) df.setOrCacheBodyAndCalcHashes(isEntry); df.setComment(ze.getComment()); df.setLastModDt(new Date(ze.getTime())); // fix mime type according to DataObjectFormat Signature sig1 = m_doc.getLastSignature(); if (sig1 != null) { Reference dRef = sig1.getSignedInfo().getReferenceForDataFile(df); if (dRef != null) { DataObjectFormat dof = sig1.getSignedInfo() .getDataObjectFormatForReference(dRef); if (dof != null) { df.setMimeType(dof.getMimeType()); } } } } } if (fTmp != null) { fTmp.delete(); fTmp = null; } } // while zip entries if (!bHasMimetype) { m_logger.error("No mimetype file"); handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML, "Not a BDOC format file! No mimetype file!", null)); } // if no signatures exist then copy mime-type from manifest.xml to DataFile -s if (m_doc.countSignatures() == 0) { for (int i = 0; i < m_doc.countDataFiles(); i++) { DataFile df = m_doc.getDataFile(i); if (m_doc.getManifest() != null) { for (int j = 0; j < m_doc.getManifest().getNumFileEntries(); j++) { ManifestFileEntry mfe = m_doc.getManifest().getFileEntry(j); if (mfe.getFullPath() != null && mfe.getFullPath().equals(df.getFileName())) { df.setMimeType(mfe.getMediaType()); } // if fullpath } // for } // if } // for i } } else { // ddoc parsing if (m_logger.isDebugEnabled()) m_logger.debug("Reading ddoc: " + fname + " file: " + m_fileName); m_fileName = fname; SAXParser saxParser = factory.newSAXParser(); if (fname != null) saxParser.parse(new SignatureInputStream(new FileInputStream(fname)), this); else if (isSdoc != null) saxParser.parse(isSdoc, this); } } catch (org.xml.sax.SAXParseException ex) { m_logger.error("SAX Error: " + ex); handleError(ex); } catch (Exception ex) { m_logger.error("Error reading3: " + ex); ex.printStackTrace(); /*if(ex instanceof DigiDocException){ DigiDocException dex = (DigiDocException)ex; m_logger.error("Dex: " + ex); if(dex.getNestedException() != null) { dex.getNestedException().printStackTrace(); m_logger.error("Trace: "); } }*/ handleError(ex); } finally { // cleanup try { if (isEntry != null) { isEntry.close(); isEntry = null; } if (zis != null) zis.close(); if (zf != null) zf.close(); if (fTmp != null) { fTmp.delete(); fTmp = null; } } catch (Exception ex) { m_logger.error("Error closing streams and files: " + ex); } } // compare Manifest and DataFiles boolean bErrList = (errs != null); if (errs == null) errs = new ArrayList(); boolean bOk = DigiDocVerifyFactory.verifyManifestEntries(m_doc, errs); if (m_doc == null) { m_logger.error("Error reading4: doc == null"); handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML, "This document is not in ddoc or bdoc format", null)); } if (!bErrList && errs.size() > 0) { // if error list was not used then we have to throw exception. So we will throw the first one since we can only do it once DigiDocException ex = (DigiDocException) errs.get(0); throw ex; } return m_doc; }
From source file:com.anysoftkeyboard.ui.settings.wordseditor.RestoreUserWordsAsyncTask.java
@Override protected Void doAsyncTask(Void[] params) throws Exception { final Fragment owner = getOwner(); if (owner == null) return null; final Context context = owner.getContext(); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); final FileInputStream fileInputStream = new FileInputStream(new File(getBackupFolder(context), mFilename)); try {/*from w w w . j a va 2 s .co m*/ parser.parse(fileInputStream, new DefaultHandler() { private boolean mInWord = false; private int mFreq = 1; private String mWord = ""; @Override public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); if (mInWord) { mWord += new String(ch, start, length); } } @Override public void startElement(String uri, String localName, String qualifiedName, Attributes attributes) throws SAXException { super.startElement(uri, localName, qualifiedName, attributes); if (localName.equals("w")) { mInWord = true; mWord = ""; mFreq = Integer.parseInt(attributes.getValue("f")); } if (localName.equals("wordlist")) { mLocale = attributes.getValue("locale"); Logger.d(TAG, "Building dictionary for locale " + mLocale); if (mDictionary != null) { mDictionary.close(); } mDictionary = new UserDictionary(context, mLocale); mDictionary.loadDictionary(); Logger.d(TAG, "Starting restore to locale " + mLocale); } } @Override public void endElement(String uri, String localName, String qualifiedName) throws SAXException { if (mInWord && localName.equals("w")) { if (!TextUtils.isEmpty(mWord)) { Logger.d(TAG, "Restoring mWord '" + mWord + "' with mFreq " + mFreq); // Disallow duplicates mDictionary.deleteWord(mWord); mDictionary.addWord(mWord, mFreq); } mInWord = false; } super.endElement(uri, localName, qualifiedName); } }); } finally { fileInputStream.close(); } return null; }
From source file:com.jiahuan.svgmapview.core.helper.map.SVGParser.java
static SVG parse(InputSource data, SVGHandler handler) throws SVGParseException { try {/*from w w w .j av a2s . c o m*/ final Picture picture = new Picture(); handler.setPicture(picture); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(handler); xr.setFeature("http://xml.org/sax/features/validation", false); if (DISALLOW_DOCTYPE_DECL) { try { xr.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); } catch (SAXNotRecognizedException e) { DISALLOW_DOCTYPE_DECL = false; } } xr.parse(data); SVG result = new SVG(picture, handler.bounds); // Skip bounds if it was an empty pic if (!Float.isInfinite(handler.limits.top)) { result.setLimits(handler.limits); } return result; } catch (Exception e) { Log.e(TAG, "Failed to parse SVG.", e); throw new SVGParseException(e); } }
From source file:net.sourceforge.seqware.common.util.workflowtools.WorkflowTools.java
private HashMap<String, HashMap<String, String>> parseLog(File failedJobLogFile) { int tries = 20; while (tries >= 0) { tries--;/*from w ww . ja v a2 s . c o m*/ if (failedJobLogFile != null && failedJobLogFile.exists() && failedJobLogFile.canRead()) { try { if (failedJobLogFile.length() <= 0) { Logger.getLogger(WorkflowTools.class.getName()).log(Level.SEVERE, "empty file: " + failedJobLogFile.getAbsolutePath()); return new HashMap<String, HashMap<String, String>>(); } Log.info(" + Parsing file: " + failedJobLogFile.getAbsolutePath()); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); // inner class to handle parsing LogDefaultHandler handler = new LogDefaultHandler(); saxParser.parse(failedJobLogFile.getAbsoluteFile(), handler); return (handler.getData()); } catch (IOException ex) { ex.printStackTrace(); Logger.getLogger(WorkflowTools.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { ex.printStackTrace(); Logger.getLogger(WorkflowTools.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { ex.printStackTrace(); Logger.getLogger(WorkflowTools.class.getName()).log(Level.SEVERE, null, ex); } } // sleep try { Thread.sleep(6000); } catch (InterruptedException ex) { Log.error("Threw interrupt exception during parseLog: " + ex.getMessage()); } } return (null); }
From source file:net.stuxcrystal.simpledev.configuration.parser.generators.xml.XMLParser.java
/** * Creates a new SAX-Parser.//from w ww .ja va2 s.c o m * @return The new sax parser. * @throws ParserConfigurationException If we failed to create anew SAX-Parser. * @throws SAXException If we failed to create anew SAX-Parser. */ private static SAXParser getParser() throws ParserConfigurationException, SAXException { SAXParserFactory factory = SAXParserFactory.newInstance(); return factory.newSAXParser(); }
From source file:net.timewalker.ffmq4.utils.xml.XMLDescriptorReader.java
/** * Read and parse an XML descriptor file *//* ww w . j a v a 2 s .com*/ public AbstractDescriptor read(File descriptorFile, Class<? extends AbstractXMLDescriptorHandler> handlerClass) throws JMSException { if (!descriptorFile.canRead()) throw new FFMQException("Can't read descriptor file : " + descriptorFile.getAbsolutePath(), "FS_ERROR"); log.debug("Parsing descriptor : " + descriptorFile.getAbsolutePath()); AbstractXMLDescriptorHandler handler; try { // Create an handler instance handler = handlerClass.newInstance(); // Parse the descriptor file SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); FileInputStream in = new FileInputStream(descriptorFile); parser.parse(in, handler); in.close(); } catch (Exception e) { throw new FFMQException("Cannot parse descriptor file : " + descriptorFile.getAbsolutePath(), "PARSE_ERROR", e); } AbstractDescriptor descriptor = handler.getDescriptor(); descriptor.setDescriptorFile(descriptorFile); return descriptor; }