Java tutorial
/* * Digital Assets Management * ========================= * * Copyright 2009 Fundacin Iavante * * Authors: * Francisco Jos Moreno Llorca <packo@assamita.net> * Francisco Jess Gonzlez Mata <chuspb@gmail.com> * Juan Antonio Guzmn Hidalgo <juan@guzmanhidalgo.com> * Daniel de la Cuesta Navarrete <cues7a@gmail.com> * Manuel Jos Cobo Fernndez <ranrrias@gmail.com> * * Licensed under the EUPL, Version 1.1 or as soon they will be approved by * the European Commission - subsequent versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * http://ec.europa.eu/idabc/eupl * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. * */ package org.iavante.sling.gad.administration.impl; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.StringPart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Http operations for AdministrationUploadService. */ public class UploadOperations extends AbstractHttpOperation { /** Default log. */ private final Logger log = LoggerFactory.getLogger(getClass()); /** Admin user name. */ private String adminUser; /** Admin user password. */ private String adminPasswd; /** Default admin user name. */ private String defaultAdminUser = "admin"; /** Default admin user password. */ private String defaultAdminPasswd = "admin"; /** Uploader url. */ private String uploaderUrl = null; /** Uploader upload api. */ private String uploaderUploadApi = null; /** Base folder for JCR repository. */ private String baseRepoDir = null; /** Authentication properties. */ private Map<String, String> authProperties = null; /** Authentication properties. */ private Map<String, String> uploaderProperties = null; /** * Constructor. * * @param aProperties * Authentication properties * @param uProperties * Uploader properties */ public UploadOperations(Map aProperties, Map uProperties) { authProperties = aProperties; uploaderProperties = uProperties; init(); } /** * Initialize object properties. */ private void init() { if (log.isInfoEnabled()) log.info("init, ini"); // getting admin, username and password from global configuration service try { adminUser = authProperties.get("sling_user"); adminPasswd = authProperties.get("sling_pass"); baseRepoDir = authProperties.get("base_repo_dir"); uploaderUrl = uploaderProperties.get("uploader_url"); uploaderUploadApi = uploaderProperties.get("uploader_upload_api"); if (log.isInfoEnabled()) log.info("init, auth_properties gotten from config node"); if (log.isInfoEnabled()) log.info("init, base_repo_dir= " + baseRepoDir); if (log.isInfoEnabled()) log.info("init, uploader_url= " + uploaderUrl); if (log.isInfoEnabled()) log.info("init, uploader_upload_api= " + uploaderUploadApi); if (log.isInfoEnabled()) log.info("init, Credentials= " + adminUser + ":" + adminPasswd.charAt(0) + "*...*" + adminPasswd.toCharArray()[adminPasswd.length() - 1]); } catch (Exception e) { adminUser = defaultAdminUser; adminPasswd = defaultAdminPasswd; uploaderUrl = "http://localhost:8888"; baseRepoDir = "/content"; uploaderUploadApi = "/uploader"; log.error("init, error getting parameters from config, " + e.getMessage()); log.error("init, using default admin username and password"); log.error("init, using default uploader_url= " + uploaderUrl); log.error("init, using default base_repo_dir= " + baseRepoDir); log.error("init, using default uploader_upload_api= " + uploaderUploadApi); } if (log.isInfoEnabled()) log.info("init, end"); } /** * Creates a new source. * * @param request * @return Location header attribute * @throws IOException */ public String createSourceInCore(HttpServletRequest request, String resourceType) throws IOException { init(); String location = null; if (log.isInfoEnabled()) log.info("createSource, ini"); Enumeration en2 = request.getParameterNames(); while (en2.hasMoreElements()) { String cad = (String) en2.nextElement(); if ("data".compareTo(cad) != 0) { if (log.isInfoEnabled()) log.info("createSource, Param: " + cad + ", value: " + request.getParameter(cad)); } else { if (log.isInfoEnabled()) log.info("createSource, Param: " + cad); } } // Getting parameters String sourcename = request.getParameter("sourcename"); if (sourcename == null) { throw new IOException("No <filename> param found in request"); } String content = request.getParameter("content"); if (content == null) { throw new IOException("No <content> param found in request"); } // If 'content' ends with '/*' then check if exists, else create if (!content.endsWith("/*")) { // Setting GET Credentials creds = new UsernamePasswordCredentials(adminUser, adminPasswd); String getUrl = HTTP_BASE_URL + content; if (log.isInfoEnabled()) log.info("createSource, getUrl: " + getUrl); assertAuthenticatedHttpStatus(creds, getUrl, 200, null); location = content; if (log.isInfoEnabled()) log.info("createSource, source already exists"); } else { // 'create' // Setting POST Credentials creds = new UsernamePasswordCredentials(adminUser, adminPasswd); String postUrl = HTTP_BASE_URL + content; if (log.isInfoEnabled()) log.info("createSource, postUrl: " + postUrl); List<NameValuePair> postParams = new ArrayList<NameValuePair>(); postParams.add(new NameValuePair("title", sourcename)); postParams.add(new NameValuePair("sling:resourceType", resourceType)); postParams.add(new NameValuePair("file", "")); postParams.add(new NameValuePair("mimetype", "")); postParams.add(new NameValuePair("jcr:lastModifiedBy", "")); postParams.add(new NameValuePair("jcr:lastModified", "")); List<String> oksCodes = new ArrayList<String>(); oksCodes.add("" + HttpServletResponse.SC_CREATED); oksCodes.add("" + HttpServletResponse.SC_OK); Header[] headers = assertAuthenticatedPostStatus(creds, postUrl, oksCodes, postParams, null); if (headers != null) { boolean seguir = true; int i = 0; while (seguir && i < headers.length) { Header header = headers[i]; if ("Location".compareTo(header.getName()) == 0) { location = header.getValue(); if (!location.startsWith(baseRepoDir)) { location = "/" + baseRepoDir + location; } seguir = false; if (log.isInfoEnabled()) log.info("createSource, header Location:" + location); } else { i++; } } if (seguir) { if (log.isInfoEnabled()) log.info("createSource, header Location: NOT FOUND (null)"); } } } if (log.isInfoEnabled()) log.info("createSource, end"); return location; } /** * Sends the request to uploader. * * @param request * @throws IOException */ public void sendSourceToUploader(HttpServletRequest request, String location, String coreurl, String rt) throws IOException, UploadException { init(); if (log.isInfoEnabled()) log.info("sendSourceToUploader, ini"); Enumeration en2 = request.getParameterNames(); while (en2.hasMoreElements()) { String cad = (String) en2.nextElement(); if (log.isInfoEnabled()) log.info("sendSourceToUploader, Param: " + cad); } String filename = request.getParameter("filename"); if (filename == null) { throw new UploadException("No <filename> param found in request"); } String content = request.getParameter("content"); if (content == null) { throw new UploadException("No <content> param found in request"); } List<String> names = Collections.list((Enumeration<String>) request.getParameterNames()); if (names.contains("data") && names.contains("filename") && names.contains("content")) { // Getting bytes from specific encoding. Otherwise doesn't work byte[] dataArray = request.getParameter("data").getBytes("ISO-8859-1"); // Setting POST Credentials creds = new UsernamePasswordCredentials(adminUser, adminPasswd); String postUrl = uploaderUrl + uploaderUploadApi; log.error("sendSourceToUploader, postUrl: " + postUrl); List<String> oksCodes = new ArrayList<String>(); oksCodes.add("" + HttpServletResponse.SC_OK); Part[] parts = null; if (coreurl == null) { parts = new Part[4]; parts[0] = new StringPart("content", location); parts[1] = new StringPart("filename", filename); parts[2] = new StringPart("rt", rt); parts[3] = new FilePart("data", new ByteArrayPartSource(filename, dataArray)); } else { parts = new Part[5]; parts[0] = new StringPart("coreurl", coreurl); parts[1] = new StringPart("content", location); parts[2] = new StringPart("filename", filename); parts[3] = new StringPart("rt", rt); parts[4] = new FilePart("data", new ByteArrayPartSource(filename, dataArray)); } Header[] headers = assertAuthenticatedPostMultipartStatus(creds, postUrl, oksCodes, parts, null); if (log.isInfoEnabled()) log.info("sendSourceToUploader, POST sent correctly to uploader"); } else { // send error log.error("sendSourceToUploader, POST failed"); throw new UploadException("sendSourceToUploader, data, filename or content params is missing"); } if (log.isInfoEnabled()) log.info("sendSourceToUploader, end"); } }