/**
   * Realizando o upload do arquivo informado
   *
   * @author Raphael Rossiter
   * @date 30/07/2009
   * @param HttpServletRequest
   */
  private Object[] recebendoObjetos(HttpServletRequest httpServletRequest)
      throws FileUploadException {

    Object[] parametrosFormulario = new Object[2];

    DiskFileUpload upload = new DiskFileUpload();

    List itens = upload.parseRequest(httpServletRequest);
    FileItem fileItem = null;

    if (itens != null) {

      Iterator iter = itens.iterator();

      while (iter.hasNext()) {

        fileItem = (FileItem) iter.next();

        if (fileItem.getFieldName().equals("arquivoAnexo")) {

          parametrosFormulario[0] = fileItem;
        }

        if (fileItem.getFieldName().equals("observacaoAnexo")) {

          parametrosFormulario[1] = fileItem.getString();
        }
      }
    }

    return parametrosFormulario;
  }
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
      chain.doFilter(request, response);
      return;
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    boolean isMultipartContent = FileUpload.isMultipartContent(httpRequest);
    if (!isMultipartContent) {
      chain.doFilter(request, response);
      return;
    }

    DiskFileUpload upload = new DiskFileUpload();
    if (repositoryPath != null) upload.setRepositoryPath(repositoryPath);

    try {
      List list = upload.parseRequest(httpRequest);
      final Map map = new HashMap();
      for (int i = 0; i < list.size(); i++) {
        FileItem item = (FileItem) list.get(i);
        String str = item.getString();
        if (item.isFormField()) map.put(item.getFieldName(), new String[] {str});
        else httpRequest.setAttribute(item.getFieldName(), item);
      }

      chain.doFilter(
          new HttpServletRequestWrapper(httpRequest) {
            public Map getParameterMap() {
              return map;
            }

            public String[] getParameterValues(String name) {
              Map map = getParameterMap();
              return (String[]) map.get(name);
            }

            public String getParameter(String name) {
              String[] params = getParameterValues(name);
              if (params == null) return null;
              return params[0];
            }

            public Enumeration getParameterNames() {
              Map map = getParameterMap();
              return Collections.enumeration(map.keySet());
            }
          },
          response);
    } catch (FileUploadException ex) {
      ServletException servletEx = new ServletException();
      servletEx.initCause(ex);
      throw servletEx;
    }
  }
示例#3
0
  public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);

    fileUpload = new DiskFileUpload();
    fileUpload.setHeaderEncoding("UTF-8");
    fileUpload.setSizeMax(verticalProperties.getMultiPartRequestMaxSize());
    fileUpload.setSizeThreshold(64000);

    // Parameters for the mail sent to users when generating a new password:
    SMTP_HOST = verticalProperties.getMailSmtpHost();
    if (SMTP_HOST == null) {
      SMTP_HOST = "mail.enonic.com";
    }
  }
  public ActionForward execute(
      ActionMapping actionMapping,
      ActionForm actionForm,
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse) {

    // Seta o mapeamento de retorno
    ActionForward retorno = actionMapping.findForward("exibirGerarAvisoDeDebito");

    DiskFileUpload upload = new DiskFileUpload();
    List items = null;
    try {
      items = upload.parseRequest(httpServletRequest);
      this.getSessao(httpServletRequest).setAttribute("arquivo", items);
    } catch (FileUploadException e) {
      items = (List) this.getSessao(httpServletRequest).getAttribute("arquivo");
      if (items == null) {
        throw new ActionServletException("erro.sistema", e);
      }
    }

    FileItem item = (FileItem) Util.retonarObjetoDeColecao(items);
    String nomeArquivo = item.getName().replace(".txt", "");
    nomeArquivo = nomeArquivo.replace("EMITIR", "");

    Collection colecaoEmitirReavisoDeDebitoHelper =
        this.gerarColecaoEmitirReavisoDeDebitoHelper(items);

    String tipoRelatorio = httpServletRequest.getParameter("tipoRelatorio");

    RelatorioAvisoDeDebito relatorio =
        new RelatorioAvisoDeDebito(this.getUsuarioLogado(httpServletRequest));

    relatorio.addParametro(
        "colecaoEmitirReavisoDeDebitoHelper", colecaoEmitirReavisoDeDebitoHelper);
    relatorio.addParametro("nomeArquivo", nomeArquivo);

    if (tipoRelatorio == null) {
      tipoRelatorio = TarefaRelatorio.TIPO_PDF + "";
    }

    relatorio.addParametro("tipoFormatoRelatorio", Integer.parseInt(tipoRelatorio));
    retorno =
        processarExibicaoRelatorio(
            relatorio, tipoRelatorio, httpServletRequest, httpServletResponse, actionMapping);

    return retorno;
  }
示例#5
0
  /**
   * Parses the input stream and partitions the parsed items into a set of form fields and a set of
   * file items.
   *
   * @param request The multipart request wrapper.
   * @param servletContext Our ServletContext object
   * @return multipart processed request
   * @throws HdivMultipartException if an unrecoverable error occurs.
   */
  public HttpServletRequest handleMultipartRequest(
      RequestWrapper request, ServletContext servletContext) throws HdivMultipartException {

    DiskFileUpload upload = new DiskFileUpload();

    upload.setHeaderEncoding(request.getCharacterEncoding());
    // Set the maximum size before a FileUploadException will be thrown.
    upload.setSizeMax(getSizeMax());
    // Set the maximum size that will be stored in memory.
    upload.setSizeThreshold((int) getSizeThreshold());
    // Set the the location for saving data on disk.
    upload.setRepositoryPath(getRepositoryPath(servletContext));

    List<FileItem> items = null;
    try {
      items = upload.parseRequest(request);

    } catch (DiskFileUpload.SizeLimitExceededException e) {
      if (log.isErrorEnabled()) {
        log.error("Size limit exceeded exception");
      }
      // Special handling for uploads that are too big.
      throw new HdivMultipartException(e);

    } catch (FileUploadException e) {
      if (log.isErrorEnabled()) {
        log.error("Failed to parse multipart request", e);
      }
      throw new HdivMultipartException(e);
    }

    // Process the uploaded items
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
      FileItem item = iter.next();

      if (item.isFormField()) {
        this.addTextParameter(request, item);
      } else {
        this.addFileParameter(request, item);
      }
    }
    return request;
  }
示例#6
0
  private ExtendedMap parseMultiPartRequest(HttpServletRequest request)
      throws FileUploadException, IOException {
    ExtendedMap formItems = new ExtendedMap();
    List paramList = fileUpload.parseRequest(request);
    for (Object parameter : paramList) {
      FileItem fileItem = (FileItem) parameter;

      String name = fileItem.getFieldName();

      if (fileItem.isFormField()) {
        String value = fileItem.getString("UTF-8");
        if (formItems.containsKey(name)) {
          ArrayList<Object> values = new ArrayList<Object>();
          Object obj = formItems.get(name);
          if (obj instanceof Object[]) {
            String[] objArray = (String[]) obj;
            for (int i = 0; i < objArray.length; i++) {
              values.add(objArray[i]);
            }
          } else {
            values.add(obj);
          }
          values.add(value);
          formItems.put(name, values.toArray(new String[values.size()]));
        } else {
          formItems.put(name, value);
        }
      } else {
        if (fileItem.getSize() > 0) {
          if (formItems.containsKey(name)) {
            ArrayList<Object> values = new ArrayList<Object>();
            Object obj = formItems.get(name);
            if (obj instanceof FileItem[]) {
              FileItem[] objArray = (FileItem[]) obj;
              for (int i = 0; i < objArray.length; i++) {
                values.add(objArray[i]);
              }
            } else {
              values.add(obj);
            }
            values.add(fileItem);
            formItems.put(name, values.toArray(new FileItem[values.size()]));
          } else {
            formItems.put(name, fileItem);
          }
        }
      }
    }

    // Add parameters from url
    Map paramMap = URLUtil.decodeParameterMap(request.getParameterMap());
    for (Object parameterEntry : paramMap.entrySet()) {
      Map.Entry entry = (Map.Entry) parameterEntry;
      String key = (String) entry.getKey();
      String[] values = (String[]) entry.getValue();
      for (String value : values) {
        formItems.put(key, value);
      }
    }

    // Remove all empty parameters that are NOT in an array
    ArrayList<String> remove = new ArrayList<String>();
    for (Object parameterKey : formItems.keySet()) {
      String key = (String) parameterKey;
      Object value = formItems.get(key);
      if (!(value instanceof String[])
          && value instanceof String
          && ((String) value).length() == 0) {
        remove.add(key);
      }
    }
    for (String key : remove) {
      formItems.remove(key);
    }

    return formItems;
  }
  public ModelAndView addDocuments(HttpServletRequest request, HttpServletResponse response)
      throws ServletException {
    JSONObject jobj = new JSONObject();
    JSONObject myjobj = new JSONObject();
    List fileItems = null;
    KwlReturnObject kmsg = null;
    String auditAction = "";
    boolean applicant = false;
    String id = java.util.UUID.randomUUID().toString();
    PrintWriter out = null;
    // Create transaction
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);
    try {
      response.setContentType("text/html;charset=UTF-8");
      out = response.getWriter();
      String userid = sessionHandlerImplObj.getUserid(request);
      String map = request.getParameter("mapid");
      HashMap<String, String> arrParam = new HashMap<String, String>();
      boolean fileUpload = false;
      String docdesc;
      ArrayList<FileItem> fi = new ArrayList<FileItem>();
      if (request.getParameter("fileAdd") != null) {
        DiskFileUpload fu = new DiskFileUpload();
        fileItems = fu.parseRequest(request);
        documentDAOObj.parseRequest(fileItems, arrParam, fi, fileUpload);
        arrParam.put("IsIE", request.getParameter("IsIE"));
        if (arrParam.get("applicantid").equalsIgnoreCase("applicant")) {
          applicant = true;
          userid = arrParam.get("refid");
        }
        if (StringUtil.isNullOrEmpty((String) arrParam.get("docdesc")) == false) {
          docdesc = (String) arrParam.get("docdesc");
        }
      }
      for (int cnt = 0; cnt < fi.size(); cnt++) {
        String docID;
        if (applicant) {
          kmsg =
              hrmsExtApplDocsDAOObj.uploadFile(
                  fi.get(cnt),
                  userid,
                  arrParam,
                  profileHandlerDAOObj.getUserFullName(sessionHandlerImplObj.getUserid(request)));
          HrmsDocs doc = (HrmsDocs) kmsg.getEntityList().get(0);
          docID = doc.getDocid();
        } else {
          kmsg = documentDAOObj.uploadFile(fi.get(cnt), userid, arrParam);
          Docs doc = (Docs) kmsg.getEntityList().get(0);
          docID = doc.getDocid();
        }

        String companyID = sessionHandlerImplObj.getCompanyid(request);
        String userID = sessionHandlerImplObj.getUserid(request);
        String refid = arrParam.get("refid");
        jobj.put("userid", userID);
        jobj.put("docid", docID);
        jobj.put("companyid", companyID);
        jobj.put("id", id);
        jobj.put("map", map);
        jobj.put("refid", refid);
        if (arrParam.get("applicantid").equalsIgnoreCase("applicant")) {
          hrmsExtApplDocsDAOObj.saveDocumentMapping(jobj);
        } else {
          documentDAOObj.saveDocumentMapping(jobj);
        }
      }
      myjobj.put("ID", id);
      txnManager.commit(status);
    } catch (Exception e) {
      System.out.println(e.getMessage());
      txnManager.rollback(status);
    } finally {
      out.close();
    }
    return new ModelAndView("jsonView", "model", myjobj.toString());
  }
  /**
   * Process the blog entries
   *
   * @param httpServletRequest Request
   * @param httpServletResponse Response
   * @param user {@link org.blojsom.blog.BlogUser} instance
   * @param context Context
   * @param entries Blog entries retrieved for the particular request
   * @return Modified set of blog entries
   * @throws BlojsomPluginException If there is an error processing the blog entries
   */
  public BlogEntry[] process(
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      BlogUser user,
      Map context,
      BlogEntry[] entries)
      throws BlojsomPluginException {
    if (!authenticateUser(httpServletRequest, httpServletResponse, context, user)) {
      httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_LOGIN_PAGE);

      return entries;
    }

    String username = getUsernameFromSession(httpServletRequest, user.getBlog());
    if (!checkPermission(user, null, username, FILE_UPLOAD_PERMISSION)) {
      httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE);
      addOperationResultMessage(context, "You are not allowed to upload files");

      return entries;
    }

    File resourceDirectory =
        new File(
            _blojsomConfiguration.getInstallationDirectory()
                + _resourcesDirectory
                + user.getId()
                + "/");

    String action = BlojsomUtils.getRequestValue(ACTION_PARAM, httpServletRequest);
    if (BlojsomUtils.checkNullOrBlank(action)) {
      _logger.debug("User did not request edit action");

      httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE);
    } else if (PAGE_ACTION.equals(action)) {
      _logger.debug("User requested file upload page");

      httpServletRequest.setAttribute(PAGE_PARAM, FILE_UPLOAD_PAGE);
    } else if (UPLOAD_FILE_ACTION.equals(action)) {
      _logger.debug("User requested file upload action");

      // Create a new disk file upload and set its parameters
      DiskFileUpload diskFileUpload = new DiskFileUpload();
      diskFileUpload.setRepositoryPath(_temporaryDirectory);
      diskFileUpload.setSizeThreshold(_maximumMemorySize);
      diskFileUpload.setSizeMax(_maximumUploadSize);

      try {
        List items = diskFileUpload.parseRequest(httpServletRequest);
        Iterator itemsIterator = items.iterator();
        while (itemsIterator.hasNext()) {
          FileItem item = (FileItem) itemsIterator.next();

          // Check for the file upload form item
          if (!item.isFormField()) {
            String itemNameWithoutPath = BlojsomUtils.getFilenameFromPath(item.getName());

            _logger.debug(
                "Found file item: " + itemNameWithoutPath + " of type: " + item.getContentType());

            // Is it one of the accepted file types?
            String fileType = item.getContentType();
            boolean isAcceptedFileType = _acceptedFileTypes.containsKey(fileType);

            String extension = BlojsomUtils.getFileExtension(itemNameWithoutPath);
            boolean isAcceptedFileExtension = true;
            for (int i = 0; i < _invalidFileExtensions.length; i++) {
              String invalidFileExtension = _invalidFileExtensions[i];
              if (itemNameWithoutPath.indexOf(invalidFileExtension) != -1) {
                isAcceptedFileExtension = false;
                break;
              }
            }

            // If so, upload the file to the resources directory
            if (isAcceptedFileType && isAcceptedFileExtension) {
              if (!resourceDirectory.exists()) {
                if (!resourceDirectory.mkdirs()) {
                  _logger.error(
                      "Unable to create resource directory for user: "******"Unable to create resource directory");
                  return entries;
                }
              }

              File resourceFile =
                  new File(
                      _blojsomConfiguration.getInstallationDirectory()
                          + _resourcesDirectory
                          + user.getId()
                          + "/"
                          + itemNameWithoutPath);
              try {
                item.write(resourceFile);
              } catch (Exception e) {
                _logger.error(e);
                addOperationResultMessage(
                    context, "Unknown error in file upload: " + e.getMessage());
              }

              String resourceURL =
                  user.getBlog().getBlogBaseURL()
                      + _blojsomConfiguration.getResourceDirectory()
                      + user.getId()
                      + "/"
                      + item.getName();

              _logger.debug("Successfully uploaded resource file: " + resourceFile.toString());
              addOperationResultMessage(
                  context,
                  "Successfully upload resource file: "
                      + item.getName()
                      + ". <p></p>Here is a link to <a href=\""
                      + resourceURL
                      + "\">"
                      + item.getName()
                      + "</a>. Right-click and copy the link to the resource to use in a blog entry.");
            } else {
              if (!isAcceptedFileExtension) {
                _logger.error("Upload file does not have an accepted extension: " + extension);
                addOperationResultMessage(
                    context, "Upload file does not have an accepted extension: " + extension);
              } else {
                _logger.error(
                    "Upload file is not an accepted type: "
                        + item.getName()
                        + " of type: "
                        + item.getContentType());
                addOperationResultMessage(
                    context,
                    "Upload file is not an accepted type: "
                        + item.getName()
                        + " of type: "
                        + item.getContentType());
              }
            }
          }
        }
      } catch (FileUploadException e) {
        _logger.error(e);
        addOperationResultMessage(context, "Unknown error in file upload: " + e.getMessage());
      }

      httpServletRequest.setAttribute(PAGE_PARAM, FILE_UPLOAD_PAGE);
    } else if (DELETE_UPLOAD_FILES.equals(action)) {
      String[] filesToDelete = httpServletRequest.getParameterValues(FILE_TO_DELETE);
      if (filesToDelete != null && filesToDelete.length > 0) {
        File deletedFile;
        for (int i = 0; i < filesToDelete.length; i++) {
          String fileToDelete = filesToDelete[i];
          deletedFile = new File(resourceDirectory, fileToDelete);
          if (!deletedFile.delete()) {
            _logger.debug("Unable to delete resource file: " + deletedFile.toString());
          }
        }

        addOperationResultMessage(
            context, "Deleted " + filesToDelete.length + " file(s) from resources directory");
      }

      httpServletRequest.setAttribute(PAGE_PARAM, FILE_UPLOAD_PAGE);
    }

    // Create a list of files in the user's resource directory
    Map resourceFilesMap = null;
    if (resourceDirectory.exists()) {
      File[] resourceFiles = resourceDirectory.listFiles();

      if (resourceFiles != null) {
        resourceFilesMap = new HashMap(resourceFiles.length);
        for (int i = 0; i < resourceFiles.length; i++) {
          File resourceFile = resourceFiles[i];
          resourceFilesMap.put(resourceFile.getName(), resourceFile.getName());
        }
      }
    } else {
      resourceFilesMap = new HashMap();
    }

    resourceFilesMap = new TreeMap(resourceFilesMap);
    context.put(PLUGIN_ADMIN_FILE_UPLOAD_FILES, resourceFilesMap);

    return entries;
  }
示例#9
0
  @SuppressWarnings({"unchecked", "deprecation"})
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response_message = "";
    HttpSession session = request.getSession();
    FileItem image_file = null;
    int record_id = 0;
    int image_id;
    InputStream instream = null;
    OutputStream full_outstream = null;
    OutputStream thumb_outstream = null;
    OutputStream regular_outstream = null;

    // Check if there is any input in the record id field
    if (request.getParameter("recordID") == null || request.getParameter("recordID").equals("")) {
      response_message = "<p><font color=ff0000>No ID entered!</font></p>";
      session.setAttribute("msg", response_message);
      response.sendRedirect("uploadImage.jsp");
    }

    try {
      // Parse the HTTP request to get the image stream
      DiskFileUpload fu = new DiskFileUpload();
      List<FileItem> FileItems = fu.parseRequest(request);

      // Process the uploaded items, assuming only 1 image file uploaded
      Iterator<FileItem> i = FileItems.iterator();

      while (i.hasNext()) {
        FileItem item = (FileItem) i.next();
        if (item.isFormField()) {
          if (item.getFieldName().equals("recordID")) {
            record_id = Integer.parseInt(item.getString());
            if (!isValidID(record_id)) {
              response_message = "<p><font color=ff0000>Invalid record id!</font></p>";
              session.setAttribute("msg", response_message);
              response.sendRedirect("uploadImage.jsp");
            }
          }
          // out.println(item.getFieldName() + ": " +
          // item.getString());
        } else {
          image_file = item;
          if (image_file.getName().equals("")) {
            response_message = "<p><font color=ff0000>No file selected!</font></p>";
            session.setAttribute("msg", response_message);
            response.sendRedirect("uploadImage.jsp");
          }
        }
      }

      // Get the image stream
      instream = image_file.getInputStream();

      BufferedImage full_image = ImageIO.read(instream);
      BufferedImage thumbnail = shrink(full_image, THUMBNAIL_SHRINK);
      BufferedImage regular_image = shrink(full_image, REGULAR_SHRINK);

      // Connect to the database
      db = new Database();
      db.connect();
      conn = db.getConnection();
      stmt = conn.createStatement();

      /*
       * First, to generate a unique pic_id using an SQL sequence
       */
      ResultSet rset1 = stmt.executeQuery(SQL_IMAGE_ID);
      rset1.next();
      image_id = rset1.getInt(1);

      // Insert an empty blob into the table first. Note that you have to
      // use the Oracle specific function empty_blob() to create an empty
      // blob
      stmt.execute(
          "INSERT INTO pacs_images VALUES("
              + record_id
              + ","
              + image_id
              + ", empty_blob(), empty_blob(), empty_blob())");

      // to retrieve the lob_locator
      // Note that you must use "FOR UPDATE" in the select statement
      String cmd = "SELECT * FROM pacs_images WHERE image_id = " + image_id + " FOR UPDATE";
      ResultSet rset = stmt.executeQuery(cmd);
      rset.next();
      BLOB thumb = ((OracleResultSet) rset).getBLOB("thumbnail");
      BLOB regular = ((OracleResultSet) rset).getBLOB("regular_size");
      BLOB full = ((OracleResultSet) rset).getBLOB("full_size");

      // Write the image to the blob object
      full_outstream = full.getBinaryOutputStream();
      ImageIO.write(full_image, "jpg", full_outstream);
      thumb_outstream = thumb.getBinaryOutputStream();
      ImageIO.write(thumbnail, "jpg", thumb_outstream);
      regular_outstream = regular.getBinaryOutputStream();
      ImageIO.write(regular_image, "jpg", regular_outstream);

      stmt.executeUpdate("commit");
      response_message = "<p>Upload OK!</p>";
      session.setAttribute("msg", response_message);
      response.sendRedirect("uploadImage.jsp");

    } catch (Exception ex) {
      response_message = ex.getMessage();
    } finally {
      if (instream != null) {
        instream.close();
      }
      if (full_outstream != null) {
        full_outstream.close();
      }
      if (thumb_outstream != null) {
        thumb_outstream.close();
      }
      if (regular_outstream != null) {
        regular_outstream.close();
      }
      db.close(conn, stmt, null, rset);
    }
  }
示例#10
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // Variable initializations.
    HttpSession session = request.getSession();
    FileItem image_file = null;
    int record_id = 0;
    int image_id;

    // Check if a record ID has been entered.
    if (request.getParameter("recordID") == null || request.getParameter("recordID").equals("")) {
      // If no ID has been entered, send message to jsp.
      response_message =
          "<p><font color=FF0000>No Record ID Detected, Please Enter One.</font></p>";
      session.setAttribute("msg", response_message);
      response.sendRedirect("UploadImage.jsp");
    }

    try {
      // Parse the HTTP request to get the image stream.
      DiskFileUpload fu = new DiskFileUpload();
      // Will get multiple image files if that happens and can be accessed through FileItems.
      List<FileItem> FileItems = fu.parseRequest(request);

      // Connect to the database and create a statement.
      conn = getConnected(drivername, dbstring, username, password);
      stmt = conn.createStatement();

      // Process the uploaded items, assuming only 1 image file uploaded.
      Iterator<FileItem> i = FileItems.iterator();

      while (i.hasNext()) {
        FileItem item = (FileItem) i.next();

        // Test if item is a form field and matches recordID.
        if (item.isFormField()) {
          if (item.getFieldName().equals("recordID")) {
            // Covert record id from string to integer.
            record_id = Integer.parseInt(item.getString());

            String sql = "select count(*) from radiology_record where record_id = " + record_id;
            int count = 0;

            try {
              rset = stmt.executeQuery(sql);

              while (rset != null && rset.next()) {
                count = (rset.getInt(1));
              }
            } catch (SQLException e) {
              response_message = e.getMessage();
            }

            // Check if recordID is in the database.
            if (count == 0) {
              // Invalid recordID, send message to jsp.
              response_message =
                  "<p><font color=FF0000>Record ID Does Not Exist In Database.</font></p>";
              session.setAttribute("msg", response_message);
              // Close connection.
              conn.close();
              response.sendRedirect("UploadImage.jsp");
            }
          }
        } else {
          image_file = item;

          if (image_file.getName().equals("")) {
            // No file, send message to jsp.
            response_message = "<p><font color=FF0000>No File Selected For Record ID.</font></p>";
            session.setAttribute("msg", response_message);
            // Close connection.
            conn.close();
            response.sendRedirect("UploadImage.jsp");
          }
        }
      }

      // Get the image stream.
      InputStream instream = image_file.getInputStream();

      BufferedImage full_image = ImageIO.read(instream);
      BufferedImage thumbnail = shrink(full_image, 10);
      BufferedImage regular_image = shrink(full_image, 5);

      // First, to generate a unique img_id using an SQL sequence.
      rset1 = stmt.executeQuery("SELECT image_id_sequence.nextval from dual");
      rset1.next();
      image_id = rset1.getInt(1);

      // Insert an empty blob into the table first. Note that you have to
      // use the Oracle specific function empty_blob() to create an empty blob.
      stmt.execute(
          "INSERT INTO pacs_images VALUES("
              + record_id
              + ","
              + image_id
              + ", empty_blob(), empty_blob(), empty_blob())");

      // to retrieve the lob_locator
      // Note that you must use "FOR UPDATE" in the select statement
      String cmd = "SELECT * FROM pacs_images WHERE image_id = " + image_id + " FOR UPDATE";
      rset = stmt.executeQuery(cmd);
      rset.next();
      BLOB myblobFull = ((OracleResultSet) rset).getBLOB(5);
      BLOB myblobThumb = ((OracleResultSet) rset).getBLOB(3);
      BLOB myblobRegular = ((OracleResultSet) rset).getBLOB(4);

      // Write the full size image to the blob object.
      OutputStream fullOutstream = myblobFull.getBinaryOutputStream();
      ImageIO.write(full_image, "jpg", fullOutstream);
      // Write the thumbnail size image to the blob object.
      OutputStream thumbOutstream = myblobThumb.getBinaryOutputStream();
      ImageIO.write(thumbnail, "jpg", thumbOutstream);
      // Write the regular size image to the blob object.
      OutputStream regularOutstream = myblobRegular.getBinaryOutputStream();
      ImageIO.write(regular_image, "jpg", regularOutstream);

      // Commit the changes to database.
      stmt.executeUpdate("commit");
      response_message = "<p><font color=00CC00>Upload Successful.</font></p>";
      session.setAttribute("msg", response_message);

      instream.close();
      fullOutstream.close();
      thumbOutstream.close();
      regularOutstream.close();

      // Close connection.
      conn.close();
      response.sendRedirect("UploadImage.jsp");

      instream.close();
      fullOutstream.close();
      thumbOutstream.close();
      regularOutstream.close();

      // Close connection.
      conn.close();
    } catch (Exception ex) {
      response_message = ex.getMessage();
    }
  }
  private void executeDeploy(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String contentType = null;
    File packageFile = null;
    FileItem item = null;
    String serviceName = null;
    String fieldName = null;
    String token = "";
    boolean forward = false;

    try {
      // checking if uploaded file is a file descriptor
      DiskFileUpload upload = new DiskFileUpload();
      List items = upload.parseRequest(req);

      Iterator iter = items.iterator();

      while (iter.hasNext()) {
        // geting item
        item = (FileItem) iter.next();

        contentType = item.getContentType();

        fieldName = item.getFieldName();
        if ((fieldName != null && fieldName.equals("importFile"))
            || (contentType != null && contentType.contains(ZIP_DEPLOY_PACKAGE_MIME_TYPE))) {

          packageFile = new File(System.getProperty("java.io.tmpdir"), item.getName());
          item.write(packageFile);

        } else if (fieldName.equals("newName")) {
          serviceName = item.getString();
        } else if (fieldName.equals("authToken")) {
          token = item.getString();
        } else if (fieldName.equals("forwardToPage")) {
          forward = true;
        }
      }

      String deployAdminToken = Toolbox.getInstance().getDeployAdminToken();
      if (deployAdminToken != null && token.equals(deployAdminToken) == false) {
        resp.sendError(500);
      }
    } catch (Exception e) {
      resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
      return;
    }

    if (serviceName == null || serviceName.equals("")) {
      serviceName = packageFile.getName();
      serviceName = serviceName.substring(0, serviceName.lastIndexOf('.'));
    }

    try {
      ServiceManager serviceManager;

      serviceManager = ServiceManager.getInstance();
      serviceManager.deployService(packageFile, serviceName);
    } catch (Exception e) {
      resp.sendRedirect(
          "selectImportOrCreate.jsp?serviceName=" + serviceName + "&error=serviceexist");
      return;
    }
    if (forward == true) {

      resp.sendRedirect("serviceConfiguration.jsp?serviceName=" + serviceName);
    } else {
      resp.setStatus(HttpServletResponse.SC_OK);
    }
  }
示例#12
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    super.doPost(request);
    logger.debug("Inicio.");

    PrintWriter out = response.getWriter();

    try {

      CResultadoOperacion resultadoOperacion;

      JAASUserPrincipal jassUserPrincipal = (JAASUserPrincipal) request.getUserPrincipal();
      PasarelaAdmcar.listaSesiones =
          (ListaSesiones)
              SessionsContextShared.getContextShared()
                  .getSharedAttribute(this.getServletContext(), "UserSessions");
      Sesion userSession = PasarelaAdmcar.listaSesiones.getSesion(jassUserPrincipal.getName());

      Principal userPrincipal = userSession.getUserPrincipal();
      Enumeration userPerms = userSession.getRoleGroup().members();

      /* - antes de MultipartPostMethod -
      String stream = request.getParameter("mensajeXML");
         logger.info("stream="+stream);
         */

      /* MultipartPostMethod */
      String stream = null;
      /** Recogemos los nuevos ficheros annadidos */
      Hashtable fileUploads = new Hashtable();
      // Create a new file upload handler
      DiskFileUpload upload = new DiskFileUpload();

      /** Set upload parameters */
      upload.setSizeThreshold(CConstantesComando.MaxMemorySize);
      upload.setSizeMax(CConstantesComando.MaxRequestSize);
      /*
      String yourTempDirectory= "anexos" + File.separator;
      upload.setRepositoryPath(yourTempDirectory);
      */

      // Parse the request
      try {
        //               request.setCharacterEncoding("ISO-8859-1");
        List items = upload.parseRequest(request);

        // Process the uploaded items
        Iterator iter = items.iterator();
        String sMunicipio = "";
        while (iter.hasNext()) {
          FileItem item = (FileItem) iter.next();

          String fieldName = item.getFieldName();
          if (item.isFormField()) {
            if (fieldName.equalsIgnoreCase("mensajeXML")) {
              stream = item.getString("ISO-8859-1");
              logger.info("MENSAJE XML:" + item.getString("ISO-8859-1"));
              System.out.println(
                  "CServletLicencias.doPost mensajeXML=" + item.getString("ISO-8859-1"));
            } else if (fieldName.equalsIgnoreCase(
                com.geopista.protocol.net.EnviarSeguro.idMunicipio)) {
              sMunicipio = item.getString("ISO-8859-1");
              userSession.setIdMunicipio(sMunicipio);
            }
          } else {
            CAnexo anexo = new CAnexo();
            /** Debido a que el nombre del fichero puede contener acentos. */
            fieldName = URLDecoder.decode(fieldName, "ISO-8859-1");
            anexo.setFileName(fieldName);
            anexo.setContent(item.get());
            fileUploads.put(fieldName, anexo);
          }
        }

      } catch (FileUploadBase.SizeLimitExceededException ex) {
        String respuesta =
            buildResponse(
                new CResultadoOperacion(false, "FileUploadBase.SizeLimitExceededException"));
        out.print(respuesta);
        out.flush();
        out.close();
        logger.warn("************************* FileUploadBase.SizeLimitExceededException");
        return;
      }

      // **********************************************************
      // ** Chequeamos
      // ******************************************************
      if ((stream == null) || (stream.trim().equals(""))) {
        String respuesta = buildResponse(new CResultadoOperacion(false, "stream es null"));
        out.print(respuesta);
        out.flush();
        out.close();
        logger.warn("stream null or empty. stream: " + stream);
        return;
      }

      StringReader sw = new StringReader(stream);
      logger.info("sw=" + sw.toString());

      CEnvioOperacion envioOperacion =
          (com.geopista.protocol.CEnvioOperacion)
              Unmarshaller.unmarshal(com.geopista.protocol.CEnvioOperacion.class, sw);
      logger.debug("envioOperacion.getComando(): " + envioOperacion.getComando());

      // CResultadoOperacion resultadoOperacion;
      String numExpediente;
      CSolicitudLicencia solicitudLicencia;
      CExpedienteLicencia expedienteLicencia;
      Hashtable hash;
      Vector vector = new Vector();

      switch (envioOperacion.getComando()) {
        case CConstantesComando.CMD_LICENCIAS_CREAR_EXPEDIENTE:
          solicitudLicencia = envioOperacion.getSolicitudLicencia();
          expedienteLicencia = envioOperacion.getExpedienteLicencia();

          /** inicio */
          /*
           * Cargamos en una hash los nombres de los anexos de la solicitud (marcados como annadidos, borrados, sin marcar).
           * El contenido de los marcados como annadidos, so se encuentra en el xml, sino en la hash fileUploads.
           */

          /* ANEXOS de solicitud. En la creacion no hay mejora de datos ni alegacion.
           * No tienen contenido.
           * Nos interesara recoger el estado (annadido, borrado) y el tipo de anexo.
           */
          /* SOLICITUD **/
          solicitudLicencia.setAnexos(
              actualizarAnexosUploaded(solicitudLicencia.getAnexos(), fileUploads));

          resultadoOperacion =
              COperacionesDatabaseLicencias.crearExpedienteLicencias(
                  solicitudLicencia,
                  expedienteLicencia,
                  userPrincipal,
                  userSession.getIdMunicipio());
          break;

        case CConstantesComando.CMD_LICENCIAS_MODIFICAR_EXPEDIENTE:
          solicitudLicencia = envioOperacion.getSolicitudLicencia();
          expedienteLicencia = envioOperacion.getExpedienteLicencia();

          /** inicio */
          /*
           * Cargamos en una hash los nombres de los anexos de la solicitud (marcados como annadidos, borrados, sin marcar).
           * El contenido de los marcados como annadidos, so se encuentra en el xml, sino en la hash fileUploads.
           */

          /*
           * No tienen contenido.
           * Nos interesara recoger el estado (annadido, borrado) y el tipo de anexo.
           */
          /** ANEXOS SOLICITUD */
          solicitudLicencia.setAnexos(
              actualizarAnexosUploaded(solicitudLicencia.getAnexos(), fileUploads));

          /* ANEXOS MEJORA DE DATOS */
          Vector vMejoras = solicitudLicencia.getMejoras();
          Vector vM = new Vector();
          if (vMejoras != null) {
            for (Enumeration e = vMejoras.elements(); e.hasMoreElements(); ) {
              Mejora mejora = (Mejora) e.nextElement();
              mejora.setAnexos(actualizarAnexosUploaded(mejora.getAnexos(), fileUploads));
              vM.add(mejora);
            }
            solicitudLicencia.setMejoras(vM);
          }

          /* ANEXOS ALEGACION */
          Alegacion alegacion = expedienteLicencia.getAlegacion();
          if (alegacion != null) {
            alegacion.setAnexos(actualizarAnexosUploaded(alegacion.getAnexos(), fileUploads));
            expedienteLicencia.setAlegacion(alegacion);
          }

          resultadoOperacion =
              COperacionesDatabaseLicencias.modificarExpedienteLicencias(
                  solicitudLicencia,
                  expedienteLicencia,
                  userPrincipal,
                  userSession.getIdMunicipio());
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_TIPOS_LICENCIA:
          resultadoOperacion = new CResultadoOperacion(true, "");
          resultadoOperacion.setVector(COperacionesDatabaseLicencias.getTiposLicencia());
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_TIPOS_OBRA:
          resultadoOperacion = new CResultadoOperacion(true, "");
          resultadoOperacion.setVector(COperacionesDatabaseLicencias.getTiposObra());
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_TIPOS_ANEXO:
          resultadoOperacion = new CResultadoOperacion(true, "");
          resultadoOperacion.setVector(COperacionesDatabaseLicencias.getTiposAnexo());
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_ESTADOS_DISPONIBLES:
          resultadoOperacion = new CResultadoOperacion(true, "");
          expedienteLicencia = (CExpedienteLicencia) envioOperacion.getParametro();
          int idTipoLicencia =
              new Integer(expedienteLicencia.getTipoLicenciaDescripcion()).intValue();
          resultadoOperacion.setVector(
              COperacionesDatabaseLicencias.getEstadosDisponibles(
                  expedienteLicencia, idTipoLicencia));
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_ESTADOS_PERMITIDOS:
          resultadoOperacion = new CResultadoOperacion(true, "");
          expedienteLicencia = (CExpedienteLicencia) envioOperacion.getParametro();
          idTipoLicencia = new Integer(expedienteLicencia.getTipoLicenciaDescripcion()).intValue();
          resultadoOperacion.setVector(
              COperacionesDatabaseLicencias.getEstadosPermitidos(
                  expedienteLicencia, userPerms, idTipoLicencia));
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_ESTADOS:
          resultadoOperacion = new CResultadoOperacion(true, "");
          Vector tiposLicencia = (Vector) envioOperacion.getTiposLicencia();
          resultadoOperacion.setVector(COperacionesDatabaseLicencias.getEstados(tiposLicencia));
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_VIAS_NOTIFICACION:
          resultadoOperacion = new CResultadoOperacion(true, "");
          resultadoOperacion.setVector(COperacionesDatabaseLicencias.getViasNotificacion());
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_SOLICITUD_LICENCIA:
          resultadoOperacion = new CResultadoOperacion(true, "");
          numExpediente = (String) envioOperacion.getParametro();
          String locale = (String) envioOperacion.getParametro2();
          tiposLicencia = (Vector) envioOperacion.getTiposLicencia();
          resultadoOperacion =
              COperacionesDatabaseLicencias.getExpedienteLicencia(
                  numExpediente, userSession.getIdMunicipio(), locale, tiposLicencia);
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_SOLICITUDES_LICENCIA:
          resultadoOperacion = new CResultadoOperacion(true, "");
          locale = (String) envioOperacion.getParametro2();
          tiposLicencia = (Vector) envioOperacion.getTiposLicencia();
          resultadoOperacion =
              COperacionesDatabaseLicencias.getSolicitudesLicencia(locale, tiposLicencia);
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_SEARCHED_EXPEDIENTES:
          resultadoOperacion = new CResultadoOperacion(true, "");
          hash = envioOperacion.getHashtable();
          resultadoOperacion.setVector(
              COperacionesDatabaseLicencias.getSearchedExpedientes(
                  hash,
                  userPerms,
                  userSession.getIdMunicipio(),
                  envioOperacion.getTiposLicencia()));
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_SEARCHED_EXPEDIENTES_PLANOS:
          resultadoOperacion = new CResultadoOperacion(true, "");
          hash = envioOperacion.getHashtable();
          resultadoOperacion.setExpedientes(
              COperacionesDatabaseLicencias.getSearchedExpedientesPlanos(
                  hash, userSession.getIdMunicipio(), envioOperacion.getTiposLicencia()));
          resultadoOperacion.setVector(
              COperacionesDatabaseLicencias.getSearchedReferenciasPlanos(
                  hash, userSession.getIdMunicipio(), envioOperacion.getTiposLicencia()));

          break;
        case CConstantesComando.CMD_LICENCIAS_GET_SEARCHED_REFERENCIAS_CATASTRALES:
          resultadoOperacion = new CResultadoOperacion(true, "");
          hash = envioOperacion.getHashtable();
          resultadoOperacion.setVector(
              COperacionesDatabaseLicencias.getSearchedReferenciasCatastrales(
                  hash, userSession.getIdMunicipio()));
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_SEARCHED_ADDRESSES:
          resultadoOperacion = new CResultadoOperacion(true, "");
          hash = envioOperacion.getHashtable();
          resultadoOperacion.setVector(
              COperacionesDatabaseLicencias.getSearchedAddresses(
                  hash, userSession.getIdMunicipio()));
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_SEARCHED_ADDRESSES_BY_NUMPOLICIA:
          resultadoOperacion = new CResultadoOperacion(true, "");
          hash = envioOperacion.getHashtable();
          resultadoOperacion.setVector(
              COperacionesDatabaseLicencias.getSearchedAddressesByNumPolicia(
                  hash, userSession.getIdMunicipio()));
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_SEARCHED_PERSONAS:
          resultadoOperacion = new CResultadoOperacion(true, "");
          hash = envioOperacion.getHashtable();
          resultadoOperacion.setVector(
              COperacionesDatabaseLicencias.getSearchedPersonas(
                  hash, userSession.getIdMunicipio()));
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_TIPOS_FINALIZACION:
          resultadoOperacion = new CResultadoOperacion(true, "");
          resultadoOperacion.setVector(COperacionesDatabaseLicencias.getTiposFinalizacion());
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_TIPOS_TRAMITACION:
          resultadoOperacion = new CResultadoOperacion(true, "");
          resultadoOperacion.setVector(COperacionesDatabaseLicencias.getTiposTramitacion());
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_TIPOS_NOTIFICACION:
          resultadoOperacion = new CResultadoOperacion(true, "");
          resultadoOperacion.setVector(COperacionesDatabaseLicencias.getTiposNotificacion());
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_ESTADOS_NOTIFICACION:
          resultadoOperacion = new CResultadoOperacion(true, "");
          resultadoOperacion.setVector(COperacionesDatabaseLicencias.getEstadosNotificacion());
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_ESTADOS_RESOLUCION:
          resultadoOperacion = new CResultadoOperacion(true, "");
          resultadoOperacion.setVector(COperacionesDatabaseLicencias.getEstadosResolucion());
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_NOTIFICACIONES:
          resultadoOperacion = new CResultadoOperacion(true, "");
          hash = envioOperacion.getHashtable();
          resultadoOperacion.setVector(COperacionesDatabaseLicencias.getNotificaciones(hash));
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_PARCELARIO:
          resultadoOperacion = new CResultadoOperacion(true, "");
          hash = envioOperacion.getHashtable();
          resultadoOperacion.setVector(
              COperacionesDatabaseLicencias.getParcelario(hash, userSession.getIdMunicipio()));
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_SOLICITUDES_EXPEDIENTES_INFORME:
          hash = envioOperacion.getHashtable();
          resultadoOperacion =
              COperacionesDatabaseLicencias.getSolicitudesExpedientesInforme(
                  hash, userSession.getIdMunicipio(), envioOperacion.getTiposLicencia());
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_PLANTILLAS:
          String aplicacion = (String) envioOperacion.getParametro();
          vector = COperacionesDatabaseLicencias.getPlantillas(aplicacion);
          resultadoOperacion = new CResultadoOperacion(true, "");
          resultadoOperacion.setVector(vector);
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_NOTIFICACIONES_MENU:
          hash = envioOperacion.getHashtable();
          vector =
              COperacionesDatabaseLicencias.getNotificacionesMenu(
                  hash, userSession.getIdMunicipio(), envioOperacion.getTiposLicencia());
          resultadoOperacion = new CResultadoOperacion(true, "");
          resultadoOperacion.setVector(vector);
          break;

        case CConstantesComando.CMD_LICENCIAS_GET_EVENTOS:
          hash = envioOperacion.getHashtable();
          locale = (String) envioOperacion.getParametro();
          resultadoOperacion =
              COperacionesDatabaseLicencias.getEventos(
                  hash, userSession.getIdMunicipio(), envioOperacion.getTiposLicencia(), locale);
          break;
        case CConstantesComando.CMD_LICENCIAS_GET_ULTIMOS_EVENTOS:
          hash = envioOperacion.getHashtable();
          locale = (String) envioOperacion.getParametro();
          resultadoOperacion =
              COperacionesDatabaseLicencias.getUltimosEventos(
                  hash, userSession.getIdMunicipio(), envioOperacion.getTiposLicencia(), locale);
          break;
        case CConstantesComando.CMD_LICENCIAS_GET_EVENTOS_SIN_REVISAR:
          hash = envioOperacion.getHashtable();
          locale = (String) envioOperacion.getParametro();
          resultadoOperacion =
              COperacionesDatabaseLicencias.getEventosSinRevisar(
                  hash, userSession.getIdMunicipio(), envioOperacion.getTiposLicencia(), locale);
          break;
        case CConstantesComando.CMD_LICENCIAS_GET_HISTORICO:
          hash = envioOperacion.getHashtable();
          locale = (String) envioOperacion.getParametro();
          resultadoOperacion =
              COperacionesDatabaseLicencias.getHistorico(
                  hash, userSession.getIdMunicipio(), envioOperacion.getTiposLicencia(), locale);
          break;
        case CConstantesComando.CMD_LICENCIAS_GET_HISTORICO_EXPEDIENTE:
          hash = envioOperacion.getHashtable();
          locale = (String) envioOperacion.getParametro();
          resultadoOperacion =
              COperacionesDatabaseLicencias.getHistorico(
                  hash, userSession.getIdMunicipio(), envioOperacion.getTiposLicencia(), locale);
          break;
        case CConstantesComando.CMD_LICENCIAS_GET_NOTIFICACIONES_PENDIENTES:
          hash = envioOperacion.getHashtable();
          vector =
              COperacionesDatabaseLicencias.getNotificacionesPendientes(
                  userSession.getIdMunicipio(), envioOperacion.getTiposLicencia());
          resultadoOperacion = new CResultadoOperacion(true, "");
          resultadoOperacion.setVector(vector);
          break;
        case CConstantesComando.CMD_LICENCIAS_GET_EVENTOS_PENDIENTES:
          resultadoOperacion =
              COperacionesDatabaseLicencias.getEventosPendientes(
                  userSession.getIdMunicipio(),
                  userPerms,
                  envioOperacion.getTiposLicencia(),
                  (String) envioOperacion.getParametro());
          break;
        case CConstantesComando.CMD_LICENCIAS_BLOQUEAR_EXPEDIENTE:
          boolean bloquear = ((Boolean) envioOperacion.getParametro()).booleanValue();
          numExpediente = envioOperacion.getExpedienteLicencia().getNumExpediente();
          resultadoOperacion =
              COperacionesDatabaseLicencias.bloquearExpediente(numExpediente, bloquear);
          break;
        case CConstantesComando.CMD_INSERTAR_INFORME:
          resultadoOperacion =
              COperacionesDatabaseLicencias.insertarInforme(
                  (Informe) envioOperacion.getParametro(), fileUploads);
          break;
        case CConstantesComando.CMD_LICENCIAS_ACTUALIZAR_IDSIGEM:
          expedienteLicencia = envioOperacion.getExpedienteLicencia();
          resultadoOperacion = COperacionesDatabaseLicencias.actualizarIdSigem(expedienteLicencia);
          break;
        case CConstantesComando.CMD_LICENCIAS_OBTENER_IDSIGEM:
          expedienteLicencia = envioOperacion.getExpedienteLicencia();
          resultadoOperacion = COperacionesDatabaseLicencias.obtenerIdSigem(expedienteLicencia);
          break;
        case CConstantesComando.CMD_LICENCIAS_ACTUALIZAR_ESTADOSIGEM:
          expedienteLicencia = envioOperacion.getExpedienteLicencia();
          resultadoOperacion =
              COperacionesDatabaseLicencias.checkExpedientePublicado(
                  expedienteLicencia, userSession.getIdMunicipio());
          break;
        case CConstantesComando.CMD_LICENCIAS_PUBLICAR_EXPEDEINTE_SIGEM:
          expedienteLicencia = envioOperacion.getExpedienteLicencia();
          solicitudLicencia = envioOperacion.getSolicitudLicencia();
          resultadoOperacion =
              COperacionesDatabaseLicencias.publicarExpedienteSigem(
                  expedienteLicencia, solicitudLicencia, userSession.getIdMunicipio());
          break;

        case CConstantesComando.CMD_LICENCIAS_ANEXO_ALFRESCO:
          resultadoOperacion =
              COperacionesDatabaseLicencias.anexoAlfresco(
                  envioOperacion.getSolicitudLicencia().getIdSolicitud(),
                  envioOperacion.getSolicitudLicencia().getAnexos(),
                  userPrincipal);
          break;

        case CConstantesComando.CMD_LICENCIAS_ANEXO_GETID:
          resultadoOperacion =
              COperacionesDatabaseLicencias.getAnexoId(
                  (String) envioOperacion.getParametro(), (Long) envioOperacion.getParametro2());
          break;

        default:
          logger.warn(
              "Comand not found. envioOperacion.getComando(): " + envioOperacion.getComando());
          resultadoOperacion = new CResultadoOperacion(false, "Command not found");
      }

      String respuesta = buildResponse(resultadoOperacion);
      out.print(respuesta);
      out.flush();
      out.close();

    } catch (Exception ex) {
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      ex.printStackTrace(pw);
      logger.error("Exception: " + sw.toString());
    }
  }