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.transcoder.impl; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.Property; import javax.jcr.PropertyIterator; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.ValueFormatException; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthPolicy; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.sling.jcr.api.SlingRepository; import org.iavante.sling.commons.services.ITranscoderService; import org.iavante.sling.commons.services.PortalSetup; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @see org.iavante.sling.commons.services.ITranscoderService * @scr.component * @scr.service * interface="org.iavante.sling.commons.services.ITranscoderService" */ public class TranscoderServiceImpl implements ITranscoderService { /** @scr.reference */ private SlingRepository repository; /** @scr.reference */ private PortalSetup portalSetup; /** Vendor. */ private final String VENDOR = "IAVANTE"; /** Description. */ private final String DESCRIPTION = "Python transcoder service"; /** Components folder. */ private final String COMPONENTS_FOLDER = "components"; /** Transcoder folder. */ private final String TRANSCODER_FOLDER = "transcoder"; /** Transformation preview folder. */ private final String PREVIEW_FOLDER = "preview"; /** Conversion description type. */ private final String DESCRIPTION_PROP = "description"; /** Conversion description type. */ private final String CONVERSION_PROP = "conversion_type"; /** JCR session. */ private Session session; /** Root node. */ private Node rootNode; /** Base repository directory. */ private String baseRepoDir = "content"; /** Sling properties. */ private Map<String, String> globalProperties = null; /** Component properties. */ private Map<String, String> transcoderProperties = null; /** Send conversion complete url. */ private String sendConversionUrl = "http://www.iavante.es/test/test"; /** Transcoding Server Auth. */ private String transcodingServerUser = ""; private String transcodingServerPassword = ""; /** Default Logger. */ private static final Logger log = LoggerFactory.getLogger(TranscoderServiceImpl.class); protected void activate(ComponentContext context) { try { session = repository.loginAdministrative(null); this.rootNode = session.getRootNode(); } catch (Exception e) { log.error("cannot start"); } // Component property globalProperties = portalSetup.get_config_properties("/sling"); transcoderProperties = portalSetup.get_config_properties("/transcoder"); transcodingServerUser = transcoderProperties.get("transcodingServerUser"); transcodingServerPassword = transcoderProperties.get("transcodingServerPassword"); String transcoder_url = transcoderProperties.get("url"); String send_conversion_path = transcoderProperties.get("send_conversion_path"); // Usefull properties baseRepoDir = globalProperties.get("base_repo_dir"); sendConversionUrl = transcoder_url + send_conversion_path; } // -------------- Constructor --------------- public TranscoderServiceImpl() { } public TranscoderServiceImpl(Node root_node) { this.rootNode = root_node; } /* * @see org.iavante.sling.commons.services.ITranscoderService */ public String getVendor() { return this.VENDOR; } /* * @see org.iavante.sling.commons.services.ITranscoderService */ public String getDescription() { return this.DESCRIPTION; } /* * @see org.iavante.sling.commons.services.ITranscoderService */ public Map<String, String> getConversionTypes(String type) { NodeIterator conversionsNodes = null; try { Node transcoderNode = this.rootNode .getNode(baseRepoDir + "/" + COMPONENTS_FOLDER + "/" + TRANSCODER_FOLDER); conversionsNodes = transcoderNode.getNodes(); } catch (PathNotFoundException e) { e.printStackTrace(); } catch (RepositoryException e) { e.printStackTrace(); } Map<String, String> conversionTypes = new HashMap<String, String>(); while (conversionsNodes.hasNext()) { Node conversion = (Node) conversionsNodes.next(); String conversionName; try { conversionName = conversion.getName(); String conversion_description = conversion.getProperty(DESCRIPTION_PROP).getValue().getString(); String conversion_type = conversion.getProperty(CONVERSION_PROP).getValue().getString(); if (type == null || type.compareTo(conversion_type) == 0) { conversionTypes.put(conversionName, conversion_description); } } catch (RepositoryException e) { e.printStackTrace(); } } return conversionTypes; } /* * @see org.iavante.sling.commons.services.ITranscoderService */ public Map<String, String> getConversion(String conversionType) { Map<String, String> conversionProp = new HashMap<String, String>(); Node conversionNode = null; try { conversionNode = this.rootNode.getNode( baseRepoDir + "/" + COMPONENTS_FOLDER + "/" + TRANSCODER_FOLDER + "/" + conversionType); if (log.isInfoEnabled()) log.info("Conversion node: " + conversionNode.getPath()); PropertyIterator propIter = conversionNode.getProperties(); while (propIter.hasNext()) { Property prop = (Property) propIter.next(); conversionProp.put(prop.getName().toString(), prop.getValue().getString()); } } catch (PathNotFoundException e) { e.printStackTrace(); } catch (RepositoryException e) { e.printStackTrace(); } return conversionProp; } /* * @see org.iavante.sling.commons.services.ITranscoderService */ public int sendConversionTask(String conversionType, String sourceLocation, String targetLocation, String notificationUrl, String externalStorageServer, String externalStorageUrl) { return sendConversionTask3(conversionType, sourceLocation, targetLocation, notificationUrl, externalStorageServer, externalStorageUrl, null, null); } /* * @see org.iavante.sling.commons.services.ITranscoderService */ public int sendConversionTask2(String conversionType, String sourceLocation, String targetLocation, String notificationUrl, String externalStorageServer, String externalStorageUrl, String params) { return sendConversionTask3(conversionType, sourceLocation, targetLocation, notificationUrl, externalStorageServer, externalStorageUrl, params, null); } /* * @see org.iavante.sling.commons.services.ITranscoderService */ public int sendConversionTask3(String conversionType, String sourceLocation, String targetLocation, String notificationUrl, String externalStorageServer, String externalStorageUrl, String params, String ds_custom_props) { Map<String, String> envs = System.getenv(); Set<String> keys = envs.keySet(); Iterator<String> it = keys.iterator(); List authPrefs = new ArrayList(2); Credentials defaultcreds; authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); defaultcreds = new UsernamePasswordCredentials(transcodingServerUser, transcodingServerPassword); // Set client connection params MultiThreadedHttpConnectionManager connManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams connParams = connManager.getParams(); connParams.setConnectionTimeout(800); HttpClient client = new HttpClient(connManager); client.getState().setCredentials(AuthScope.ANY, defaultcreds); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); if (log.isInfoEnabled()) log.info("Sending conversion task"); Node convTypeNode = null; try { convTypeNode = rootNode.getNode(baseRepoDir + "/" + COMPONENTS_FOLDER + "/" + TRANSCODER_FOLDER) .getNode(conversionType); } catch (PathNotFoundException e) { e.printStackTrace(); } catch (RepositoryException e) { e.printStackTrace(); } String executable = null; try { executable = convTypeNode.getProperty("command").getValue().getString(); if (params == null) { params = convTypeNode.getProperty("params").getValue().getString(); } if (ds_custom_props == null) { ds_custom_props = ""; } } catch (ValueFormatException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (PathNotFoundException e) { e.printStackTrace(); } catch (RepositoryException e) { e.printStackTrace(); } PostMethod post = new PostMethod(sendConversionUrl); //post.getParams().setParameter("http.socket.timeout", new Integer(50)); post.setDoAuthentication(true); NameValuePair[] data = { new NameValuePair("source_location", sourceLocation), new NameValuePair("target_location", targetLocation), new NameValuePair("executable", executable), new NameValuePair("params", params), new NameValuePair("ds_custom_props", ds_custom_props), new NameValuePair("notification_url", notificationUrl), new NameValuePair("extern_storage_server", externalStorageServer), new NameValuePair("sling:resourceType", "gad/job"), new NameValuePair("extern_storage_url", externalStorageUrl) }; post.setRequestBody(data); post.setDoAuthentication(true); int status = 0; int intentos = 0; while ((status != 201) && (intentos < 2)) { try { client.executeMethod(post); status = post.getStatusCode(); log.info("Conversion sent. Status code: " + status); } catch (HttpException e1) { log.error("Excepcion: HttpException"); e1.printStackTrace(); post.releaseConnection(); return status; } catch (IOException e1) { log.error("Excepcion: IOexception"); e1.printStackTrace(); post.releaseConnection(); return status; } finally { intentos++; } } post.releaseConnection(); return status; } }