Search in sources :

Example 1 with AppService

use of org.cerberus.crud.entity.AppService in project cerberus-source by cerberustesting.

the class SoapService method callSOAP.

@Override
public AnswerItem<AppService> callSOAP(String envelope, String servicePath, String soapOperation, String attachmentUrl, List<AppServiceHeader> header, String token, int timeOutMs, String system) {
    AnswerItem result = new AnswerItem();
    String unescapedEnvelope = StringEscapeUtils.unescapeXml(envelope);
    boolean is12SoapVersion = SOAP_1_2_NAMESPACE_PATTERN.matcher(unescapedEnvelope).matches();
    AppService serviceSOAP = factoryAppService.create("", AppService.TYPE_SOAP, null, "", "", envelope, "", servicePath, "", soapOperation, "", null, "", null);
    serviceSOAP.setTimeoutms(timeOutMs);
    ByteArrayOutputStream out = null;
    MessageEvent message = null;
    if (StringUtil.isNullOrEmpty(servicePath)) {
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSOAP_SERVICEPATHMISSING);
        result.setResultMessage(message);
        return result;
    }
    if (StringUtil.isNullOrEmpty(envelope)) {
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSOAP_ENVELOPEMISSING);
        result.setResultMessage(message);
        return result;
    }
    // If header is null we create the list empty.
    if (header == null) {
        header = new ArrayList<>();
    }
    // We feed the header with token + Standard SOAP header.
    if (token != null) {
        header.add(factoryAppServiceHeader.create(null, "cerberus-token", token, "Y", 0, "", "", null, "", null));
    }
    if (StringUtil.isNullOrEmpty(soapOperation)) {
        header.add(factoryAppServiceHeader.create(null, "SOAPAction", "", "Y", 0, "", "", null, "", null));
    } else {
        header.add(factoryAppServiceHeader.create(null, "SOAPAction", "\"" + soapOperation + "\"", "Y", 0, "", "", null, "", null));
    }
    header.add(factoryAppServiceHeader.create(null, "Content-Type", is12SoapVersion ? SOAPConstants.SOAP_1_2_CONTENT_TYPE : SOAPConstants.SOAP_1_1_CONTENT_TYPE, "Y", 0, "", "", null, "", null));
    serviceSOAP.setHeaderList(header);
    SOAPConnectionFactory soapConnectionFactory;
    SOAPConnection soapConnection = null;
    try {
        // Initialize SOAP Connection
        soapConnectionFactory = SOAPConnectionFactory.newInstance();
        soapConnection = soapConnectionFactory.createConnection();
        LOG.debug("Connection opened");
        // Create SOAP Request
        LOG.debug("Create request");
        SOAPMessage input = createSoapRequest(envelope, soapOperation, header, token);
        // Add attachment File if specified
        if (!StringUtil.isNullOrEmpty(attachmentUrl)) {
            this.addAttachmentPart(input, attachmentUrl);
            // Store the SOAP Call
            out = new ByteArrayOutputStream();
            input.writeTo(out);
            LOG.debug("WS call with attachement : " + out.toString());
            serviceSOAP.setServiceRequest(out.toString());
        } else {
            // Store the SOAP Call
            out = new ByteArrayOutputStream();
            input.writeTo(out);
            LOG.debug("WS call : " + out.toString());
        }
        // We already set the item in order to keep the request message in case of failure of SOAP calls.
        serviceSOAP.setService(servicePath);
        result.setItem(serviceSOAP);
        // Call the WS
        LOG.debug("Calling WS.");
        // Reset previous Authentification.
        Authenticator.setDefault(null);
        serviceSOAP.setProxyWithCredential(false);
        serviceSOAP.setProxyUser(null);
        SOAPMessage soapResponse = null;
        if (proxyService.useProxy(servicePath, system)) {
            // Get Proxy host and port from parameters.
            String proxyHost = parameterService.getParameterStringByKey("cerberus_proxy_host", system, DEFAULT_PROXY_HOST);
            int proxyPort = parameterService.getParameterIntegerByKey("cerberus_proxy_port", system, DEFAULT_PROXY_PORT);
            serviceSOAP.setProxy(true);
            serviceSOAP.setProxyHost(proxyHost);
            serviceSOAP.setProxyPort(proxyPort);
            // Create the Proxy.
            SocketAddress sockaddr = new InetSocketAddress(proxyHost, proxyPort);
            try (Socket socket = new Socket()) {
                socket.connect(sockaddr, 10000);
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(socket.getInetAddress(), proxyPort));
                if (parameterService.getParameterBooleanByKey("cerberus_proxyauthentification_active", system, DEFAULT_PROXYAUTHENT_ACTIVATE)) {
                    // Get the credentials from parameters.
                    String proxyUser = parameterService.getParameterStringByKey("cerberus_proxyauthentification_user", system, DEFAULT_PROXYAUTHENT_USER);
                    String proxyPass = parameterService.getParameterStringByKey("cerberus_proxyauthentification_password", system, DEFAULT_PROXYAUTHENT_PASSWORD);
                    serviceSOAP.setProxyWithCredential(true);
                    serviceSOAP.setProxyUser(proxyUser);
                    // Define the credential to the proxy.
                    initializeProxyAuthenticator(proxyUser, proxyPass);
                }
                // Call with Proxy.
                soapResponse = sendSOAPMessage(input, servicePath, proxy, timeOutMs);
            } catch (Exception e) {
                LOG.warn(e.toString());
            }
        } else {
            serviceSOAP.setProxy(false);
            serviceSOAP.setProxyHost(null);
            serviceSOAP.setProxyPort(0);
            // Call without proxy.
            soapResponse = sendSOAPMessage(input, servicePath, null, timeOutMs);
        // soapResponse = soapConnection.call(input, servicePath);
        }
        LOG.debug("Called WS.");
        out = new ByteArrayOutputStream();
        // Store the response
        soapResponse.writeTo(out);
        LOG.debug("WS response received.");
        LOG.debug("WS response : " + out.toString());
        message = new MessageEvent(MessageEventEnum.ACTION_SUCCESS_CALLSOAP);
        message.setDescription(message.getDescription().replace("%SERVICEPATH%", servicePath).replace("%SOAPMETHOD%", soapOperation));
        result.setResultMessage(message);
        // soapResponse.getSOAPPart().getEnvelope().getBody().getFault().getFaultCode();
        // We save convert to string the final response from SOAP request.
        serviceSOAP.setResponseHTTPBody(SoapUtil.convertSoapMessageToString(soapResponse));
        // Get result Content Type.
        serviceSOAP.setResponseHTTPBodyContentType(appServiceService.guessContentType(serviceSOAP, AppService.RESPONSEHTTPBODYCONTENTTYPE_XML));
        result.setItem(serviceSOAP);
    } catch (SOAPException | UnsupportedOperationException | IOException | SAXException | ParserConfigurationException | CerberusException e) {
        LOG.error(e.toString());
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSOAP);
        message.setDescription(message.getDescription().replace("%SERVICEPATH%", servicePath).replace("%SOAPMETHOD%", soapOperation).replace("%DESCRIPTION%", e.getMessage()));
        result.setResultMessage(message);
        return result;
    } finally {
        try {
            if (soapConnection != null) {
                soapConnection.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (SOAPException | IOException ex) {
            LOG.error(ex);
        } finally {
            result.setResultMessage(message);
        }
    }
    return result;
}
Also used : SOAPConnectionFactory(javax.xml.soap.SOAPConnectionFactory) IFactoryAppService(org.cerberus.crud.factory.IFactoryAppService) AppService(org.cerberus.crud.entity.AppService) CerberusException(org.cerberus.exception.CerberusException) MessageEvent(org.cerberus.engine.entity.MessageEvent) InetSocketAddress(java.net.InetSocketAddress) SOAPConnection(javax.xml.soap.SOAPConnection) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) AnswerItem(org.cerberus.util.answer.AnswerItem) SOAPMessage(javax.xml.soap.SOAPMessage) SOAPException(javax.xml.soap.SOAPException) CerberusException(org.cerberus.exception.CerberusException) SAXException(org.xml.sax.SAXException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) Proxy(java.net.Proxy) SOAPException(javax.xml.soap.SOAPException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) Socket(java.net.Socket)

Example 2 with AppService

use of org.cerberus.crud.entity.AppService in project cerberus-source by cerberustesting.

the class RestService method executeHTTPCall.

private AppService executeHTTPCall(CloseableHttpClient httpclient, HttpRequestBase httpget) throws Exception {
    try {
        // Create a custom response handler
        ResponseHandler<AppService> responseHandler = new ResponseHandler<AppService>() {

            @Override
            public AppService handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
                AppService myResponse = factoryAppService.create("", AppService.TYPE_REST, AppService.METHOD_HTTPGET, "", "", "", "", "", "", "", "", null, "", null);
                int responseCode = response.getStatusLine().getStatusCode();
                myResponse.setResponseHTTPCode(responseCode);
                myResponse.setResponseHTTPVersion(response.getProtocolVersion().toString());
                LOG.info(String.valueOf(responseCode) + " " + response.getProtocolVersion().toString());
                Header[] allHeaderList = response.getAllHeaders();
                for (Header header : allHeaderList) {
                    myResponse.addResponseHeaderList(factoryAppServiceHeader.create(null, header.getName(), header.getValue(), "Y", 0, "", "", null, "", null));
                }
                HttpEntity entity = response.getEntity();
                myResponse.setResponseHTTPBody(entity != null ? EntityUtils.toString(entity) : null);
                return myResponse;
            }
        };
        return httpclient.execute(httpget, responseHandler);
    } catch (Exception ex) {
        LOG.error(ex.toString());
        throw ex;
    } finally {
        httpclient.close();
    }
}
Also used : IFactoryAppService(org.cerberus.crud.factory.IFactoryAppService) AppService(org.cerberus.crud.entity.AppService) ResponseHandler(org.apache.http.client.ResponseHandler) Header(org.apache.http.Header) IFactoryAppServiceHeader(org.cerberus.crud.factory.IFactoryAppServiceHeader) AppServiceHeader(org.cerberus.crud.entity.AppServiceHeader) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) ClientProtocolException(org.apache.http.client.ClientProtocolException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException)

Example 3 with AppService

use of org.cerberus.crud.entity.AppService in project cerberus-source by cerberustesting.

the class CreateAppService method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
final void processRequest(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    response.setContentType("text/html;charset=UTF-8");
    String charset = request.getCharacterEncoding();
    // Parameter that are already controled by GUI (no need to decode) --> We SECURE them
    // Parameter that needs to be secured --> We SECURE+DECODE them
    String service = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("service"), null, charset);
    String group = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("group"), "", charset);
    String description = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("description"), "", charset);
    String attachementurl = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("attachementurl"), "", charset);
    String operation = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("operation"), "", charset);
    String application = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("application"), null, charset);
    String type = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("type"), "", charset);
    String method = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("method"), "", charset);
    // Parameter that we cannot secure as we need the html --> We DECODE them
    String servicePath = ParameterParserUtil.parseStringParamAndDecode(request.getParameter("servicePath"), "", charset);
    String serviceRequest = ParameterParserUtil.parseStringParamAndDecode(request.getParameter("serviceRequest"), null, charset);
    // Prepare the final answer.
    MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
    Answer finalAnswer = new Answer(msg1);
    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(service)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "SoapLibrary").replace("%OPERATION%", "Create").replace("%REASON%", "SoapLibrary name is missing!"));
        finalAnswer.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        appServiceService = appContext.getBean(IAppServiceService.class);
        appServiceFactory = appContext.getBean(IFactoryAppService.class);
        appServiceHeaderService = appContext.getBean(IAppServiceHeaderService.class);
        appServiceContentService = appContext.getBean(IAppServiceContentService.class);
        appServiceContentFactory = appContext.getBean(IFactoryAppServiceContent.class);
        appServiceHeaderFactory = appContext.getBean(IFactoryAppServiceHeader.class);
        AppService appService = appServiceFactory.create(service, type, method, application, group, serviceRequest, description, servicePath, attachementurl, operation, request.getRemoteUser(), null, null, null);
        ans = appServiceService.create(appService);
        finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
        if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            /**
             * Adding Log entry.
             */
            logEventService = appContext.getBean(ILogEventService.class);
            logEventService.createForPrivateCalls("/CreateAppService", "CREATE", "Create AppService : " + service, request);
        }
        // Update content
        if (request.getParameter("contentList") != null) {
            JSONArray objContentArray = new JSONArray(request.getParameter("contentList"));
            List<AppServiceContent> contentList = new ArrayList();
            contentList = getContentListFromRequest(request, appContext, service, objContentArray);
            // Update the Database with the new list.
            ans = appServiceContentService.compareListAndUpdateInsertDeleteElements(service, contentList);
            finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
        }
        // Update header
        if (request.getParameter("headerList") != null) {
            JSONArray objHeaderArray = new JSONArray(request.getParameter("headerList"));
            List<AppServiceHeader> headerList = new ArrayList();
            headerList = getHeaderListFromRequest(request, appContext, service, objHeaderArray);
            // Update the Database with the new list.
            ans = appServiceHeaderService.compareListAndUpdateInsertDeleteElements(service, headerList);
            finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
        }
    }
    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());
    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}
Also used : IFactoryAppService(org.cerberus.crud.factory.IFactoryAppService) AppService(org.cerberus.crud.entity.AppService) MessageEvent(org.cerberus.engine.entity.MessageEvent) IAppServiceHeaderService(org.cerberus.crud.service.IAppServiceHeaderService) JSONArray(org.json.JSONArray) IFactoryAppServiceContent(org.cerberus.crud.factory.IFactoryAppServiceContent) AppServiceContent(org.cerberus.crud.entity.AppServiceContent) ArrayList(java.util.ArrayList) IFactoryAppServiceHeader(org.cerberus.crud.factory.IFactoryAppServiceHeader) AppServiceHeader(org.cerberus.crud.entity.AppServiceHeader) IAppServiceService(org.cerberus.crud.service.IAppServiceService) IFactoryAppServiceHeader(org.cerberus.crud.factory.IFactoryAppServiceHeader) Answer(org.cerberus.util.answer.Answer) IFactoryAppService(org.cerberus.crud.factory.IFactoryAppService) ApplicationContext(org.springframework.context.ApplicationContext) JSONObject(org.json.JSONObject) IAppServiceContentService(org.cerberus.crud.service.IAppServiceContentService) IFactoryAppServiceContent(org.cerberus.crud.factory.IFactoryAppServiceContent) ILogEventService(org.cerberus.crud.service.ILogEventService)

Example 4 with AppService

use of org.cerberus.crud.entity.AppService in project cerberus-source by cerberustesting.

the class AppServiceDAO method findAppServiceByLikeName.

@Override
public AnswerList findAppServiceByLikeName(String service, int limit) {
    AnswerList response = new AnswerList();
    boolean throwEx = false;
    AppService result = null;
    final String query = "SELECT * FROM appservice srv WHERE `service` LIKE ? limit ?";
    List<AppService> objectList = new ArrayList<AppService>();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    Connection connection = this.databaseSpring.connect();
    try {
        PreparedStatement preStat = connection.prepareStatement(query);
        try {
            preStat.setString(1, "%" + service + "%");
            preStat.setInt(2, limit);
            ResultSet resultSet = preStat.executeQuery();
            try {
                while (resultSet.next()) {
                    objectList.add(this.loadFromResultSet(resultSet));
                }
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
                msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "SELECT"));
                resultSet = preStat.executeQuery("SELECT FOUND_ROWS()");
                int nrTotalRows = 0;
                if (resultSet != null && resultSet.next()) {
                    nrTotalRows = resultSet.getInt(1);
                }
                response = new AnswerList(objectList, nrTotalRows);
            } catch (SQLException exception) {
                LOG.warn("Unable to execute query : " + exception.toString());
            } finally {
                resultSet.close();
            }
        } catch (SQLException exception) {
            LOG.warn("Unable to execute query : " + exception.toString());
        } finally {
            preStat.close();
        }
    } catch (SQLException exception) {
        LOG.warn("Unable to execute query : " + exception.toString());
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            LOG.warn("Exception closing connection : " + e.toString());
        }
    }
    response.setResultMessage(msg);
    response.setDataList(objectList);
    return response;
}
Also used : AnswerList(org.cerberus.util.answer.AnswerList) IFactoryAppService(org.cerberus.crud.factory.IFactoryAppService) AppService(org.cerberus.crud.entity.AppService) FactoryAppService(org.cerberus.crud.factory.impl.FactoryAppService) SQLException(java.sql.SQLException) MessageEvent(org.cerberus.engine.entity.MessageEvent) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 5 with AppService

use of org.cerberus.crud.entity.AppService in project cerberus-source by cerberustesting.

the class FactoryAppService method create.

@Override
public AppService create(String service, String type, String method, String application, String group, String serviceRequest, String description, String servicePath, String attachementURL, String operation, String usrCreated, Timestamp dateCreated, String usrModif, Timestamp dateModif) {
    AppService s = new AppService();
    s.setService(service);
    s.setServiceRequest(serviceRequest);
    s.setGroup(group);
    s.setDescription(description);
    s.setServicePath(servicePath);
    s.setAttachementURL(attachementURL);
    s.setOperation(operation);
    s.setMethod(method);
    s.setApplication(application);
    s.setType(type);
    s.setUsrCreated(usrCreated);
    s.setUsrModif(usrModif);
    s.setDateCreated(dateCreated);
    s.setDateModif(dateModif);
    List<AppServiceContent> objectContentList = new ArrayList<>();
    s.setContentList(objectContentList);
    List<AppServiceHeader> objectHeaderList = new ArrayList<>();
    s.setHeaderList(objectHeaderList);
    List<AppServiceHeader> objectResponseHeaderList = new ArrayList<>();
    s.setResponseHeaderList(objectResponseHeaderList);
    return s;
}
Also used : AppService(org.cerberus.crud.entity.AppService) IFactoryAppService(org.cerberus.crud.factory.IFactoryAppService) AppServiceContent(org.cerberus.crud.entity.AppServiceContent) ArrayList(java.util.ArrayList) AppServiceHeader(org.cerberus.crud.entity.AppServiceHeader)

Aggregations

AppService (org.cerberus.crud.entity.AppService)21 AnswerItem (org.cerberus.util.answer.AnswerItem)13 MessageEvent (org.cerberus.engine.entity.MessageEvent)12 IFactoryAppService (org.cerberus.crud.factory.IFactoryAppService)11 ArrayList (java.util.ArrayList)9 AppServiceHeader (org.cerberus.crud.entity.AppServiceHeader)7 IAppServiceService (org.cerberus.crud.service.IAppServiceService)7 CerberusException (org.cerberus.exception.CerberusException)7 JSONObject (org.json.JSONObject)7 AppServiceContent (org.cerberus.crud.entity.AppServiceContent)6 AnswerList (org.cerberus.util.answer.AnswerList)6 Connection (java.sql.Connection)4 PreparedStatement (java.sql.PreparedStatement)4 ResultSet (java.sql.ResultSet)4 SQLException (java.sql.SQLException)4 IFactoryAppServiceHeader (org.cerberus.crud.factory.IFactoryAppServiceHeader)4 JSONArray (org.json.JSONArray)4 ApplicationContext (org.springframework.context.ApplicationContext)4 IOException (java.io.IOException)3 List (java.util.List)3