List of usage examples for org.apache.commons.lang3 StringUtils substringBetween
public static String substringBetween(final String str, final String open, final String close)
Gets the String that is nested in between two Strings.
From source file:com.denimgroup.threadfix.importer.impl.upload.ClangChannelImporter.java
private Calendar getImportTime() { InputStream indexHtml = getFileFromZip("index.html"); if (indexHtml == null) return null; try {/*from w ww. ja va 2 s .com*/ String s = IOUtils.toString(indexHtml); String sDate = StringUtils.substringBetween(s, "<tr><th>Date:</th><td>", "</td></tr>"); // Mon Aug 4 13:18:00 2014 return DateUtils.getCalendarFromString("EEE MMM dd HH:mm:ss yyyy", sDate); } catch (IOException e) { log.error("IOException reading inputstream index.html in getTestDate(indexHtml)", e); return null; } }
From source file:com.searchbox.collection.oppfin.TopicCollection.java
/** * Load HTML page and extract the part with the description * * @param topicFileName The topic identifier in the URL * @return The html markup that corresponds to the description *//*from ww w. j a v a 2s. co m*/ private String getTopicDescription(String topicFileName) { LOGGER.info("Loading topic description [" + topicFileName + "]"); String topicUrlDetail = String.format(env.getProperty(TOPIC_DETAIL_URL, TOPIC_DETAIL_URL_DEFAULT), topicFileName); //TODO fix bug LOGGER.info("Loading topic loadFromUrl [" + topicUrlDetail + "]"); String desc = StringUtils.substringBetween(this.loadFromUrl(topicUrlDetail), env.getProperty(TOPIC_DETAIL_BEGIN, TOPIC_DETAIL_BEGIN_DEFAULT), env.getProperty(TOPIC_DETAIL_END, TOPIC_DETAIL_END_DEFAULT)); if (desc == null) { String tagOpen = "<div class=\"more-block\">"; String tagEnd = env.getProperty(TOPIC_DETAIL_END, TOPIC_DETAIL_END_DEFAULT); desc = StringUtils.substringBetween(this.loadFromUrl(topicUrlDetail), tagOpen, tagEnd); } if (desc != null) { desc = desc.trim(); } else { desc = "cannot get Description"; } return desc; }
From source file:com.netflix.dyno.jedis.DynoJedisPipeline.java
/** * Checks that a pipeline is associated with a single key. If there is a hashtag * defined in the first host of the connectionpool then we check that first. * //from w w w . ja v a 2 s . c om * @param key */ private void checkKey(final String key) { /* * Get hashtag from the first host of the active pool We cannot use the * connection object because as of now we have not selected a connection. A * connection is selected based on the key or hashtag respectively. */ String hashtag = connPool.getConfiguration().getHashtag(); if (hashtag == null || hashtag.isEmpty()) { if (theKey.get() != null) { verifyKey(key); } else { boolean success = theKey.compareAndSet(null, key); if (!success) { // someone already beat us to it. that's fine, just verify // that the key is the same verifyKey(key); } else { pipelined(key); } } } else { /* * We have a identified a hashtag in the Host object. That means Dynomite has a * defined hashtag. Producing the hashvalue out of the hashtag and using that as * a reference to the pipeline */ String hashValue = StringUtils.substringBetween(key, Character.toString(hashtag.charAt(0)), Character.toString(hashtag.charAt(1))); checkHashtag(key, hashValue); } }
From source file:net.pms.network.RequestV2.java
/** * Construct a proper HTTP response to a received request. After the response has been * created, it is sent and the resulting {@link ChannelFuture} object is returned. * See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">RFC-2616</a> * for HTTP header field definitions./* w ww . ja v a 2 s . co m*/ * @param output The {@link HttpResponse} object that will be used to construct the response. * @param e The {@link MessageEvent} object used to communicate with the client that sent * the request. * @param close Set to true to close the channel after sending the response. By default the * channel is not closed after sending. * @param startStopListenerDelegate The {@link StartStopListenerDelegate} object that is used * to notify plugins that the {@link DLNAResource} is about to start playing. * @return The {@link ChannelFuture} object via which the response was sent. * @throws IOException */ public ChannelFuture answer(HttpResponse output, MessageEvent e, final boolean close, final StartStopListenerDelegate startStopListenerDelegate) throws IOException { ChannelFuture future = null; long CLoverride = -2; // 0 and above are valid Content-Length values, -1 means omit StringBuilder response = new StringBuilder(); DLNAResource dlna = null; boolean xbox = mediaRenderer.isXBOX(); // Samsung 2012 TVs have a problematic preceding slash that needs to be removed. if (argument.startsWith("/")) { logger.trace("Stripping preceding slash from: " + argument); argument = argument.substring(1); } if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("console/")) { // Request to output a page to the HTML console. output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html"); response.append(HTMLConsole.servePage(argument.substring(8))); } else if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("get/")) { // Request to retrieve a file /* * skip the leading "get/" and extract the * resource ID from the first path element * e.g. "get/0$1$5$3$4/Foo.mp4" -> "0$1$5$3$4" * * ExSport: I spotted on Android it is asking for "/get/0$2$4$2$1$3" */ String id = StringUtils.substringBetween(argument, "get/", "/"); // Some clients escape the separators in their request: unescape them. id = id.replace("%24", "$"); // Retrieve the DLNA resource itself. List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(id, false, 0, 0, mediaRenderer); if (transferMode != null) { output.setHeader("TransferMode.DLNA.ORG", transferMode); } if (files.size() == 1) { // DLNAresource was found. dlna = files.get(0); String fileName = argument.substring(argument.lastIndexOf("/") + 1); if (fileName.startsWith("thumbnail0000")) { // This is a request for a thumbnail file. output.setHeader(HttpHeaders.Names.CONTENT_TYPE, dlna.getThumbnailContentType()); output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes"); output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT"); output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive"); if (mediaRenderer.isMediaParserV2()) { dlna.checkThumbnail(); } inputStream = dlna.getThumbnailInputStream(); } else if (fileName.indexOf("subtitle0000") > -1) { // This is a request for a subtitle file output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain"); output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT"); List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitleTracksList(); if (subs != null && !subs.isEmpty()) { // TODO: maybe loop subs to get the requested subtitle type instead of using the first one DLNAMediaSubtitle sub = subs.get(0); if (sub.isExternal()) { inputStream = new java.io.FileInputStream(sub.getExternalFile()); } } } else { // This is a request for a regular file. // If range has not been initialized yet and the DLNAResource has its // own start and end defined, initialize range with those values before // requesting the input stream. Range.Time splitRange = dlna.getSplitRange(); if (range.getStart() == null && splitRange.getStart() != null) { range.setStart(splitRange.getStart()); } if (range.getEnd() == null && splitRange.getEnd() != null) { range.setEnd(splitRange.getEnd()); } inputStream = dlna.getInputStream( Range.create(lowRange, highRange, range.getStart(), range.getEnd()), mediaRenderer); if (!configuration.isDisableSubtitles()) { // Some renderers (like Samsung devices) allow a custom header for a subtitle URL String subtitleHttpHeader = mediaRenderer.getSubtitleHttpHeader(); if (subtitleHttpHeader != null && !"".equals(subtitleHttpHeader)) { // Device allows a custom subtitle HTTP header; construct it List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitleTracksList(); if (subs != null && !subs.isEmpty()) { DLNAMediaSubtitle sub = subs.get(0); String subtitleUrl; String subExtension = sub.getType().getExtension(); if (isNotBlank(subExtension)) { subtitleUrl = "http://" + PMS.get().getServer().getHost() + ':' + PMS.get().getServer().getPort() + "/get/" + id + "/subtitle0000." + subExtension; } else { subtitleUrl = "http://" + PMS.get().getServer().getHost() + ':' + PMS.get().getServer().getPort() + "/get/" + id + "/subtitle0000"; } output.setHeader(subtitleHttpHeader, subtitleUrl); } } } String name = dlna.getDisplayName(mediaRenderer); if (inputStream == null) { // No inputStream indicates that transcoding / remuxing probably crashed. logger.error("There is no inputstream to return for " + name); } else { // Notify plugins that the DLNAresource is about to start playing startStopListenerDelegate.start(dlna); // Try to determine the content type of the file String rendererMimeType = getRendererMimeType(dlna.mimeType(), mediaRenderer); if (rendererMimeType != null && !"".equals(rendererMimeType)) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, rendererMimeType); } final DLNAMediaInfo media = dlna.getMedia(); if (media != null) { if (isNotBlank(media.getContainer())) { name += " [container: " + media.getContainer() + "]"; } if (isNotBlank(media.getCodecV())) { name += " [video: " + media.getCodecV() + "]"; } } PMS.get().getFrame().setStatusLine("Serving " + name); // Response generation: // We use -1 for arithmetic convenience but don't send it as a value. // If Content-Length < 0 we omit it, for Content-Range we use '*' to signify unspecified. boolean chunked = mediaRenderer.isChunkedTransfer(); // Determine the total size. Note: when transcoding the length is // not known in advance, so DLNAMediaInfo.TRANS_SIZE will be returned instead. long totalsize = dlna.length(mediaRenderer); if (chunked && totalsize == DLNAMediaInfo.TRANS_SIZE) { // In chunked mode we try to avoid arbitrary values. totalsize = -1; } long remaining = totalsize - lowRange; long requested = highRange - lowRange; if (requested != 0) { // Determine the range (i.e. smaller of known or requested bytes) long bytes = remaining > -1 ? remaining : inputStream.available(); if (requested > 0 && bytes > requested) { bytes = requested + 1; } // Calculate the corresponding highRange (this is usually redundant). highRange = lowRange + bytes - (bytes > 0 ? 1 : 0); logger.trace( (chunked ? "Using chunked response. " : "") + "Sending " + bytes + " bytes."); output.setHeader(HttpHeaders.Names.CONTENT_RANGE, "bytes " + lowRange + "-" + (highRange > -1 ? highRange : "*") + "/" + (totalsize > -1 ? totalsize : "*")); // Content-Length refers to the current chunk size here, though in chunked // mode if the request is open-ended and totalsize is unknown we omit it. if (chunked && requested < 0 && totalsize < 0) { CLoverride = -1; } else { CLoverride = bytes; } } else { // Content-Length refers to the total remaining size of the stream here. CLoverride = remaining; } // Calculate the corresponding highRange (this is usually redundant). highRange = lowRange + CLoverride - (CLoverride > 0 ? 1 : 0); if (contentFeatures != null) { output.setHeader("ContentFeatures.DLNA.ORG", dlna.getDlnaContentFeatures()); } output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes"); output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive"); } } } } else if ((method.equals("GET") || method.equals("HEAD")) && (argument.toLowerCase().endsWith(".png") || argument.toLowerCase().endsWith(".jpg") || argument.toLowerCase().endsWith(".jpeg"))) { if (argument.toLowerCase().endsWith(".png")) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/png"); } else { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/jpeg"); } output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes"); output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive"); output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT"); inputStream = getResourceInputStream(argument); } else if ((method.equals("GET") || method.equals("HEAD")) && (argument.equals("description/fetch") || argument.endsWith("1.0.xml"))) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\""); output.setHeader(HttpHeaders.Names.CACHE_CONTROL, "no-cache"); output.setHeader(HttpHeaders.Names.EXPIRES, "0"); output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes"); output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive"); inputStream = getResourceInputStream((argument.equals("description/fetch") ? "PMS.xml" : argument)); if (argument.equals("description/fetch")) { byte b[] = new byte[inputStream.available()]; inputStream.read(b); String s = new String(b); s = s.replace("[uuid]", PMS.get().usn()); //.substring(0, PMS.get().usn().length()-2)); String profileName = configuration.getProfileName(); if (PMS.get().getServer().getHost() != null) { s = s.replace("[host]", PMS.get().getServer().getHost()); s = s.replace("[port]", "" + PMS.get().getServer().getPort()); } if (xbox) { logger.debug("DLNA changes for Xbox 360"); s = s.replace("PS3 Media Server", "PS3 Media Server [" + profileName + "] : Windows Media Connect"); s = s.replace("<modelName>PMS</modelName>", "<modelName>Windows Media Connect</modelName>"); s = s.replace("<serviceList>", "<serviceList>" + CRLF + "<service>" + CRLF + "<serviceType>urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1</serviceType>" + CRLF + "<serviceId>urn:microsoft.com:serviceId:X_MS_MediaReceiverRegistrar</serviceId>" + CRLF + "<SCPDURL>/upnp/mrr/scpd</SCPDURL>" + CRLF + "<controlURL>/upnp/mrr/control</controlURL>" + CRLF + "</service>" + CRLF); } else { s = s.replace("PS3 Media Server", "PS3 Media Server [" + profileName + "]"); } if (!mediaRenderer.isPS3()) { // hacky stuff. replace the png icon by a jpeg one. Like mpeg2 remux, // really need a proper format compatibility list by renderer s = s.replace("<mimetype>image/png</mimetype>", "<mimetype>image/jpeg</mimetype>"); s = s.replace("/images/thumbnail-video-256.png", "/images/thumbnail-video-120.jpg"); s = s.replace(">256<", ">120<"); } response.append(s); inputStream = null; } } else if (method.equals("POST") && (argument.contains("MS_MediaReceiverRegistrar_control") || argument.contains("mrr/control"))) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\""); response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); if (soapaction != null && soapaction.contains("IsAuthorized")) { response.append(HTTPXMLHelper.XBOX_2); response.append(CRLF); } else if (soapaction != null && soapaction.contains("IsValidated")) { response.append(HTTPXMLHelper.XBOX_1); response.append(CRLF); } response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (method.equals("POST") && argument.endsWith("upnp/control/connection_manager")) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\""); if (soapaction != null && soapaction.indexOf("ConnectionManager:1#GetProtocolInfo") > -1) { response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.PROTOCOLINFO_RESPONSE); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } } else if (method.equals("POST") && argument.endsWith("upnp/control/content_directory")) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\""); if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSystemUpdateID") > -1) { response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_HEADER); response.append(CRLF); response.append("<Id>").append(DLNAResource.getSystemUpdateId()).append("</Id>"); response.append(CRLF); response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_FOOTER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#X_GetFeatureList") > -1) { // Added for Samsung 2012 TVs response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.UPNP_INVALID_ACTION); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSortCapabilities") > -1) { response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SORTCAPS_RESPONSE); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSearchCapabilities") > -1) { response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SEARCHCAPS_RESPONSE); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (soapaction != null && (soapaction.contains("ContentDirectory:1#Browse") || soapaction.contains("ContentDirectory:1#Search"))) { objectID = getEnclosingValue(content, "<ObjectID>", "</ObjectID>"); String containerID = null; if (isEmpty(objectID) && xbox) { containerID = getEnclosingValue(content, "<ContainerID>", "</ContainerID>"); if (containerID == null || !containerID.contains("$")) { objectID = "0"; } else { objectID = containerID; containerID = null; } } Object sI = getEnclosingValue(content, "<StartingIndex>", "</StartingIndex>"); Object rC = getEnclosingValue(content, "<RequestedCount>", "</RequestedCount>"); browseFlag = getEnclosingValue(content, "<BrowseFlag>", "</BrowseFlag>"); if (sI != null) { startingIndex = Integer.parseInt(sI.toString()); } if (rC != null) { requestCount = Integer.parseInt(rC.toString()); } response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) { response.append(HTTPXMLHelper.SEARCHRESPONSE_HEADER); } else { response.append(HTTPXMLHelper.BROWSERESPONSE_HEADER); } response.append(CRLF); response.append(HTTPXMLHelper.RESULT_HEADER); response.append(HTTPXMLHelper.DIDL_HEADER); if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) { browseFlag = "BrowseDirectChildren"; } // XBOX virtual containers ... d'oh! String searchCriteria = null; if (xbox && configuration.getUseCache() && PMS.get().getLibrary() != null && containerID != null) { if (containerID.equals("7") && PMS.get().getLibrary().getAlbumFolder() != null) { objectID = PMS.get().getLibrary().getAlbumFolder().getResourceId(); } else if (containerID.equals("6") && PMS.get().getLibrary().getArtistFolder() != null) { objectID = PMS.get().getLibrary().getArtistFolder().getResourceId(); } else if (containerID.equals("5") && PMS.get().getLibrary().getGenreFolder() != null) { objectID = PMS.get().getLibrary().getGenreFolder().getResourceId(); } else if (containerID.equals("F") && PMS.get().getLibrary().getPlaylistFolder() != null) { objectID = PMS.get().getLibrary().getPlaylistFolder().getResourceId(); } else if (containerID.equals("4") && PMS.get().getLibrary().getAllFolder() != null) { objectID = PMS.get().getLibrary().getAllFolder().getResourceId(); } else if (containerID.equals("1")) { String artist = getEnclosingValue(content, "upnp:artist = "", "")"); if (artist != null) { objectID = PMS.get().getLibrary().getArtistFolder().getResourceId(); searchCriteria = artist; } } } List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(objectID, browseFlag != null && browseFlag.equals("BrowseDirectChildren"), startingIndex, requestCount, mediaRenderer); if (searchCriteria != null && files != null) { for (int i = files.size() - 1; i >= 0; i--) { if (!files.get(i).getName().equals(searchCriteria)) { files.remove(i); } } if (files.size() > 0) { files = files.get(0).getChildren(); } } int minus = 0; if (files != null) { for (DLNAResource uf : files) { if (xbox && containerID != null) { uf.setFakeParentId(containerID); } if (uf.isCompatible(mediaRenderer) && (uf.getPlayer() == null || uf.getPlayer().isPlayerCompatible(mediaRenderer))) { response.append(uf.toString(mediaRenderer)); } else { minus++; } } } response.append(HTTPXMLHelper.DIDL_FOOTER); response.append(HTTPXMLHelper.RESULT_FOOTER); response.append(CRLF); int filessize = 0; if (files != null) { filessize = files.size(); } response.append("<NumberReturned>").append(filessize - minus).append("</NumberReturned>"); response.append(CRLF); DLNAResource parentFolder = null; if (files != null && filessize > 0) { parentFolder = files.get(0).getParent(); } if (browseFlag != null && browseFlag.equals("BrowseDirectChildren") && mediaRenderer.isMediaParserV2() && mediaRenderer.isDLNATreeHack()) { // with the new parser, files are parsed and analyzed *before* creating the DLNA tree, // every 10 items (the ps3 asks 10 by 10), // so we do not know exactly the total number of items in the DLNA folder to send // (regular files, plus the #transcode folder, maybe the #imdb one, also files can be // invalidated and hidden if format is broken or encrypted, etc.). // let's send a fake total size to force the renderer to ask following items int totalCount = startingIndex + requestCount + 1; // returns 11 when 10 asked if (filessize - minus <= 0) { // if no more elements, send the startingIndex totalCount = startingIndex; } response.append("<TotalMatches>").append(totalCount).append("</TotalMatches>"); } else if (browseFlag != null && browseFlag.equals("BrowseDirectChildren")) { response.append("<TotalMatches>") .append(((parentFolder != null) ? parentFolder.childrenNumber() : filessize) - minus) .append("</TotalMatches>"); } else { //from upnp spec: If BrowseMetadata is specified in the BrowseFlags then TotalMatches = 1 response.append("<TotalMatches>1</TotalMatches>"); } response.append(CRLF); response.append("<UpdateID>"); if (parentFolder != null) { response.append(parentFolder.getUpdateId()); } else { response.append("1"); } response.append("</UpdateID>"); response.append(CRLF); if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) { response.append(HTTPXMLHelper.SEARCHRESPONSE_FOOTER); } else { response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER); } response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); // logger.trace(response.toString()); } } else if (method.equals("SUBSCRIBE")) { output.setHeader("SID", PMS.get().usn()); output.setHeader("TIMEOUT", "Second-1800"); if (soapaction != null) { String cb = soapaction.replace("<", "").replace(">", ""); try { URL soapActionUrl = new URL(cb); String addr = soapActionUrl.getHost(); int port = soapActionUrl.getPort(); Socket sock = new Socket(addr, port); OutputStream out = sock.getOutputStream(); out.write(("NOTIFY /" + argument + " HTTP/1.1").getBytes()); out.write(CRLF.getBytes()); out.write(("SID: " + PMS.get().usn()).getBytes()); out.write(CRLF.getBytes()); out.write(("SEQ: " + 0).getBytes()); out.write(CRLF.getBytes()); out.write(("NT: upnp:event").getBytes()); out.write(CRLF.getBytes()); out.write(("NTS: upnp:propchange").getBytes()); out.write(CRLF.getBytes()); out.write(("HOST: " + addr + ":" + port).getBytes()); out.write(CRLF.getBytes()); out.flush(); out.close(); sock.close(); } catch (MalformedURLException ex) { logger.debug("Cannot parse address and port from soap action \"" + soapaction + "\"", ex); } } else { logger.debug("Expected soap action in request"); } if (argument.contains("connection_manager")) { response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ConnectionManager:1")); response.append(HTTPXMLHelper.eventProp("SinkProtocolInfo")); response.append(HTTPXMLHelper.eventProp("SourceProtocolInfo")); response.append(HTTPXMLHelper.eventProp("CurrentConnectionIDs")); response.append(HTTPXMLHelper.EVENT_FOOTER); } else if (argument.contains("content_directory")) { response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ContentDirectory:1")); response.append(HTTPXMLHelper.eventProp("TransferIDs")); response.append(HTTPXMLHelper.eventProp("ContainerUpdateIDs")); response.append(HTTPXMLHelper.eventProp("SystemUpdateID", "" + DLNAResource.getSystemUpdateId())); response.append(HTTPXMLHelper.EVENT_FOOTER); } } else if (method.equals("NOTIFY")) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml"); output.setHeader("NT", "upnp:event"); output.setHeader("NTS", "upnp:propchange"); output.setHeader("SID", PMS.get().usn()); output.setHeader("SEQ", "0"); response.append("<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">"); response.append("<e:property>"); response.append("<TransferIDs></TransferIDs>"); response.append("</e:property>"); response.append("<e:property>"); response.append("<ContainerUpdateIDs></ContainerUpdateIDs>"); response.append("</e:property>"); response.append("<e:property>"); response.append("<SystemUpdateID>").append(DLNAResource.getSystemUpdateId()) .append("</SystemUpdateID>"); response.append("</e:property>"); response.append("</e:propertyset>"); } output.setHeader("Server", PMS.get().getServerName()); if (response.length() > 0) { // A response message was constructed; convert it to data ready to be sent. byte responseData[] = response.toString().getBytes("UTF-8"); output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + responseData.length); // HEAD requests only require headers to be set, no need to set contents. if (!method.equals("HEAD")) { // Not a HEAD request, so set the contents of the response. ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseData); output.setContent(buf); } // Send the response to the client. future = e.getChannel().write(output); if (close) { // Close the channel after the response is sent. future.addListener(ChannelFutureListener.CLOSE); } } else if (inputStream != null) { // There is an input stream to send as a response. if (CLoverride > -2) { // Content-Length override has been set, send or omit as appropriate if (CLoverride > -1 && CLoverride != DLNAMediaInfo.TRANS_SIZE) { // Since PS3 firmware 2.50, it is wiser not to send an arbitrary Content-Length, // as the PS3 will display a network error and request the last seconds of the // transcoded video. Better to send no Content-Length at all. output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + CLoverride); } } else { int cl = inputStream.available(); logger.trace("Available Content-Length: " + cl); output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + cl); } if (range.isStartOffsetAvailable() && dlna != null) { // Add timeseek information headers. String timeseekValue = DLNAMediaInfo.getDurationString(range.getStartOrZero()); String timetotalValue = dlna.getMedia().getDurationString(); String timeEndValue = range.isEndLimitAvailable() ? DLNAMediaInfo.getDurationString(range.getEnd()) : timetotalValue; output.setHeader("TimeSeekRange.dlna.org", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue); output.setHeader("X-Seek-Range", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue); } // Send the response headers to the client. future = e.getChannel().write(output); if (lowRange != DLNAMediaInfo.ENDFILE_POS && !method.equals("HEAD")) { // Send the response body to the client in chunks. ChannelFuture chunkWriteFuture = e.getChannel().write(new ChunkedStream(inputStream, BUFFER_SIZE)); // Add a listener to clean up after sending the entire response body. chunkWriteFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { try { PMS.get().getRegistry().reenableGoToSleep(); inputStream.close(); } catch (IOException e) { logger.debug("Caught exception", e); } // Always close the channel after the response is sent because of // a freeze at the end of video when the channel is not closed. future.getChannel().close(); startStopListenerDelegate.stop(); } }); } else { // HEAD method is being used, so simply clean up after the response was sent. try { PMS.get().getRegistry().reenableGoToSleep(); inputStream.close(); } catch (IOException ioe) { logger.debug("Caught exception", ioe); } if (close) { // Close the channel after the response is sent future.addListener(ChannelFutureListener.CLOSE); } startStopListenerDelegate.stop(); } } else { // No response data and no input stream. Seems we are merely serving up headers. if (lowRange > 0 && highRange > 0) { // FIXME: There is no content, so why set a length? output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + (highRange - lowRange + 1)); } else { output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "0"); } // Send the response headers to the client. future = e.getChannel().write(output); if (close) { // Close the channel after the response is sent. future.addListener(ChannelFutureListener.CLOSE); } } // Log trace information Iterator<String> it = output.getHeaderNames().iterator(); while (it.hasNext()) { String headerName = it.next(); logger.trace("Sent to socket: " + headerName + ": " + output.getHeader(headerName)); } return future; }
From source file:com.denimgroup.threadfix.importer.impl.upload.ClangChannelImporter.java
private Calendar getTestDate(InputStream indexHtml) { try {// w ww . j a v a2 s. com String s = IOUtils.toString(indexHtml); String sDate = StringUtils.substringBetween(s, "<tr><th>Date:</th><td>", "</td></tr>"); // Mon Aug 4 13:18:00 2014 return DateUtils.getCalendarFromString("EEE MMM dd HH:mm:ss yyyy", sDate); } catch (IOException e) { log.error("IOException reading inputstream index.html in getTestDate(indexHtml)", e); return null; } }
From source file:kenh.expl.impl.ExpLParser.java
/** * Invoke functioin, support name space. For example, expl:contains(...). * @param function/* w ww . j av a2 s .co m*/ * @return Return string or non-string object. Return empty string instead of null. */ private Object executeFunction(String function) throws UnsupportedExpressionException { // function should return a string object; if (StringUtils.isBlank(function)) { UnsupportedExpressionException e = new UnsupportedExpressionException("Function is null."); throw e; } logger.trace("Func: " + function); String parameter = StringUtils.substringBeforeLast(StringUtils.substringAfter(function, "("), ")"); String[] parts = splitParameter(parameter); String funcName = StringUtils.substringBetween(function, "#", "("); String nameSpace = null; if (StringUtils.contains(funcName, ":")) { nameSpace = StringUtils.substringBefore(funcName, ":"); funcName = StringUtils.substringAfter(funcName, ":"); } if (StringUtils.isBlank(funcName)) { UnsupportedExpressionException e = new UnsupportedExpressionException("Failure to get function name"); e.push(function); throw e; } Object[] objs = new Object[parts.length]; int i = 0; for (String part : parts) { if (part.indexOf('{') != -1) { Object obj = this.parseExpress(part); objs[i++] = obj; } else { objs[i++] = part; } } try { // instantiate it, and create the parameters Function func = this.getEnvironment().getFunction(nameSpace, funcName); if (func == null) throw new UnsupportedExpressionException("Can't find the function. [" + (StringUtils.isBlank(nameSpace) ? funcName : nameSpace + ":" + funcName) + "]"); func.setEnvironment(this.getEnvironment()); // invoke return func.invoke(objs); } catch (UnsupportedExpressionException e) { e.push(function); throw e; } catch (Exception ex) { UnsupportedExpressionException e = new UnsupportedExpressionException(ex); e.push(function); throw e; } }
From source file:com.searchbox.collection.oppfin.TopicCollection.java
/** * Load HTML page and extract the part with the description * * @param callFileName The call identifier in the URL * @return The html markup that corresponds to the description *//*w w w .ja va 2s. c o m*/ private String getCallDescription(String callFileName) { // If the call is not cached, load it from URL if (!callList.containsKey(callFileName)) { callList.put(callFileName, new FieldMap()); // callList.put(item.get("callIdentifier").toString(), item); } if (!callList.get(callFileName).containsKey("callDescriptionHtml")) { LOGGER.info("Loading call description [" + callFileName + "]"); String topicUrlDetail = String.format(env.getProperty(CALL_DETAIL_URL, CALL_DETAIL_URL_DEFAULT), callFileName); // String htmlValue = StringUtils.substringBetween( // this.loadFromUrl(topicUrlDetail), // env.getProperty(CALL_DETAIL_BEGIN, CALL_DETAIL_BEGIN_DEFAULT), // env.getProperty(CALL_DETAIL_END, CALL_DETAIL_END_DEFAULT)).trim(); //TODO fix bug LOGGER.info("Loading topic loadFromUrl [" + topicUrlDetail + "]"); String htmlValue = StringUtils.substringBetween(this.loadFromUrl(topicUrlDetail), env.getProperty(CALL_DETAIL_BEGIN, CALL_DETAIL_BEGIN_DEFAULT), env.getProperty(CALL_DETAIL_END, CALL_DETAIL_END_DEFAULT)); if (htmlValue != null) { htmlValue = htmlValue.trim(); } else { htmlValue = "cannot get Description"; } callList.get(callFileName).put("callDescriptionHtml", htmlValue); String callDetailRaw = new HtmlToPlainText().getPlainText(Jsoup.parse(htmlValue)); callList.get(callFileName).put("callDescriptionRaw", callDetailRaw); // Creating a new enhancedCall JSONObject enhancedCall = new JSONObject(); // Pulling full HTML description from the web String callIdentifier = (String) callList.get(callFileName).get("callId").get(0); enhancedCall.put("eur_call_description_html", htmlValue); enhancedCall.put("eur_call_description_raw", callDetailRaw); enhancedCall.put("FileName", callFileName); enhancedCall.put("eur_call_timestamp", Calendar.getInstance().getTime()); enhancedCall.put("eur_call_FileName", callFileName); enhancedCall.put("eur_call_CallId", callIdentifier); // Saving the enhanced file try { File file = new File("output/calls/" + callFileName + ".json"); file.getParentFile().mkdirs(); FileWriter writer = new FileWriter(file); writer.write(enhancedCall.toJSONString()); writer.flush(); writer.close(); LOGGER.debug("File saved under " + file.getAbsolutePath()); // Saving the list of calls identifiers File file2 = new File("output/calls/calls_identifiers.txt"); FileWriter writer2 = new FileWriter(file2, true); writer2.write(callIdentifier + "\n"); writer2.flush(); writer2.close(); } catch (IOException e) { LOGGER.error(e.getLocalizedMessage()); } } return callList.get(callFileName).get("callDescriptionHtml").toString(); }
From source file:com.aniruddhc.acemusic.player.AsyncTasks.AsyncAutoGetAlbumArtTask.java
@Override protected Void doInBackground(String... params) { //First, we'll go through all the songs in the music library DB and get their attributes. dbHelper = new DBAccessHelper(mContext); String selection = DBAccessHelper.SONG_SOURCE + "<>" + "'GOOGLE_PLAY_MUSIC'"; String[] projection = { DBAccessHelper._ID, DBAccessHelper.SONG_FILE_PATH, DBAccessHelper.SONG_ALBUM, DBAccessHelper.SONG_ARTIST, DBAccessHelper.SONG_TITLE }; Cursor cursor = dbHelper.getWritableDatabase().query(DBAccessHelper.MUSIC_LIBRARY_TABLE, projection, selection, null, null, null, null); if (cursor.getCount() != 0) { cursor.moveToFirst();/*from w ww . j a v a 2s .co m*/ dataURIsList.add(cursor.getString(1)); albumsList.add(cursor.getString(2)); artistsList.add(cursor.getString(3)); while (cursor.moveToNext()) { dataURIsList.add(cursor.getString(1)); albumsList.add(cursor.getString(2)); artistsList.add(cursor.getString(3)); } } else { //The user doesn't have any music so let's get outta here. return null; } pd.setMax(dataURIsList.size()); //Now that we have the attributes of the songs, we'll go through them each and check for missing covers. for (int i = 0; i < dataURIsList.size(); i++) { try { file = new File(dataURIsList.get(i)); } catch (Exception e) { continue; } audioFile = null; try { audioFile = AudioFileIO.read(file); } catch (CannotReadException e2) { // TODO Auto-generated catch block continue; } catch (IOException e2) { // TODO Auto-generated catch block continue; } catch (TagException e2) { // TODO Auto-generated catch block continue; } catch (ReadOnlyFileException e2) { // TODO Auto-generated catch block continue; } catch (InvalidAudioFrameException e2) { // TODO Auto-generated catch block continue; } Tag tag = audioFile.getTag(); //Set the destination directory for the xml file. File SDCardRoot = Environment.getExternalStorageDirectory(); File xmlFile = new File(SDCardRoot, "albumArt.xml"); if (tag != null) { String title = tag.getFirst(FieldKey.TITLE); String checkingMessage = mContext.getResources().getString(R.string.checking_if) + " " + title + " " + mContext.getResources().getString(R.string.has_album_art) + "."; currentProgress = currentProgress + 1; String[] checkingProgressParams = { checkingMessage, "" + currentProgress }; publishProgress(checkingProgressParams); List<Artwork> artworkList = tag.getArtworkList(); if (artworkList.size() == 0) { //Since the file doesn't have any album artwork, we'll have to download it. //Get the artist and album name of the file we're working with. String artist = tag.getFirst(FieldKey.ARTIST); String album = tag.getFirst(FieldKey.ALBUM); //Update the progress dialog. String message = mContext.getResources().getString(R.string.downloading_artwork_for) + " " + title; String[] progressParams = { message, "" + currentProgress }; publishProgress(progressParams); //Remove any unacceptable characters. if (artist.contains("#")) { artist = artist.replace("#", ""); } if (artist.contains("$")) { artist = artist.replace("$", ""); } if (artist.contains("@")) { artist = artist.replace("@", ""); } if (album.contains("#")) { album = album.replace("#", ""); } if (album.contains("$")) { album = album.replace("$", ""); } if (album.contains("@")) { album = album.replace("@", ""); } //Replace any spaces in the artist and album fields with "%20". if (artist.contains(" ")) { artist = artist.replace(" ", "%20"); } if (album.contains(" ")) { album = album.replace(" ", "%20"); } //Construct the url for the HTTP request. URL url = null; try { url = new URL( "http://itunes.apple.com/search?term=" + artist + "+" + album + "&entity=album"); } catch (MalformedURLException e1) { // TODO Auto-generated catch block continue; } String xml = null; try { //Create a new HTTP connection. HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.connect(); //Check if albumArt.xml already exists and delete it. if (xmlFile.exists()) { xmlFile.delete(); } //Create the OuputStream that will be used to store the downloaded data into the file. FileOutputStream fileOutput = new FileOutputStream(xmlFile); //Create the InputStream that will read the data from the HTTP connection. InputStream inputStream = urlConnection.getInputStream(); //Total size of target file. int totalSize = urlConnection.getContentLength(); //Temp variable that stores the number of downloaded bytes. int downloadedSize = 0; //Create a buffer to store the downloaded bytes. buffer = new byte[1024]; int bufferLength = 0; //Now read through the buffer and write the contents to the file. while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); downloadedSize += bufferLength; } //Close the File Output Stream. fileOutput.close(); } catch (MalformedURLException e) { //TODO Auto-generated method stub continue; } catch (IOException e) { // TODO Auto-generated method stub continue; } //Load the XML file into a String variable for local use. String xmlAsString = null; try { xmlAsString = FileUtils.readFileToString(xmlFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Extract the albumArt parameter from the XML file. artworkURL = StringUtils.substringBetween(xmlAsString, "\"artworkUrl100\":\"", "\","); if (artworkURL == null) { //Check and see if a lower resolution image available. artworkURL = StringUtils.substringBetween(xmlAsString, "\"artworkUrl60\":\"", "\","); if (artworkURL == null) { //Can't do anything about that here. } else { //Replace "100x100" with "600x600" to retrieve larger album art images. artworkURL = artworkURL.replace("100x100", "600x600"); } } else { //Replace "100x100" with "600x600" to retrieve larger album art images. artworkURL = artworkURL.replace("100x100", "600x600"); } //If no URL has been found, there's no point in continuing. if (artworkURL != null) { artworkBitmap = null; artworkBitmap = mApp.getImageLoader().loadImageSync(artworkURL); File artworkFile = new File(Environment.getExternalStorageDirectory() + "/artwork.jpg"); //Save the artwork. try { FileOutputStream out = new FileOutputStream(artworkFile); artworkBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); } catch (Exception e) { e.printStackTrace(); } finally { Artwork artwork = null; try { artwork = ArtworkFactory.createArtworkFromFile(artworkFile); } catch (IOException e) { // TODO Auto-generated catch block setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } catch (ArrayIndexOutOfBoundsException e) { // TODO Auto-generated catch block setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } catch (Exception e) { e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } catch (Error e) { e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } if (artwork != null) { try { //Remove the current artwork field and recreate it. tag.deleteArtworkField(); tag.addField(artwork); } catch (Exception e) { // TODO Auto-generated catch block setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } catch (Error e) { e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } try { audioFile.commit(); } catch (CannotWriteException e) { // TODO Auto-generated catch block setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } catch (Error e) { e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } } //Delete the temporary files that we stored during the fetching process. if (artworkFile.exists()) { artworkFile.delete(); } if (xmlFile.exists()) { xmlFile.delete(); } //Set the files to null to help clean up memory. artworkBitmap = null; audioFile = null; tag = null; xmlFile = null; artworkFile = null; } } } } } audioFile = null; file = null; //System.gc(); return null; }
From source file:com.eryansky.common.orm.core.hibernate.support.BasicHibernateDao.java
/** * HQL?,?hql// w ww . j a va2 s . c om * * @param orgHql hql * * @return String */ private String prepareCountHql(String orgHql) { String countField = StringUtils.substringBetween(orgHql, "select", "from"); String countHql = MessageFormat.format("select count ({0}) {1} ", StringUtils.isEmpty(countField) ? "*" : countField, removeSelect(removeOrders(orgHql))); return countHql; }
From source file:ching.icecreaming.action.ViewAction.java
@Action(value = "view", results = { @Result(name = "login", location = "edit.jsp"), @Result(name = "input", location = "view.jsp"), @Result(name = "success", location = "view.jsp"), @Result(name = "error", location = "error.jsp") }) public String execute() throws Exception { Enumeration enumerator = null; String[] array1 = null, array2 = null; int int1 = -1, int2 = -1, int3 = -1; InputStream inputStream1 = null; OutputStream outputStream1 = null; java.io.File file1 = null, file2 = null, dir1 = null; List<File> files = null; HttpHost httpHost1 = null;//from ww w. j a v a 2 s . c o m HttpGet httpGet1 = null, httpGet2 = null; HttpPut httpPut1 = null; URI uri1 = null; URL url1 = null; DefaultHttpClient httpClient1 = null; URIBuilder uriBuilder1 = null, uriBuilder2 = null; HttpResponse httpResponse1 = null, httpResponse2 = null; HttpEntity httpEntity1 = null, httpEntity2 = null; List<NameValuePair> nameValuePair1 = null; String string1 = null, string2 = null, string3 = null, string4 = null, return1 = LOGIN; XMLConfiguration xmlConfiguration = null; List<HierarchicalConfiguration> list1 = null, list2 = null; HierarchicalConfiguration hierarchicalConfiguration2 = null; DataModel1 dataModel1 = null; DataModel2 dataModel2 = null; List<DataModel1> listObject1 = null, listObject3 = null; org.joda.time.DateTime dateTime1 = null, dateTime2 = null; org.joda.time.Period period1 = null; PeriodFormatter periodFormatter1 = new PeriodFormatterBuilder().appendYears() .appendSuffix(String.format(" %s", getText("year")), String.format(" %s", getText("years"))) .appendSeparator(" ").appendMonths() .appendSuffix(String.format(" %s", getText("month")), String.format(" %s", getText("months"))) .appendSeparator(" ").appendWeeks() .appendSuffix(String.format(" %s", getText("week")), String.format(" %s", getText("weeks"))) .appendSeparator(" ").appendDays() .appendSuffix(String.format(" %s", getText("day")), String.format(" %s", getText("days"))) .appendSeparator(" ").appendHours() .appendSuffix(String.format(" %s", getText("hour")), String.format(" %s", getText("hours"))) .appendSeparator(" ").appendMinutes() .appendSuffix(String.format(" %s", getText("minute")), String.format(" %s", getText("minutes"))) .appendSeparator(" ").appendSeconds().minimumPrintedDigits(2) .appendSuffix(String.format(" %s", getText("second")), String.format(" %s", getText("seconds"))) .printZeroNever().toFormatter(); if (StringUtils.isBlank(urlString) || StringUtils.isBlank(wsType)) { urlString = portletPreferences.getValue("urlString", "/"); wsType = portletPreferences.getValue("wsType", "folder"); } Configuration propertiesConfiguration1 = new PropertiesConfiguration("system.properties"); timeZone1 = portletPreferences.getValue("timeZone", TimeZone.getDefault().getID()); enumerator = portletPreferences.getNames(); if (enumerator.hasMoreElements()) { array1 = portletPreferences.getValues("server", null); if (array1 != null) { if (ArrayUtils.isNotEmpty(array1)) { for (int1 = 0; int1 < array1.length; int1++) { switch (int1) { case 0: sid = array1[int1]; break; case 1: uid = array1[int1]; break; case 2: pid = array1[int1]; break; case 3: alias1 = array1[int1]; break; default: break; } } sid = new String(Base64.decodeBase64(sid.getBytes())); uid = new String(Base64.decodeBase64(uid.getBytes())); pid = new String(Base64.decodeBase64(pid.getBytes())); } return1 = INPUT; } else { return1 = LOGIN; } } else { return1 = LOGIN; } if (StringUtils.equals(urlString, "/")) { if (listObject1 != null) { listObject1.clear(); } if (session.containsKey("breadcrumbs")) { session.remove("breadcrumbs"); } } else { array2 = StringUtils.split(urlString, "/"); listObject1 = (session.containsKey("breadcrumbs")) ? (List<DataModel1>) session.get("breadcrumbs") : new ArrayList<DataModel1>(); int2 = array2.length - listObject1.size(); if (int2 > 0) { listObject1.add(new DataModel1(urlString, label1)); } else { int2 += listObject1.size(); for (int1 = listObject1.size() - 1; int1 >= int2; int1--) { listObject1.remove(int1); } } session.put("breadcrumbs", listObject1); } switch (wsType) { case "folder": break; case "reportUnit": try { dateTime1 = new org.joda.time.DateTime(); return1 = INPUT; httpClient1 = new DefaultHttpClient(); if (StringUtils.equals(button1, getText("Print"))) { nameValuePair1 = new ArrayList<NameValuePair>(); if (listObject2 != null) { if (listObject2.size() > 0) { for (DataModel2 dataObject2 : listObject2) { listObject3 = dataObject2.getOptions(); if (listObject3 == null) { string2 = dataObject2.getValue1(); if (StringUtils.isNotBlank(string2)) nameValuePair1.add(new BasicNameValuePair(dataObject2.getId(), string2)); } else { for (int1 = listObject3.size() - 1; int1 >= 0; int1--) { dataModel1 = (DataModel1) listObject3.get(int1); string2 = dataModel1.getString2(); if (StringUtils.isNotBlank(string2)) nameValuePair1 .add(new BasicNameValuePair(dataObject2.getId(), string2)); } } } } } url1 = new URL(sid); uriBuilder1 = new URIBuilder(sid); uriBuilder1.setUserInfo(uid, pid); if (StringUtils.isBlank(format1)) format1 = "pdf"; uriBuilder1.setPath(url1.getPath() + "/rest_v2/reports" + urlString + "." + format1); if (StringUtils.isNotBlank(locale2)) { nameValuePair1.add(new BasicNameValuePair("userLocale", locale2)); } if (StringUtils.isNotBlank(page1)) { if (NumberUtils.isNumber(page1)) { nameValuePair1.add(new BasicNameValuePair("page", page1)); } } if (nameValuePair1.size() > 0) { uriBuilder1.setQuery(URLEncodedUtils.format(nameValuePair1, "UTF-8")); } uri1 = uriBuilder1.build(); httpGet1 = new HttpGet(uri1); httpResponse1 = httpClient1.execute(httpGet1); int1 = httpResponse1.getStatusLine().getStatusCode(); if (int1 == HttpStatus.SC_OK) { string3 = System.getProperty("java.io.tmpdir") + File.separator + httpServletRequest.getSession().getId(); dir1 = new File(string3); if (!dir1.exists()) { dir1.mkdir(); } httpEntity1 = httpResponse1.getEntity(); file1 = new File(string3, StringUtils.substringAfterLast(urlString, "/") + "." + format1); if (StringUtils.equalsIgnoreCase(format1, "html")) { result1 = EntityUtils.toString(httpEntity1); FileUtils.writeStringToFile(file1, result1); array1 = StringUtils.substringsBetween(result1, "<img src=\"", "\""); if (ArrayUtils.isNotEmpty(array1)) { dir1 = new File( string3 + File.separator + FilenameUtils.getBaseName(file1.getName())); if (dir1.exists()) { FileUtils.deleteDirectory(dir1); } file2 = new File(FilenameUtils.getFullPath(file1.getAbsolutePath()) + FilenameUtils.getBaseName(file1.getName()) + ".zip"); if (file2.exists()) { if (FileUtils.deleteQuietly(file2)) { } } for (int2 = 0; int2 < array1.length; int2++) { try { string2 = url1.getPath() + "/rest_v2/reports" + urlString + "/" + StringUtils.substringAfter(array1[int2], "/"); uriBuilder1.setPath(string2); uri1 = uriBuilder1.build(); httpGet1 = new HttpGet(uri1); httpResponse1 = httpClient1.execute(httpGet1); int1 = httpResponse1.getStatusLine().getStatusCode(); } finally { if (int1 == HttpStatus.SC_OK) { try { string2 = StringUtils.substringBeforeLast(array1[int2], "/"); dir1 = new File(string3 + File.separator + string2); if (!dir1.exists()) { dir1.mkdirs(); } httpEntity1 = httpResponse1.getEntity(); inputStream1 = httpEntity1.getContent(); } finally { string1 = StringUtils.substringAfterLast(array1[int2], "/"); file2 = new File(string3 + File.separator + string2, string1); outputStream1 = new FileOutputStream(file2); IOUtils.copy(inputStream1, outputStream1); } } } } outputStream1 = new FileOutputStream( FilenameUtils.getFullPath(file1.getAbsolutePath()) + FilenameUtils.getBaseName(file1.getName()) + ".zip"); ArchiveOutputStream archiveOutputStream1 = new ArchiveStreamFactory() .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputStream1); archiveOutputStream1.putArchiveEntry(new ZipArchiveEntry(file1, file1.getName())); IOUtils.copy(new FileInputStream(file1), archiveOutputStream1); archiveOutputStream1.closeArchiveEntry(); dir1 = new File(FilenameUtils.getFullPath(file1.getAbsolutePath()) + FilenameUtils.getBaseName(file1.getName())); files = (List<File>) FileUtils.listFiles(dir1, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); for (File file3 : files) { archiveOutputStream1.putArchiveEntry(new ZipArchiveEntry(file3, StringUtils .substringAfter(file3.getCanonicalPath(), string3 + File.separator))); IOUtils.copy(new FileInputStream(file3), archiveOutputStream1); archiveOutputStream1.closeArchiveEntry(); } archiveOutputStream1.close(); } bugfixGateIn = propertiesConfiguration1.getBoolean("bugfixGateIn", false); string4 = bugfixGateIn ? String.format("<img src=\"%s/namespace1/file-link?sessionId=%s&fileName=", portletRequest.getContextPath(), httpServletRequest.getSession().getId()) : String.format("<img src=\"%s/namespace1/file-link?fileName=", portletRequest.getContextPath()); result1 = StringUtils.replace(result1, "<img src=\"", string4); } else { inputStream1 = httpEntity1.getContent(); outputStream1 = new FileOutputStream(file1); IOUtils.copy(inputStream1, outputStream1); result1 = file1.getAbsolutePath(); } return1 = SUCCESS; } else { addActionError(String.format("%s %d: %s", getText("Error"), int1, getText(Integer.toString(int1)))); } dateTime2 = new org.joda.time.DateTime(); period1 = new Period(dateTime1, dateTime2.plusSeconds(1)); message1 = getText("Execution.time") + ": " + periodFormatter1.print(period1); } else { url1 = new URL(sid); uriBuilder1 = new URIBuilder(sid); uriBuilder1.setUserInfo(uid, pid); uriBuilder1.setPath(url1.getPath() + "/rest_v2/reports" + urlString + "/inputControls"); uri1 = uriBuilder1.build(); httpGet1 = new HttpGet(uri1); httpResponse1 = httpClient1.execute(httpGet1); int1 = httpResponse1.getStatusLine().getStatusCode(); switch (int1) { case HttpStatus.SC_NO_CONTENT: break; case HttpStatus.SC_OK: httpEntity1 = httpResponse1.getEntity(); if (httpEntity1 != null) { inputStream1 = httpEntity1.getContent(); if (inputStream1 != null) { xmlConfiguration = new XMLConfiguration(); xmlConfiguration.load(inputStream1); list1 = xmlConfiguration.configurationsAt("inputControl"); if (list1.size() > 0) { listObject2 = new ArrayList<DataModel2>(); for (HierarchicalConfiguration hierarchicalConfiguration1 : list1) { string2 = hierarchicalConfiguration1.getString("type"); dataModel2 = new DataModel2(); dataModel2.setId(hierarchicalConfiguration1.getString("id")); dataModel2.setLabel1(hierarchicalConfiguration1.getString("label")); dataModel2.setType1(string2); dataModel2.setMandatory(hierarchicalConfiguration1.getBoolean("mandatory")); dataModel2.setReadOnly(hierarchicalConfiguration1.getBoolean("readOnly")); dataModel2.setVisible(hierarchicalConfiguration1.getBoolean("visible")); switch (string2) { case "bool": case "singleValueText": case "singleValueNumber": case "singleValueDate": case "singleValueDatetime": hierarchicalConfiguration2 = hierarchicalConfiguration1 .configurationAt("state"); dataModel2.setValue1(hierarchicalConfiguration2.getString("value")); break; case "singleSelect": case "singleSelectRadio": case "multiSelect": case "multiSelectCheckbox": hierarchicalConfiguration2 = hierarchicalConfiguration1 .configurationAt("state"); list2 = hierarchicalConfiguration2.configurationsAt("options.option"); if (list2.size() > 0) { listObject3 = new ArrayList<DataModel1>(); for (HierarchicalConfiguration hierarchicalConfiguration3 : list2) { dataModel1 = new DataModel1( hierarchicalConfiguration3.getString("label"), hierarchicalConfiguration3.getString("value")); if (hierarchicalConfiguration3.getBoolean("selected")) { dataModel2.setValue1( hierarchicalConfiguration3.getString("value")); } listObject3.add(dataModel1); } dataModel2.setOptions(listObject3); } break; default: break; } listObject2.add(dataModel2); } } } } break; default: addActionError(String.format("%s %d: %s", getText("Error"), int1, getText(Integer.toString(int1)))); break; } if (httpEntity1 != null) { EntityUtils.consume(httpEntity1); } uriBuilder1.setPath(url1.getPath() + "/rest/resource" + urlString); uri1 = uriBuilder1.build(); httpGet1 = new HttpGet(uri1); httpResponse1 = httpClient1.execute(httpGet1); int2 = httpResponse1.getStatusLine().getStatusCode(); if (int2 == HttpStatus.SC_OK) { httpEntity1 = httpResponse1.getEntity(); inputStream1 = httpEntity1.getContent(); xmlConfiguration = new XMLConfiguration(); xmlConfiguration.load(inputStream1); list1 = xmlConfiguration.configurationsAt("resourceDescriptor"); for (HierarchicalConfiguration hierarchicalConfiguration4 : list1) { if (StringUtils.equalsIgnoreCase( StringUtils.trim(hierarchicalConfiguration4.getString("[@wsType]")), "prop")) { if (map1 == null) map1 = new HashMap<String, String>(); string2 = StringUtils.substringBetween( StringUtils.substringAfter( hierarchicalConfiguration4.getString("[@uriString]"), "_files/"), "_", ".properties"); map1.put(string2, StringUtils.isBlank(string2) ? getText("Default") : getText(string2)); } } } if (httpEntity1 != null) { EntityUtils.consume(httpEntity1); } } } catch (IOException | ConfigurationException | URISyntaxException exception1) { exception1.printStackTrace(); addActionError(exception1.getLocalizedMessage()); httpGet1.abort(); return ERROR; } finally { httpClient1.getConnectionManager().shutdown(); IOUtils.closeQuietly(inputStream1); } break; default: addActionError(getText("This.file.type.is.not.supported")); break; } if (return1 != LOGIN) { sid = new String(Base64.encodeBase64(sid.getBytes())); uid = new String(Base64.encodeBase64(uid.getBytes())); pid = new String(Base64.encodeBase64(pid.getBytes())); } return return1; }