List of usage examples for javax.xml.parsers ParserConfigurationException printStackTrace
public void printStackTrace()
From source file:pt.aptoide.backupapps.data.webservices.ManagerUploads.java
public EnumServerLoginStatus login(ViewServerLogin serverLogin) { EnumServerLoginStatus status = EnumServerLoginStatus.LOGIN_SERVICE_UNAVAILABLE; String endpointString;/*w w w . j a va 2 s . c om*/ if (serverLogin.getRepoName() == null) { endpointString = String.format(Constants.URI_FORMAT_LOGIN_DEFAULT_REPO_WS, URLEncoder.encode(serverLogin.getUsername()), URLEncoder.encode(serverLogin.getPasshash())); } else { endpointString = String.format(Constants.URI_FORMAT_LOGIN_WS, URLEncoder.encode(serverLogin.getUsername()), URLEncoder.encode(serverLogin.getPasshash()), URLEncoder.encode(serverLogin.getRepoName())); } Log.d("Aptoide-ManagerUploads login", endpointString); try { URL endpoint = new URL(endpointString); HttpURLConnection connection = (HttpURLConnection) endpoint.openConnection(); //Careful with UnknownHostException. Throws MalformedURLException, IOException connection.setConnectTimeout(Constants.SERVER_CONNECTION_TIMEOUT); connection.setReadTimeout(Constants.SERVER_READ_TIMEOUT); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // connection.setConnectTimeout(TIME_OUT); connection.setRequestProperty("User-Agent", getUserAgentString()); status = serviceData.getManagerXml().dom.parseServerLoginReturn(connection); if (status.equals(EnumServerLoginStatus.SUCCESS)) { serviceData.getManagerPreferences() .setServerLogin(new ViewLogin(serverLogin.getUsername(), serverLogin.getPasshash())); } } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return status; }
From source file:pt.aptoide.backupapps.data.webservices.ManagerUploads.java
public EnumServerAddAppVersionLikeStatus addAppVersionLike(String repoName, int appHashid, boolean like) { //TODO create ViewLike from args EnumServerAddAppVersionLikeStatus status = EnumServerAddAppVersionLikeStatus.SERVICE_UNAVAILABLE; String token = serviceData.getManagerPreferences().getToken(); //TODO add support for multiple servers String endpointString;// w w w . j a v a 2 s . com if (like) { endpointString = String.format(Constants.URI_FORMAT_ADD_LIKE_WS, URLEncoder.encode(token), URLEncoder.encode(repoName), URLEncoder.encode(Integer.toString(appHashid))); } else { endpointString = String.format(Constants.URI_FORMAT_ADD_DISLIKE_WS, URLEncoder.encode(token), URLEncoder.encode(repoName), URLEncoder.encode(Integer.toString(appHashid))); } Log.d("Aptoide-ManagerUploads addLike: ", endpointString); try { URL endpoint = new URL(endpointString); HttpURLConnection connection = (HttpURLConnection) endpoint.openConnection(); //Careful with UnknownHostException. Throws MalformedURLException, IOException connection.setConnectTimeout(Constants.SERVER_CONNECTION_TIMEOUT); connection.setReadTimeout(Constants.SERVER_READ_TIMEOUT); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // connection.setConnectTimeout(TIME_OUT); // connection.setRequestProperty("User-Agent", getUserAgentString()); status = serviceData.getManagerXml().dom.parseAddAppVersionLikeReturn(connection); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return status; }
From source file:pt.aptoide.backupapps.data.webservices.ManagerUploads.java
public EnumServerAddAppVersionCommentStatus addAppVersionComment(String repoName, int appHashid, String commentBody, String subject, long answerTo) { //TODO create ViewComment from args EnumServerAddAppVersionCommentStatus status = EnumServerAddAppVersionCommentStatus.SERVICE_UNAVAILABLE; String token = serviceData.getManagerPreferences().getToken(); //TODO add support for multiple servers try {//from w ww. jav a 2 s . c om URL endpoint = new URL(Constants.URI_ADD_COMMENT_POST_WS); HttpURLConnection connection = (HttpURLConnection) endpoint.openConnection();//Careful with UnknownHostException connection.setConnectTimeout(Constants.SERVER_CONNECTION_TIMEOUT); connection.setReadTimeout(Constants.SERVER_READ_TIMEOUT); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept", "application/xml"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // connection.setRequestProperty("User-Agent", getUserAgentString()); //Variable definition StringBuilder postArguments = new StringBuilder(); postArguments.append(URLEncoder.encode("token", "UTF-8") + "=" + URLEncoder.encode(token, "UTF-8")); postArguments .append("&" + URLEncoder.encode("repo", "UTF-8") + "=" + URLEncoder.encode(repoName, "UTF-8")); postArguments.append( "&" + URLEncoder.encode("apkid", "UTF-8") + "=" + URLEncoder.encode("apphashid", "UTF-8")); postArguments.append("&" + URLEncoder.encode("apkversion", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(appHashid), "UTF-8")); postArguments.append( "&" + URLEncoder.encode("text", "UTF-8") + "=" + URLEncoder.encode(commentBody, "UTF-8")); String language = serviceData.getResources().getConfiguration().locale.getLanguage() + "_" + serviceData.getResources().getConfiguration().locale.getCountry(); Log.d("Aptoide-ManagerUploads", "addAppVersionComment, language: " + language); postArguments .append("&" + URLEncoder.encode("lang", "UTF-8") + "=" + URLEncoder.encode(language, "UTF-8")); if (answerTo != Constants.EMPTY_INT) { postArguments.append("&" + URLEncoder.encode("answerto", "UTF-8") + "=" + URLEncoder.encode(Long.toString(answerTo), "UTF-8")); } if (subject != null && subject.length() != 0) { postArguments.append( "&" + URLEncoder.encode("subject", "UTF-8") + "=" + URLEncoder.encode(subject, "UTF-8")); } postArguments .append("&" + URLEncoder.encode("mode", "UTF-8") + "=" + URLEncoder.encode("xml", "UTF-8")); connection.setDoOutput(true); connection.setDoInput(true); OutputStreamWriter output = new OutputStreamWriter(connection.getOutputStream()); output.write(postArguments.toString()); output.flush(); status = serviceData.getManagerXml().dom.parseAddAppVersionCommentReturn(connection); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return status; }
From source file:robert843.o2.pl.player.LocalPlayback.java
@Override public void play(QueueItem item) { mPlayOnFocusGain = true;/*from w w w. j a va2s . co m*/ tryToGetAudioFocus(); registerAudioNoisyReceiver(); String mediaId = item.getDescription().getMediaId(); boolean mediaHasChanged = !TextUtils.equals(mediaId, mCurrentMediaId); if (mediaHasChanged) { mCurrentPosition = 0; mCurrentMediaId = mediaId; } if (mState == PlaybackState.STATE_PAUSED && !mediaHasChanged && mMediaPlayer != null) { configMediaPlayerState(); } else { mState = PlaybackState.STATE_STOPPED; relaxResources(false); // release everything except MediaPlayer final MediaMetadata track = mMusicProvider .getMusic(MediaIDHelper.extractMusicIDFromMediaID(item.getDescription().getMediaId())); String source = track.getString(MusicProvider.CUSTOM_METADATA_TRACK_SOURCE); // Asynchronously load the music catalog in a separate thread new AsyncTask<Void, Void, MovieParser>() { @Override protected MovieParser doInBackground(Void... params) { MovieParser parser = new MovieParser(track.getString("id")); try { parser.parse(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return parser; } @Override protected void onPostExecute(MovieParser current) { createMediaPlayerIfNeeded(); mState = PlaybackState.STATE_BUFFERING; mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mMediaPlayer.setDataSource(current.getUrl()); } catch (IOException e) { e.printStackTrace(); } // Starts preparing the media player in the background. When // it's done, it will call our OnPreparedListener (that is, // the onPrepared() method on this class, since we set the // listener to 'this'). Until the media player is prepared, // we *cannot* call start() on it! mMediaPlayer.prepareAsync(); // If we are streaming from the internet, we want to hold a // Wifi lock, which prevents the Wifi radio from going to // sleep while the song is playing. mWifiLock.acquire(); if (mCallback != null) { mCallback.onPlaybackStatusChanged(mState); } } }.execute(); } }
From source file:shiec.secondBlock.RegisterGenerator.java
/** * Generate XML data out of request InputStream. * @throws SAXException //from w w w . ja v a 2s. c om */ public void generate() throws IOException, SAXException, ProcessingException { System.out.println("getting in..."); SAXParser parser = null; int len = 0; String contentType; Request request = ObjectModelHelper.getRequest(this.objectModel); try { contentType = request.getContentType(); if (contentType == null) { contentType = parameters.getParameter("defaultContentType", null); if (getLogger().isDebugEnabled()) { getLogger().debug("no Content-Type header - using contentType parameter: " + contentType); } if (contentType == null) { throw new IOException("Both Content-Type header and defaultContentType parameter are not set"); } } InputSource source; if (contentType.startsWith("application/x-www-form-urlencoded") || contentType.startsWith("multipart/form-data")) { String parameter = parameters.getParameter(FORM_NAME, null); if (parameter == null) { throw new ProcessingException("StreamGenerator expects a sitemap parameter called '" + FORM_NAME + "' for handling form data"); } Object xmlObject = request.get(parameter); Reader xmlReader; if (xmlObject instanceof String) { xmlReader = new StringReader((String) xmlObject); } else if (xmlObject instanceof Part) { xmlReader = new InputStreamReader(((Part) xmlObject).getInputStream()); } else { throw new ProcessingException( "Unknown request object encountered named " + parameter + " : " + xmlObject); } source = new InputSource(xmlReader); } else if (contentType.startsWith("text/plain") || contentType.startsWith("text/xml") || contentType.startsWith("application/xhtml+xml") || contentType.startsWith("application/xml")) { HttpServletRequest httpRequest = (HttpServletRequest) objectModel .get(HttpEnvironment.HTTP_REQUEST_OBJECT); if (httpRequest == null) { throw new ProcessingException("This feature is only available in an http environment."); } len = request.getContentLength(); if (len <= 0) { throw new IOException("getContentLen() == 0"); } PostInputStream anStream = new PostInputStream(httpRequest.getInputStream(), len); source = new InputSource(anStream); } else { throw new IOException("Unexpected getContentType(): " + request.getContentType()); } if (getLogger().isDebugEnabled()) { getLogger().debug("Processing stream ContentType=" + contentType + " ContentLength=" + len); } String charset = getCharacterEncoding(request, contentType); if (charset != null) { source.setEncoding(charset); } String path = "D:/Java/kepler/workspace/secondBlock/src/main/resources/COB-INF/database/"; //String path = "../database/"; File file = new File(path + "description.xml"); if (!file.exists()) { try { file.createNewFile(); System.out.println("creating new description file..."); } catch (IOException e) { e.printStackTrace(); } } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(source); String fileName = "";//the name of the description file. Get from the description. NodeList nodeList = doc.getElementsByTagName("spec"); Node root = nodeList.item(0); fileName = ((Element) root).getAttribute("name"); File newFile = new File(path + fileName + ".xml"); if (!newFile.exists()) { DOMSource src = new DOMSource(doc); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); StreamResult result = new StreamResult(file); transformer.transform(src, result); System.out.println("Transforming..."); FileUtils.copyFile(file, newFile); file.delete(); String changePath = "D:/Java/kepler/workspace/secondBlock/src/main/resources/COB-INF/demo/"; File changeFile = new File(changePath + "deviceList.xml"); System.out.println("Reading file..."); DocumentBuilderFactory changeFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder changeBuilder = changeFactory.newDocumentBuilder(); Document changeDoc = changeBuilder.parse(changeFile); Element toAdd = changeDoc.createElement("Device"); toAdd.setAttribute("id", fileName); Element var = changeDoc.createElement("Name"); var.setTextContent(fileName); toAdd.appendChild(var); changeDoc.getFirstChild().appendChild(toAdd); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transform = tFactory.newTransformer(); //transform.setOutputProperty(OutputKeys.INDENT,"yes"); DOMSource domSource = new DOMSource(changeDoc); StreamResult domResult = new StreamResult(new FileOutputStream(changeFile)); transform.transform(domSource, domResult); } } catch (IOException e) { getLogger().error("StreamGenerator.generate()", e); throw new ResourceNotFoundException("StreamGenerator could not find resource", e); } catch (SAXException e) { getLogger().error("StreamGenerator.generate()", e); throw (e); } catch (ParserConfigurationException e1) { e1.printStackTrace(); } catch (TransformerConfigurationException e1) { e1.printStackTrace(); } catch (TransformerException e1) { e1.printStackTrace(); } finally { this.manager.release(parser); } }
From source file:shnakkydoodle.measuring.provider.MetricsProviderSQLServer.java
/** * Get all scripts to be run to create logging db tables with procs and * constraints Execute each scripts/* ww w. j av a 2s . c om*/ */ private void ProcessConfigFile() { try { InputStream in = getClass() .getResourceAsStream("shnakkydoodle/measuring/provider/resources/config.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(in); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("resourcepath"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String resourcePath = eElement.getTextContent(); // Read in script and execute if (ReadExecuteScript(resourcePath)) { System.out.println("Successfully created: " + resourcePath); } else { System.err.println("Failed on creating: " + resourcePath); } } } } catch (ParserConfigurationException e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); e.printStackTrace(); } catch (SAXException e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); e.printStackTrace(); } }
From source file:threadapp.Thread.java
public void save() throws TransformerException { // 1. Convert Thread object to XML // 2. Write to file try {//from ww w . j a v a 2s .c o m DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // Add root element thread Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("thread"); rootElement.setAttribute("title", this.title); doc.appendChild(rootElement); // Add post elements if (posts != null) { for (int i = 0; i < this.posts.length; i++) { Element post = doc.createElement("post"); post.setAttribute("timestamp", Integer.toString(this.posts[i].timestamp)); post.appendChild(doc.createTextNode(this.posts[i].content)); rootElement.appendChild(post); } } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("threads/" + getFilename(id))); // Output to console for testing //StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } }
From source file:tw.edu.chit.struts.action.portfolio.ConnectorServlet.java
/** * Manage the Get requests (GetFolders, GetFoldersAndFiles, CreateFolder).<br> * * The servlet accepts commands sent in the following format:<br> * connector?Command=CommandName&Type=ResourceType&CurrentFolder=FolderPath<br><br> * It execute the command and then return the results to the client in XML format. * *//*w w w . j a va2s . com*/ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (debug) System.out.println("--- BEGIN DOGET ---"); response.setContentType("text/xml; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); String currentPath = baseDir + typeStr + currentFolderStr; String currentDirPath = getServletContext().getRealPath(currentPath); File currentDir = new File(currentDirPath); if (!currentDir.exists()) { currentDir.mkdir(); } Document document = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.newDocument(); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } Node root = CreateCommonXml(document, commandStr, typeStr, currentFolderStr, request.getContextPath() + currentPath); if (debug) System.out.println("Command = " + commandStr); if (commandStr.equals("GetFolders")) { getFolders(currentDir, root, document); } else if (commandStr.equals("GetFoldersAndFiles")) { getFolders(currentDir, root, document); getFiles(currentDir, root, document); } else if (commandStr.equals("CreateFolder")) { String newFolderStr = request.getParameter("NewFolderName"); File newFolder = new File(currentDir, newFolderStr); String retValue = "110"; if (newFolder.exists()) { retValue = "101"; } else { try { boolean dirCreated = newFolder.mkdir(); if (dirCreated) retValue = "0"; else retValue = "102"; } catch (SecurityException sex) { retValue = "103"; } } setCreateFolderResponse(retValue, root, document); } document.getDocumentElement().normalize(); try { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(out); transformer.transform(source, result); if (debug) { StreamResult dbgResult = new StreamResult(System.out); transformer.transform(source, dbgResult); System.out.println(""); System.out.println("--- END DOGET ---"); dbgResult = null; } } catch (Exception ex) { ex.printStackTrace(); } out.flush(); out.close(); }
From source file:us.mn.state.health.lims.reports.action.AuditTrailReportBySampleProcessAction.java
private void parseXmlFile(String xml) { //get the factory DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try {/*from www. ja v a2 s . c o m*/ //Using factory get an instance of document builder DocumentBuilder db = dbf.newDocumentBuilder(); //parse using builder to get DOM representation of the XML file Document dom = db.parse(xml); System.out.println("This is parsed xml getting changes " + dom.getElementById("accessionNumber")); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (SAXException se) { se.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } }
From source file:ws.argo.AsynchListener.AsynchListener.java
private ArrayList<ServiceInfoBean> parseProbeResponseXML(String xmlString) throws SAXException, IOException { ArrayList<ServiceInfoBean> serviceList = new ArrayList<ServiceInfoBean>(); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setCoalescing(true);// www . j a v a2s. c o m DocumentBuilder builder = null; try { builder = builderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } InputStream is = IOUtils.toInputStream(xmlString); Document document = builder.parse(is); NodeList list = document.getElementsByTagName("service"); for (int i = 0; i < list.getLength(); i++) { Element service = (Element) list.item(i); String contractID = null; String serviceID = null; contractID = service.getAttribute("contractID"); serviceID = service.getAttribute("id"); ServiceInfoBean config = new ServiceInfoBean(serviceID); config.serviceContractID = contractID; // Need some better error handling here. The xml MUST have all config items in it // or bad things happen. Node n; n = service.getElementsByTagName("ipAddress").item(0); config.ipAddress = ((Element) n).getTextContent(); n = service.getElementsByTagName("port").item(0); config.port = ((Element) n).getTextContent(); n = service.getElementsByTagName("url").item(0); config.url = ((Element) n).getTextContent(); n = service.getElementsByTagName("data").item(0); config.data = ((Element) n).getTextContent(); n = service.getElementsByTagName("description").item(0); config.description = ((Element) n).getTextContent(); n = service.getElementsByTagName("contractDescription").item(0); config.contractDescription = ((Element) n).getTextContent(); n = service.getElementsByTagName("serviceName").item(0); config.serviceName = ((Element) n).getTextContent(); n = service.getElementsByTagName("consumability").item(0); config.consumability = ((Element) n).getTextContent(); n = service.getElementsByTagName("ttl").item(0); config.ttl = Integer.decode(((Element) n).getTextContent()); serviceList.add(config); } return serviceList; }