Search in sources :

Example 11 with ApplicationObject

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

the class ReadApplicationObject method findApplicationObject.

private AnswerItem findApplicationObject(String application, String objecta, ApplicationContext appContext, boolean userHasPermissions, HttpServletRequest request) throws JSONException {
    AnswerItem item = new AnswerItem();
    JSONObject object = new JSONObject();
    applicationObjectService = appContext.getBean(IApplicationObjectService.class);
    AnswerItem resp = applicationObjectService.readByKey(application, objecta);
    JSONObject jsonObject = null;
    if (resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null) {
        // the service was able to perform the query, then we should get all values
        jsonObject = convertApplicationObjectToJSONObject((ApplicationObject) resp.getItem());
    }
    object.put("hasPermissions", userHasPermissions);
    object.put("contentTable", jsonObject);
    item.setItem(object);
    item.setResultMessage(resp.getResultMessage());
    return item;
}
Also used : JSONObject(org.json.JSONObject) ApplicationObject(org.cerberus.crud.entity.ApplicationObject) IApplicationObjectService(org.cerberus.crud.service.IApplicationObjectService) AnswerItem(org.cerberus.util.answer.AnswerItem)

Example 12 with ApplicationObject

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

the class CreateApplicationObject 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
 * @throws CerberusException
 * @throws JSONException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding();
    response.setContentType("application/json");
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    Map<String, String> fileData = new HashMap<String, String>();
    FileItem file = null;
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        List<FileItem> fields = upload.parseRequest(request);
        Iterator<FileItem> it = fields.iterator();
        if (!it.hasNext()) {
            return;
        }
        while (it.hasNext()) {
            FileItem fileItem = it.next();
            boolean isFormField = fileItem.isFormField();
            if (isFormField) {
                fileData.put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
            } else {
                file = fileItem;
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
    /**
     * Parsing and securing all required parameters.
     */
    // 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 application = ParameterParserUtil.parseStringParamAndDecode(fileData.get("application"), null, charset);
    String object = ParameterParserUtil.parseStringParamAndDecode(fileData.get("object"), null, charset);
    String value = ParameterParserUtil.parseStringParam(fileData.get("value"), null);
    String usrcreated = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getRemoteUser(), "", charset);
    String datecreated = new Timestamp(new java.util.Date().getTime()).toString();
    String usrmodif = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getRemoteUser(), "", charset);
    String datemodif = new Timestamp(new java.util.Date().getTime()).toString();
    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(application)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "ApplicationObject").replace("%OPERATION%", "Create").replace("%REASON%", "Application name is missing!"));
        ans.setResultMessage(msg);
    } else if (StringUtil.isNullOrEmpty(object)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "ApplicationObject").replace("%OPERATION%", "Create").replace("%REASON%", "Object name is missing!"));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IApplicationObjectService applicationobjectService = appContext.getBean(IApplicationObjectService.class);
        IFactoryApplicationObject factoryApplicationobject = appContext.getBean(IFactoryApplicationObject.class);
        String fileName = "";
        if (file != null) {
            fileName = file.getName();
        }
        ApplicationObject applicationData = factoryApplicationobject.create(-1, application, object, value, fileName, usrcreated, datecreated, usrmodif, datemodif);
        ans = applicationobjectService.create(applicationData);
        if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            /**
             * Object created. Adding Log entry.
             */
            ILogEventService logEventService = appContext.getBean(LogEventService.class);
            logEventService.createForPrivateCalls("/CreateApplicationObject", "CREATE", "Create Application Object: ['" + application + "','" + object + "']", request);
            if (file != null) {
                AnswerItem an = applicationobjectService.readByKey(application, object);
                if (an.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && an.getItem() != null) {
                    applicationData = (ApplicationObject) an.getItem();
                    ans = applicationobjectService.uploadFile(applicationData.getID(), file);
                    if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    }
                }
            }
        }
    }
    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());
    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}
Also used : IFactoryApplicationObject(org.cerberus.crud.factory.IFactoryApplicationObject) PolicyFactory(org.owasp.html.PolicyFactory) HashMap(java.util.HashMap) MessageEvent(org.cerberus.engine.entity.MessageEvent) ILogEventService(org.cerberus.crud.service.ILogEventService) LogEventService(org.cerberus.crud.service.impl.LogEventService) Timestamp(java.sql.Timestamp) ApplicationContext(org.springframework.context.ApplicationContext) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ILogEventService(org.cerberus.crud.service.ILogEventService) IFactoryApplicationObject(org.cerberus.crud.factory.IFactoryApplicationObject) ApplicationObject(org.cerberus.crud.entity.ApplicationObject) IApplicationObjectService(org.cerberus.crud.service.IApplicationObjectService) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) AnswerItem(org.cerberus.util.answer.AnswerItem) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) Answer(org.cerberus.util.answer.Answer) FileItem(org.apache.commons.fileupload.FileItem) JSONObject(org.json.JSONObject) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 13 with ApplicationObject

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

the class FactoryApplicationObject method create.

@Override
public ApplicationObject create(String application, String object) {
    ApplicationObject ao = new ApplicationObject();
    ao.setApplication(application);
    ao.setObject(object);
    return ao;
}
Also used : ApplicationObject(org.cerberus.crud.entity.ApplicationObject) IFactoryApplicationObject(org.cerberus.crud.factory.IFactoryApplicationObject)

Example 14 with ApplicationObject

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

the class ApplicationObjectDAO method readImageByKey.

@Override
public BufferedImage readImageByKey(String application, String object) {
    BufferedImage image = null;
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED).resolveDescription("DESCRIPTION", "cerberus_applicationobject_path Parameter not found");
    AnswerItem a = parameterService.readByKey("", "cerberus_applicationobject_path");
    if (a.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
        Parameter p = (Parameter) a.getItem();
        String uploadPath = p.getValue();
        a = readByKey(application, object);
        if (a.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            ApplicationObject ao = (ApplicationObject) a.getItem();
            if (ao != null) {
                File picture = new File(uploadPath + File.separator + ao.getID() + File.separator + ao.getScreenShotFileName());
                try {
                    image = ImageIO.read(picture);
                } catch (IOException e) {
                    LOG.warn("Impossible to read the image");
                }
            }
        } else {
            LOG.warn("Application Object not found");
        }
    } else {
        LOG.warn("cerberus_applicationobject_path Parameter not found");
    }
    a.setResultMessage(msg);
    return image;
}
Also used : MessageEvent(org.cerberus.engine.entity.MessageEvent) IFactoryApplicationObject(org.cerberus.crud.factory.IFactoryApplicationObject) ApplicationObject(org.cerberus.crud.entity.ApplicationObject) Parameter(org.cerberus.crud.entity.Parameter) IOException(java.io.IOException) AnswerItem(org.cerberus.util.answer.AnswerItem) File(java.io.File) BufferedImage(java.awt.image.BufferedImage)

Example 15 with ApplicationObject

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

the class ApplicationObjectDAO method readByApplicationByCriteria.

@Override
public AnswerList readByApplicationByCriteria(String application, int start, int amount, String column, String dir, String searchTerm, Map<String, List<String>> individualSearch) {
    AnswerList response = new AnswerList();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    List<ApplicationObject> objectList = new ArrayList<ApplicationObject>();
    StringBuilder searchSQL = new StringBuilder();
    List<String> individalColumnSearchValues = new ArrayList<String>();
    StringBuilder query = new StringBuilder();
    // SQL_CALC_FOUND_ROWS allows to retrieve the total number of columns by disrearding the limit clauses that
    // were applied -- used for pagination p
    query.append("SELECT SQL_CALC_FOUND_ROWS * FROM applicationobject ");
    searchSQL.append(" where 1=1 ");
    if (!StringUtil.isNullOrEmpty(searchTerm)) {
        searchSQL.append(" and (`Application` like ?");
        searchSQL.append(" or `Object` like ?");
        searchSQL.append(" or `Value` like ?");
        searchSQL.append(" or `ScreenshotFileName` like ?");
        searchSQL.append(" or `UsrCreated` like ?");
        searchSQL.append(" or `DateCreated` like ?");
        searchSQL.append(" or `UsrModif` like ?");
        searchSQL.append(" or `DateModif` like ?)");
    }
    if (individualSearch != null && !individualSearch.isEmpty()) {
        searchSQL.append(" and ( 1=1 ");
        for (Map.Entry<String, List<String>> entry : individualSearch.entrySet()) {
            searchSQL.append(" and ");
            searchSQL.append(SqlUtil.getInSQLClauseForPreparedStatement(entry.getKey(), entry.getValue()));
            individalColumnSearchValues.addAll(entry.getValue());
        }
        searchSQL.append(" )");
    }
    if (!StringUtil.isNullOrEmpty(application)) {
        searchSQL.append(" and (`Application` = ? )");
    }
    query.append(searchSQL);
    if (!StringUtil.isNullOrEmpty(column)) {
        query.append(" order by `").append(column).append("` ").append(dir);
    }
    if ((amount <= 0) || (amount >= MAX_ROW_SELECTED)) {
        query.append(" limit ").append(start).append(" , ").append(MAX_ROW_SELECTED);
    } else {
        query.append(" limit ").append(start).append(" , ").append(amount);
    }
    // Debug message on SQL.
    if (LOG.isDebugEnabled()) {
        LOG.debug("SQL : " + query.toString());
    }
    Connection connection = this.databaseSpring.connect();
    try {
        PreparedStatement preStat = connection.prepareStatement(query.toString());
        try {
            int i = 1;
            if (!StringUtil.isNullOrEmpty(searchTerm)) {
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
            }
            for (String individualColumnSearchValue : individalColumnSearchValues) {
                preStat.setString(i++, individualColumnSearchValue);
            }
            if (!StringUtil.isNullOrEmpty(application)) {
                preStat.setString(i++, application);
            }
            ResultSet resultSet = preStat.executeQuery();
            try {
                // gets the data
                while (resultSet.next()) {
                    objectList.add(this.loadFromResultSet(resultSet));
                }
                // get the total number of rows
                resultSet = preStat.executeQuery("SELECT FOUND_ROWS()");
                int nrTotalRows = 0;
                if (resultSet != null && resultSet.next()) {
                    nrTotalRows = resultSet.getInt(1);
                }
                if (objectList.size() >= MAX_ROW_SELECTED) {
                    // Result of SQl was limited by MAX_ROW_SELECTED constrain. That means that we may miss some lines in the resultList.
                    LOG.error("Partial Result in the query.");
                    msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_WARNING_PARTIAL_RESULT);
                    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", "Maximum row reached : " + MAX_ROW_SELECTED));
                    response = new AnswerList(objectList, nrTotalRows);
                } else if (objectList.size() <= 0) {
                    msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_NO_DATA_FOUND);
                    response = new AnswerList(objectList, nrTotalRows);
                } else {
                    msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
                    msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "SELECT"));
                    response = new AnswerList(objectList, nrTotalRows);
                }
            } catch (SQLException exception) {
                LOG.error("Unable to execute query : " + exception.toString());
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
                msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString()));
            } finally {
                if (resultSet != null) {
                    resultSet.close();
                }
            }
        } catch (SQLException exception) {
            LOG.error("Unable to execute query : " + exception.toString());
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
            msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString()));
        } finally {
            if (preStat != null) {
                preStat.close();
            }
        }
    } catch (SQLException exception) {
        LOG.error("Unable to execute query : " + exception.toString());
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
        msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString()));
    } finally {
        try {
            if (!this.databaseSpring.isOnTransaction()) {
                if (connection != null) {
                    connection.close();
                }
            }
        } catch (SQLException exception) {
            LOG.warn("Unable to close connection : " + exception.toString());
        }
    }
    response.setResultMessage(msg);
    response.setDataList(objectList);
    return response;
}
Also used : AnswerList(org.cerberus.util.answer.AnswerList) SQLException(java.sql.SQLException) MessageEvent(org.cerberus.engine.entity.MessageEvent) IFactoryApplicationObject(org.cerberus.crud.factory.IFactoryApplicationObject) ApplicationObject(org.cerberus.crud.entity.ApplicationObject) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) ResultSet(java.sql.ResultSet) AnswerList(org.cerberus.util.answer.AnswerList) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map)

Aggregations

ApplicationObject (org.cerberus.crud.entity.ApplicationObject)16 AnswerItem (org.cerberus.util.answer.AnswerItem)11 IFactoryApplicationObject (org.cerberus.crud.factory.IFactoryApplicationObject)9 MessageEvent (org.cerberus.engine.entity.MessageEvent)9 IApplicationObjectService (org.cerberus.crud.service.IApplicationObjectService)7 JSONObject (org.json.JSONObject)7 Connection (java.sql.Connection)5 PreparedStatement (java.sql.PreparedStatement)5 ResultSet (java.sql.ResultSet)5 SQLException (java.sql.SQLException)5 AnswerList (org.cerberus.util.answer.AnswerList)5 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)3 ILogEventService (org.cerberus.crud.service.ILogEventService)3 LogEventService (org.cerberus.crud.service.impl.LogEventService)3 Answer (org.cerberus.util.answer.Answer)3 ApplicationContext (org.springframework.context.ApplicationContext)3 Timestamp (java.sql.Timestamp)2 List (java.util.List)2 Map (java.util.Map)2