Package com.jamonapi

Examples of com.jamonapi.Monitor


 
    IDataSet dataSet;
    IDataStore dataStore;
   
    logger.debug("IN");
    Monitor monitor =MonitorFactory.start("SpagoBI_Console.GetConsoleDataAction.service")
   
    try {
      super.service(request,response);
      ConsoleEngineInstance consoleEngineInstance = getConsoleEngineInstance();
     
      dataSetLabel = getAttributeAsString( DATASET_LABEL );
      logger.debug("Parameter [" + DATASET_LABEL + "] is equals to [" + dataSetLabel + "]");     
      Assert.assertTrue(!StringUtilities.isEmpty( dataSetLabel ), "Parameter [" + DATASET_LABEL + "] cannot be null or empty");
     
      callback = getAttributeAsString( CALLBACK );
      logger.debug("Parameter [" + CALLBACK + "] is equals to [" + callback + "]");
     
      dataSet = null;
      try {
        dataSet = getDataSet(dataSetLabel);
      } catch(Throwable t) {
        throw new SpagoBIServiceException("Impossible to find a dataset whose label is [" + dataSetLabel + "]", t);
      }
      Assert.assertNotNull(dataSet, "Impossible to find a dataset whose label is [" + dataSetLabel + "]");
      Map params = consoleEngineInstance.getAnalyticalDrivers();
      dataSet.setParamsMap(params);
      dataSet.setUserProfileAttributes(UserProfileUtils.getProfileAttributes( (UserProfile) this.getEnv().get(EngineConstants.ENV_USER_PROFILE)));
      //dataSet.setParamsMap(getEnv());
      //gets the max number of rows for the table
      String strRowLimit = ConsoleEngineConfig.getInstance().getProperty("CONSOLE-TABLE-ROWS-LIMIT");
      int rowLimit = (strRowLimit == null)? 0 : Integer.parseInt(strRowLimit);
      Monitor monitorLD =MonitorFactory.start("SpagoBI_Console.GetConsoleDataAction.service.LoadData");
      if (rowLimit > 0){
        dataSet.loadData(-1, -1, rowLimit);
      }else{
        dataSet.loadData();
      }
      monitorLD.stop();
      dataStore = dataSet.getDataStore();
      Assert.assertNotNull(dataStore, "The dataStore returned by loadData method of the class [" + dataSet.getClass().getName()+ "] cannot be null");
     
      JSONObject results = new JSONObject();
      try {
View Full Code Here


    IDataStore dataStore;
    JSONObject dataSetJSON;
   
   
    logger.debug("IN");
    Monitor monitor =MonitorFactory.start("SpagoBI_Console.GetWarningListAction.service")
   
    try {
      super.service(request,response);
      ConsoleEngineInstance consoleEngineInstance = getConsoleEngineInstance();
   
      dataSetLabel = getAttributeAsString( DATASET_LABEL );
      logger.debug("Parameter [" + DATASET_LABEL + "] is equals to [" + dataSetLabel + "]");     
      Assert.assertTrue(!StringUtilities.isEmpty( dataSetLabel ), "Parameter [" + DATASET_LABEL + "] cannot be null or empty");
     
      callback = getAttributeAsString( CALLBACK );
      logger.debug("Parameter [" + CALLBACK + "] is equals to [" + callback + "]");
     
      rowId = getAttributeAsString( ID );
      logger.debug("Parameter [" + ID + "] is equals to [" + rowId + "]");
      Assert.assertNotNull(rowId, "Input parameters [" + ID + "] cannot be null");
     
      dataSet = null;
      try {
        dataSet = getDataSet(dataSetLabel);
      } catch(Throwable t) {
        throw new SpagoBIServiceException("Impossible to find a dataset whose label is [" + dataSetLabel + "]", t);
      }
      Assert.assertNotNull(dataSet, "Impossible to find a dataset whose label is [" + dataSetLabel + "]");
        /*
      Map params = new HashMap();
      params.put("id", rowId);
      dataSet.setParamsMap(params);
      */
      Map params = consoleEngineInstance.getAnalyticalDrivers();
      params.put("id", rowId);
      dataSet.setParamsMap(params);
      dataSet.setUserProfileAttributes(UserProfileUtils.getProfileAttributes( (UserProfile) this.getEnv().get(EngineConstants.ENV_USER_PROFILE)));
      Monitor monitorLD =MonitorFactory.start("SpagoBI_Console.GetWarningListAction.service.LoadData")
      dataSet.loadData();
      monitorLD.stop();
      dataStore = dataSet.getDataStore();
      Assert.assertNotNull(dataStore, "The dataStore returned by loadData method of the class [" + dataSet.getClass().getName()+ "] cannot be null");
         
      dataStore.getMetaData().setProperty("detailProperty", ERRORS_DETAIL_COLUMN);
      //int fieldIndex = dataStore.getMetaData().getFieldIndex(ERRORS_DETAIL_COLUMN);
View Full Code Here

    String outputFormat = null;
    String executionId = null;
    File maptmpfile = null;
    boolean inlineResponse;
    String responseFileName;
    Monitor totalTimeMonitor = null;
    Monitor totalTimePerFormatMonitor = null;
    Monitor flushingResponseTotalTimeMonitor = null;
    Monitor errorHitsMonitor = null;
 
    logger.debug("IN");
   
    try {   
      super.service(serviceRequest, serviceResponse);
     
      totalTimeMonitor = MonitorFactory.start("GeoEngine.drawMapAction.totalTime");
     
      executionId = getAttributeAsString( "SBI_EXECUTION_ID" );
     
      outputFormat = getAttributeAsString( OUTPUT_FORMAT );   
      logger.debug("Parameter [" + OUTPUT_FORMAT + "] is equal to [" + outputFormat + "]");
     
     
      inlineResponse = getAttributeAsBoolean( INLINE_RESPONSE, true );   
      logger.debug("Parameter [" + INLINE_RESPONSE + "] is equal to [" + inlineResponse + "]");
     
      if(getAuditServiceProxy() != null) getAuditServiceProxy().notifyServiceStartEvent();
     
      if(outputFormat == null) {
        logger.info("Parameter [" + outputFormat + "] not specified into request");
        outputFormat = (String)getGeoEngineInstance().getEnv().get(GeoEngineConstants.ENV_OUTPUT_TYPE);
        logger.debug("Env Parameter [" + GeoEngineConstants.ENV_OUTPUT_TYPE + "] is equal to [" + outputFormat + "]");
      }
     
      if(outputFormat == null) {
        logger.info("Parameter [" + GeoEngineConstants.ENV_OUTPUT_TYPE + "] not specified into environment");
        outputFormat = DEFAULT_OUTPUT_TYPE;
      }
     
      totalTimePerFormatMonitor = MonitorFactory.start("GeoEngine.drawMapAction." + outputFormat + "totalTime");
     
     
      try {
        if(outputFormat.equalsIgnoreCase(GeoEngineConstants.PDF)){
          maptmpfile = getGeoEngineInstance().renderMap( GeoEngineConstants.JPEG );
         
        }else{
          maptmpfile = getGeoEngineInstance().renderMap( outputFormat );
        }
      } catch (Throwable t) {
         throw new DrawMapServiceException(getActionName(), "Impossible to render map", t);
      }
     
      responseFileName = "map.svg";
     
      IStreamEncoder encoder = null;
      File tmpFile = null;
      if(outputFormat.equalsIgnoreCase(GeoEngineConstants.JPEG)) {
        encoder = new SVGMapConverter();
        responseFileName =  "map.jpeg";
      }else if(outputFormat.equalsIgnoreCase(GeoEngineConstants.PDF)){
       
        encoder = new SVGMapConverter();
        BufferedInputStream bis = null;
       
        String dirS = System.getProperty("java.io.tmpdir");
        File imageFile = null;
        bis = new BufferedInputStream( new FileInputStream(maptmpfile) );
        try {
          int contentLength = 0;
          int b = -1;
          String contentFileName = "tempJPEGExport";
          freezeHttpResponse();
                   
          File dir = new File(dirS);
          imageFile = File.createTempFile("tempJPEGExport", ".jpeg" , dir);
          FileOutputStream stream = new FileOutputStream(imageFile);
         
          encoder.encode(bis,stream);
         
          stream.flush();
          stream.close();   
         
          File dirF = new File(dirS);
            tmpFile = File.createTempFile("tempPDFExport", ".pdf", dirF);
            Document pdfDocument = new Document();
            PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(tmpFile));
            pdfDocument.open();
            Image jpg = Image.getInstance(imageFile.getPath());
            jpg.setRotation(new Double(Math.PI/2).floatValue());
            jpg.scaleAbsolute(770, 520);
            pdfDocument.add(jpg);
            pdfDocument.close();
            docWriter.close();
            maptmpfile = tmpFile;
         
        } finally {
          bis.close();
          if(imageFile!=null)imageFile.delete();
        }   

        responseFileName =  "map.pdf";
        encoder = null;
       
      }
     
      try {
        flushingResponseTotalTimeMonitor = MonitorFactory.start("GeoEngine.drawMapAction.flushResponse.totalTime");
        writeBackToClient(maptmpfile, encoder, inlineResponse, responseFileName, getContentType(outputFormat));
       
      } catch(IOException e) {
        logger.error("error while flushing output", e);
        if(getAuditServiceProxy() != null) getAuditServiceProxy().notifyServiceErrorEvent( "Error while flushing output" );
        throw new DrawMapServiceException(getActionName(), "Error while flushing output", e);
      }
     
      if(getAuditServiceProxy() != null) getAuditServiceProxy().notifyServiceEndEvent( );
     
      maptmpfile.delete()
      if(tmpFile!=null)tmpFile.delete();
     
    } catch (Throwable t) {
      errorHitsMonitor = MonitorFactory.start("GeoEngine.errorHits");
      errorHitsMonitor.stop();
      DrawMapServiceException wrappedException;
      if(t instanceof DrawMapServiceException) {
        wrappedException = (DrawMapServiceException)t;
      } else {
        wrappedException = new DrawMapServiceException(getActionName(), "An unpredicted error occurred while executing " + getActionName() + " service", t);
View Full Code Here

  public File renderMap(IMapProvider mapProvider,
      IDataMartProvider datamartProvider,
      String outputFormat) throws GeoEngineException {

    Monitor totalTimeMonitor = null;
    Monitor totalTimePerFormatMonitor = null;

    try {

      totalTimeMonitor = MonitorFactory.start("GeoEngine.drawMapAction.renderMap.totalTime");
      totalTimePerFormatMonitor = MonitorFactory.start("GeoEngine.drawMapAction.renderMap." + outputFormat + ".totalTime");

      if(outputFormat.equalsIgnoreCase(GeoEngineConstants.SVG)) {
        return renderSVGMap(mapProvider, datamartProvider);
      }else if(outputFormat.equalsIgnoreCase(GeoEngineConstants.DSVG)) {
        return renderDSVGMap(mapProvider, datamartProvider, false);
      } else if(outputFormat.equalsIgnoreCase(GeoEngineConstants.XDSVG)) {
        return renderDSVGMap(mapProvider, datamartProvider, true);
      } else if(outputFormat.equalsIgnoreCase(GeoEngineConstants.JPEG)) {
        return renderSVGMap(mapProvider, datamartProvider);
      }
    } finally {
      if(totalTimePerFormatMonitor != null) totalTimePerFormatMonitor.stop();
      if(totalTimeMonitor != null) totalTimeMonitor.stop();     
    }


    return renderDSVGMap(mapProvider, datamartProvider, true);
View Full Code Here

    SVGDocument targetMap;
    SVGDocument masterMap = null;
    File tmpMap;
    DataMart dataMart;
    Monitor loadDataMartTotalTimeMonitor = null;
    Monitor loadMasterMapTotalTimeMonitor = null;
    Monitor loadTargetMapTotalTimeMonitor = null;
    Monitor margeAndDecorateMapTotalTimeMonitor = null;

    // load datamart
    try {
      loadDataMartTotalTimeMonitor = MonitorFactory.start("GeoEngine.drawMapAction.renderMap.loadDatamart");
      dataMart = (DataMart)datamartProvider.getDataMart();
    } finally {
      if(loadDataMartTotalTimeMonitor != null) loadDataMartTotalTimeMonitor.stop();
    }

    // load master map
    try {
      loadMasterMapTotalTimeMonitor = MonitorFactory.start("GeoEngine.drawMapAction.renderMap.loadMasterMap");
      masterMap = svgMapLoader.loadMapAsDocument(getMasterMapFile(true));
    } catch (IOException e) {
      GeoEngineException geoException;
      logger.error("Impossible to load map from file: " + getMasterMapFile(true));
      String description = "Impossible to load map from file: " + getMasterMapFile(true);
      geoException = new GeoEngineException("Impossible to render map", e);
      geoException.setDescription(description);
      throw  geoException;
    } finally {
      if(loadMasterMapTotalTimeMonitor != null) loadMasterMapTotalTimeMonitor.stop();
    }

    // load target map
    try {
      loadTargetMapTotalTimeMonitor = MonitorFactory.start("GeoEngine.drawMapAction.renderMap.loadTargetMap");
      targetMap = mapProvider.getSVGMapDOMDocument()
    }finally {
      if(loadTargetMapTotalTimeMonitor != null) loadTargetMapTotalTimeMonitor.stop();
    }

    // marge and decorate map
    try {

      margeAndDecorateMapTotalTimeMonitor = MonitorFactory.start("GeoEngine.drawMapAction.renderMap.margeAndDecorateMap");

      addData(targetMap, dataMart);
      addLink(targetMap, dataMart);


      SVGMapMerger.margeMap(targetMap, masterMap, null, "targetMap");

      if( includeScript ) {
        includeScripts(masterMap);
      } else {
        importScripts(masterMap);
      }


      setMainMapDimension(masterMap, targetMap);

      Element scriptInit = masterMap.getElementById("init");     
      Node scriptText = scriptInit.getFirstChild();

      JSONObject conf = new JSONObject();     

      JSONArray measures;
      try {
        measures = getMeasuresConfigurationScript(dataMart);
        String selectedMeasureName = getSelectedMeasureName();
        logger.debug("Selected measure [" + selectedMeasureName + "]");
        Assert.assertTrue(selectedMeasureName != null, "default_kpi attribute cannot be null. Please add it to MEASURES tag in your template file");
       
       
        int selectedMeasureIndexIndex = -1;
        for(int i = 0; i < measures.length(); i++) {
          JSONObject measure = (JSONObject)measures.get(i);
          logger.debug("Comparing selected measure [" + selectedMeasureName + "] with measure [" + (String)measure.get("name") + "]");
          String nm = (String)measure.get("name");
          if(selectedMeasureName.equalsIgnoreCase( nm)) {
            logger.debug("Selected measure [" + selectedMeasureName + "] is equal to measure [" + (String)measure.get("name") + "]");
            selectedMeasureIndexIndex = i;
            break;
          }
        }
        logger.debug("Selected measure index [" + selectedMeasureIndexIndex + "]");
        conf.put("selected_measure_index", selectedMeasureIndexIndex);
        conf.put("measures", measures);

        JSONArray layers =  getLayersConfigurationScript(targetMap);
        String targetLayer = datamartProvider.getSelectedLevel().getFeatureName();
        int targetLayerIndex = -1;
        for(int i = 0; i < layers.length(); i++) {
          JSONObject layer = (JSONObject)layers.get(i);

          if(targetLayer.equals( layer.get("name"))) {
            targetLayerIndex = i;
            break;
          }
        }
        conf.put("target_layer_index", targetLayerIndex);
        conf.put("layers", layers);


        JSONObject guiSettings =  getGUIConfigurationScript();
        guiSettings.put("includeChartLayer", getLayer("grafici")!=null);
        guiSettings.put("includeValuesLayer", getLayer("valori")!=null);
        conf.put("gui_settings", guiSettings);

        String execId = (String)this.getEnv().get("SBI_EXECUTION_ID");
        conf.put("execId", execId);

        JSONObject localeJSON =  new JSONObject();
        Locale locale = (Locale) this.getEnv().get(EngineConstants.ENV_LOCALE);
        logger.debug("Current environment locale is: " + locale);
        if (locale == null) {
          logger.debug("Using default english locale");
          locale = Locale.ENGLISH;
        }
        localeJSON.put("language", locale.getLanguage());
        localeJSON.put("country", locale.getCountry());
        DecimalFormatSymbols dfs = new DecimalFormatSymbols(locale);
        localeJSON.put("decimalSeparator", new Character(dfs.getDecimalSeparator()).toString());
        localeJSON.put("groupingSeparator", new Character(dfs.getGroupingSeparator()).toString());
        conf.put("locale", localeJSON);
      } catch (JSONException e1) {
        GeoEngineException geoException;
        logger.error("Impossible to create sbi.geo.conf", e1);
        String description = "Impossible to create sbi.geo.conf";
        geoException = new GeoEngineException("Impossible to create sbi.geo.conf", e1);
        geoException.setDescription(description);
        throw  geoException;
      }

      scriptText.setNodeValue( "sbi = {};\n sbi.geo = {};\n sbi.geo.conf = " + conf.toString() );


      try {
        tmpMap = getTempFile();
      } catch (IOException e) {
        GeoEngineException geoException;
        logger.error("Impossible to create a temporary file", e);
        String description = "Impossible to create a temporary file";
        geoException = new GeoEngineException("Impossible to render map", e);
        geoException.setDescription(description);
        throw  geoException;
      }catch (Throwable t) {
        GeoEngineException geoException;
        logger.error("Impossible to create a temporary file", t);
        String description = "Impossible to create a temporary file";
        geoException = new GeoEngineException("Impossible to render map", t);
        geoException.setDescription(description);
        throw  geoException;
      }       
      try {
        SVGMapSaver.saveMap(masterMap, tmpMap);
      } catch (FileNotFoundException e) {
        GeoEngineException geoException;
        logger.error("Impossible to save map on temporary file " + tmpMap, e);
        String str = e.getMessage()!=null?e.getMessage():e.getClass().getName();
        String description = "Impossible to save map on temporary file " + tmpMap + ". Root cause: " + str;
        geoException = new GeoEngineException("Impossible to render map", e);
        geoException.setDescription(description);
        throw  geoException;
      } catch (TransformerException e) {
        GeoEngineException geoException;
        logger.error("Impossible to save map on temporary file " + tmpMap, e);
        String str = e.getMessage()!=null?e.getMessage():e.getClass().getName();
        String description = "Impossible to save map on temporary file " + tmpMap + ". Root cause: " + str;
        geoException = new GeoEngineException("Impossible to render map",  e);
        geoException.setDescription(description);
        throw  geoException;
      }catch (Throwable t) {
        GeoEngineException geoException;
        logger.error("Impossible to save map on temporary file " + tmpMap, t);
        String str = t.getMessage()!=null?t.getMessage():t.getClass().getName();
        String description = "Impossible to save map on temporary file " + tmpMap + ". Root cause: " + str;
        geoException = new GeoEngineException("Impossible to render map",  t);
        geoException.setDescription(description);
        throw  geoException;
      }
    } finally {
      if(margeAndDecorateMapTotalTimeMonitor != null) margeAndDecorateMapTotalTimeMonitor.stop();
    }

    return tmpMap;
  }
View Full Code Here

     * @throws IOException Signals that an I/O exception has occurred.
     */
    public void processService(PortletRequest request, PortletResponse response) throws PortletException, IOException {
    //**************** END MODFIFICATION ZERBETTO 09-10-2006 ****************
     
      Monitor monitor = null;
      PortletTracer.info(Constants.NOME_MODULO, "AdapterPortlet", "processService", "Invocato");
        try {
            SourceBean serviceRequest = null;
            EMFErrorHandler emfErrorHandler = null;
           
            RequestContainer requestContainer = new RequestContainer();
            RequestContainer.setRequestContainer(requestContainer);
            ResponseContainer responseContainer = new ResponseContainer();
            ResponseContainer.setResponseContainer(responseContainer);
            RequestContextIFace requestContext = new DefaultRequestContext(requestContainer,
                    responseContainer);
           
            // try to get from the request the loopback attribute. If present the method has to serve
            // a loopback request (the method has been called from the doRenderService)
            // if not present is a normal request
            boolean isLoop = request.getAttribute(Constants.PUBLISHING_MODE_LOOPBACK) != null;
            if(isLoop) {
              // remove from the request the loopback attribute
              request.removeAttribute(Constants.PUBLISHING_MODE_LOOPBACK);
              //String responseContainerName = (String)request.getAttribute(Constants.RESPONSE_CONTAINER);
             
              //**************** START MODFIFICATION ZERBETTO 09-10-2006 ****************
              // get from the session the previous response container name
              //String responseContainerName = (String)request.getPortletSession().getAttribute(RESPONSE_CONTAINER_NAME);
              // get from the session the previous response container
              //ResponseContainer loopbackResponseContainer = (ResponseContainer)request.getPortletSession().getAttribute(responseContainerName);
              ResponseContainer loopbackResponseContainer = (ResponseContainer)request.getPortletSession().getAttribute(Constants.RESPONSE_CONTAINER);
              //**************** END MODFIFICATION ZERBETTO 09-10-2006 ****************
             
                TracerSingleton.log(
                    Constants.NOME_MODULO,
                    TracerSingleton.DEBUG,
                    "AdapterPortlet::service: loop-back rilevato");
                serviceRequest =
                    loopbackResponseContainer.getLoopbackServiceRequest();
                if (serviceRequest == null)
                    serviceRequest = new SourceBean(Constants.SERVICE_REQUEST);
                else {
                    Object newServiceRequest =
                        serviceRequest.getAttribute(Constants.SERVICE_REQUEST);
                    if ((newServiceRequest != null)
                        && (newServiceRequest instanceof SourceBean))
                        serviceRequest = (SourceBean) newServiceRequest;
                } // if (serviceRequest == null)
                emfErrorHandler = loopbackResponseContainer.getErrorHandler();
                if (emfErrorHandler == null)
                    emfErrorHandler = new EMFErrorHandler();
            } // if (isLoop)
            else {
              monitor = MonitorFactory.start("controller.adapter.portlet");
              serviceRequest = new SourceBean(Constants.SERVICE_REQUEST);
              requestContainer.setServiceRequest(serviceRequest);
             
                boolean isMultipart = false;
               
                // only an ActionRequest can have a multipart content
                if (request instanceof ActionRequest && PortletFileUpload.isMultipartContent((ActionRequest) request)) {
                  isMultipart = true;
                }
               
                if (isMultipart) {
                  handleMultipartForm((ActionRequest) request, requestContext);
                } else {
                  handleSimpleForm(request, requestContext);
                }
             
              // ***************** START SERVICE ***********************************************
              String actionName = (String) request.getAttribute("ACTION_NAME");
              if(actionName!=null) {
                request.removeAttribute("ACTION_NAME");
                serviceRequest.setAttribute("ACTION_NAME", actionName);
                serviceRequest.setAttribute(NEW_SESSION, "TRUE");
              }
              String page = (String)request.getAttribute("PAGE");
              if(page!=null) {
                request.removeAttribute("PAGE");
                serviceRequest.setAttribute("PAGE", page);
                serviceRequest.setAttribute(NEW_SESSION, "TRUE");
             
            // *******************************************************************************************
              emfErrorHandler = new EMFErrorHandler();
            }
           
            //***************** NAVIGATION CONTROL *******************************************************
            String navigation = getInitParameter("light_navigation");
            if ("enabled".equalsIgnoreCase(navigation)) {
              serviceRequest = LightNavigationManager.controlLightNavigation(request, serviceRequest);
            }
            //updates service request after LightNavigationManager control
            requestContainer.setServiceRequest(serviceRequest);
            //********************************************************************************************
           
            boolean isRequestedSessionIdValid = true;
            PortletSession session = request.getPortletSession(true);
            /*
            if (session.isNew()) {
                String newSessionString =
                    (String) (serviceRequest.getAttribute(NEW_SESSION));
                isRequestedSessionIdValid =
                    ((newSessionString != null)
                        && (newSessionString.equalsIgnoreCase("TRUE")));
            } // if (session.isNew())
            */
            synchronized (session) {
               
              // try to get the previous request container. Download from the session the previous
              // request container name and if it isn't null (it's null only formthe first invocation)
              //use it for download the request container object
              RequestContainer parentRequestContainer = null;
             
              //**************** START MODFIFICATION ZERBETTO 09-10-2006 ****************
              //String parentRequestContainerName =
              //  (String) session.getAttribute(REQUEST_CONTAINER_NAME);
              //if(parentRequestContainerName != null) {
              //  parentRequestContainer = (RequestContainer) session.getAttribute(parentRequestContainerName);
              //}
              parentRequestContainer = (RequestContainer) session.getAttribute(Constants.REQUEST_CONTAINER);
              //**************** END MODFIFICATION ZERBETTO 09-10-2006 ****************

                if (!Navigator.isNavigatorEnabled()) {
                    if (parentRequestContainer == null)
                        requestContainer.setSessionContainer(
                            new PortletSessionContainer(true));
                    else
                        requestContainer.setSessionContainer(
                            parentRequestContainer.getSessionContainer());
                }
                else {
                    if (parentRequestContainer == null)
                        requestContainer.setSessionContainer(
                            new PortletSessionContainer(true));
                    else {
                        requestContainer.setSessionContainer(
                            new PortletSessionContainer(false));
                        requestContainer.setParent(parentRequestContainer);
                    } // if (parentRequestContainer == null) else
                } // if (!Navigator.isNavigatorEnabled())
               
                //**************** START MODFIFICATION ZERBETTO 09-10-2006 ****************
                //session.setAttribute(Constants.REQUEST_CONTAINER, requestContainer);
                //**************** END MODFIFICATION ZERBETTO 09-10-2006 ****************
               
            } // synchronized (session)
            if (!isRequestedSessionIdValid) {
                TracerSingleton.log(
                    Constants.NOME_MODULO,
                    TracerSingleton.WARNING,
                    "AdapterPortlet::processAction: sessione scaduta !");
                SessionExpiredUtility.setSessionExpiredAction(serviceRequest);
            } // if (!isRequestedSessionIdValid)
           
            requestContainer.setAttribute(
                    HTTP_SESSION_ID,
                    request.getPortletSession().getId());
            String channelType = "PORTLET";
            String channelTypeParameter =
                (String) (serviceRequest.getAttribute(Constants.CHANNEL_TYPE));
            String channelTypeHeader =
                (String) (requestContainer.getAttribute(HTTP_ACCEPT_HEADER));
            if (((channelTypeParameter != null)
                && channelTypeParameter.equalsIgnoreCase(Constants.WAP_CHANNEL))
                || ((channelTypeHeader != null)
                    && (channelTypeHeader.indexOf(WAP_MIME_TYPE) != -1)))
                channelType = Constants.WAP_CHANNEL;
            requestContainer.setChannelType(channelType);


            TracerSingleton.log(
                Constants.NOME_MODULO,
                TracerSingleton.DEBUG,
                "AdapterPortlet::processAction: requestContainer",
                requestContainer);
            TracerSingleton.log(
                Constants.NOME_MODULO,
                TracerSingleton.DEBUG,
                "AdapterPortlet::processAction: sessionContainer",
                requestContainer.getSessionContainer());

            responseContainer.setErrorHandler(emfErrorHandler);
            SourceBean serviceResponse =
                new SourceBean(Constants.SERVICE_RESPONSE);
            responseContainer.setServiceResponse(serviceResponse);
            try {
                Navigator.checkNavigation(requestContainer);
            } // try
            catch (NavigationException ne) {
                TracerSingleton.log(
                    Constants.NOME_MODULO,
                    TracerSingleton.CRITICAL,
                    "AdapterPortlet::processAction: ",
                    ne);
                requestContainer.setServiceRequest(
                    NavigationErrorUtility.getNavigationErrorServiceRequest());
            } // catch (NavigationException ne)
            serviceRequest = requestContainer.getServiceRequest();

            CoordinatorIFace coordinator =
                DispatcherManager.getCoordinator(requestContext);
            Exception serviceException = null;
            if (coordinator == null) {
                TracerSingleton.log(
                    Constants.NOME_MODULO,
                    TracerSingleton.WARNING,
                    "AdapterPortlet::processAction: coordinator nullo !");
                serviceException = new Exception("Coordinatore non trovato");
                emfErrorHandler.addError(
                    new EMFInternalError(
                        EMFErrorSeverity.ERROR,
                        "Coordinatore non trovato !"));
            } // if (coordinator == null)
            else {
                ((RequestContextIFace) coordinator).setRequestContext(
                    requestContext);
                responseContainer.setBusinessType(
                        coordinator.getBusinessType());
                    responseContainer.setBusinessName(
                        coordinator.getBusinessName());
                try {
                    coordinator.service(serviceRequest, serviceResponse);
                } // try
                catch (Exception ex) {
                    TracerSingleton.log(
                        Constants.NOME_MODULO,
                        TracerSingleton.CRITICAL,
                        "AdapterPortlet::processAction:",
                        ex);
                    serviceException = ex;
                    emfErrorHandler.addError(
                        new EMFInternalError(EMFErrorSeverity.ERROR, ex));
                    responseContainer.setAttribute(PORTLET_EXCEPTION, serviceException);
                } // catch (Exception ex)
                 ((RequestContextIFace) coordinator).setRequestContext(null);
            } // if (coordinator == null) else
           
            //**************** START MODFIFICATION ZERBETTO 09-10-2006 ****************
            //synchronized (session) {
            //    session.setAttribute(
            //        Constants.REQUEST_CONTAINER,
            //        session.getAttribute(Constants.REQUEST_CONTAINER));
            //} // synchronized (session)
            //**************** END MODFIFICATION ZERBETTO 09-10-2006 ****************
           
            TracerSingleton.log(
                Constants.NOME_MODULO,
                TracerSingleton.DEBUG,
                "AdapterPortlet::processAction: responseContainer",
                responseContainer);
            TracerSingleton.log(
                Constants.NOME_MODULO,
                TracerSingleton.DEBUG,
                "AdapterPortlet::processAction: sessionContainer",
                requestContainer.getSessionContainer());
               
      if (serializeSession) {
        TracerSingleton.log(
          Constants.NOME_MODULO,
          TracerSingleton.DEBUG,
          "AdapterPortlet::processAction: sessionContainer size ["
            + Serializer.serialize(
              requestContainer.getSessionContainer()).length
            + "]");
      }
     
      //**************** START MODFIFICATION ZERBETTO 09-10-2006 ****************
            //String requestContainerName =
            //    Constants.REQUEST_CONTAINER
            //        + requestContainer.hashCode();
            //String responseContainerName =
            //    Constants.RESPONSE_CONTAINER
            //        + responseContainer.hashCode();                          

            // set into the session new request and response container produced
            //session.setAttribute(requestContainerName, requestContainer);
            //session.setAttribute(responseContainerName, responseContainer);
            // set into the session the name of the new request and response container produced
            //session.setAttribute(REQUEST_CONTAINER_NAME, requestContainerName);
            //session.setAttribute(RESPONSE_CONTAINER_NAME, responseContainerName);
            // if the response is of type ActionResponse (the method has been called from the container)
            // set the name of the container like parameter of the request for the render method
            //if(response instanceof ActionResponse) {
            //  ((ActionResponse)response).setRenderParameter(REQUEST_CONTAINER_NAME, requestContainerName);
            //  ((ActionResponse)response).setRenderParameter(RESPONSE_CONTAINER_NAME, responseContainerName);
            //}
            // if the response is of type RenderResponse the method has been called from the doRenderService
            // method and the container names must be returned to the method into an hashmap (it's not possible
            // to set them like parameters because the container will not call automatically the render service)
            //else if(response instanceof RenderResponse){
            //  map.put(REQUEST_CONTAINER_NAME, requestContainerName);
            //  map.put(RESPONSE_CONTAINER_NAME, responseContainerName);
            //}
            session.setAttribute(Constants.REQUEST_CONTAINER, requestContainer);
            session.setAttribute(Constants.RESPONSE_CONTAINER, responseContainer);
            //**************** END MODFIFICATION ZERBETTO 09-10-2006 ****************
           
        } // try
        catch (Exception ex) {
            TracerSingleton.log(
                Constants.NOME_MODULO,
                TracerSingleton.CRITICAL,
                "AdapterPortlet::processAction: ",
                ex);
        } // catch (Excpetion ex) try
        finally {   
          RequestContainer.delRequestContainer();
            ResponseContainer.delResponseContainer();
            if (monitor != null)
                monitor.stop();
        } // finally
       
        //**************** START MODFIFICATION ZERBETTO 09-10-2006 ****************
        //return map;
        //**************** END MODFIFICATION ZERBETTO 09-10-2006 ****************
 
View Full Code Here

              } // if (publisherType.equalsIgnoreCase(Constants.LOOP_PUBLISHER_TYPE)
                // || publisherType.equalsIgnoreCase(SERVLET_PUBLISHER_TYPE) ||
                // publisherType.equalsIgnoreCase(JSP_PUBLISHER_TYPE))
              else {
                  response.setContentType(HTTP_CONTENT_TYPE);
                  Monitor renderingMonitor =
                          MonitorFactory.start(
                              "view.portlet."
                                  + publisherType.toLowerCase()
                                  + "."
                                  + publisher.getName().toLowerCase());
                  try {
                      response.getWriter().print(
                          PresentationRendering.render(
                              responseContainer,
                              resources));
                      response.getWriter().flush();
                  } // try
                  catch (Exception ex) {
                    TracerSingleton.log(
                              Constants.NOME_MODULO,
                              TracerSingleton.DEBUG,
                              "AdapterPortlet::doView:eccezzione", ex);
                  } // catch (Exception ex)
                  finally {
                    // Allow better garbage collection
                    publisher.release();
                    // Stop performance measurement
                      renderingMonitor.stop();
                  } // finally
              } // if (publisherType.equalsIgnoreCase(AF_PUBLISHER_TYPE)
              // || publisherType.equalsIgnoreCase(SERVLET_PUBLISHER_TYPE) ||
              // publisherType.equalsIgnoreCase(JSP_PUBLISHER_TYPE)) else
          } //if (requestContainer == null && responseContainer == null) else
View Full Code Here

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    public void service(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        Monitor monitor = null;
      IEventNotifier eventNotifier = null;
      RequestContextIFace requestContext = null;

        try {
          SourceBean serviceRequest = null;
            EMFErrorHandler emfErrorHandler = null;
            EMFExceptionHandler exceptionHandler = new EMFExceptionHandler();
           
            // Retrieve LOOP responseContainer, if any
            ResponseContainer loopbackResponseContainer = ResponseContainer.getResponseContainer();
           
            RequestContainer requestContainer = new RequestContainer();
            RequestContainer.setRequestContainer(requestContainer);
           
            ResponseContainer responseContainer = new ResponseContainer();
            ResponseContainer.setResponseContainer(responseContainer);
           
            requestContext = new DefaultRequestContext(requestContainer,
                    responseContainer);
           
            // Retrieve HTTP session
            HttpSession session = request.getSession(true);

          eventNotifier = EventNotifierFactory.getEventNotifier();
          eventNotifier.notifyEvent(
                new ServiceStartEvent(session),
                requestContext);           
          // Trace only after calling listener, so the session id can be written on log files
            TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.DEBUG,
                      "AdapterHTTP::service: invocato");

            boolean loopback = (request.getAttribute(Constants.PUBLISHING_MODE_LOOPBACK) != null);
            if (loopback) {
                TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.DEBUG,
                "AdapterHTTP::service: loop-back rilevato");

                // remove from the request the loopback attribute
              request.removeAttribute(Constants.PUBLISHING_MODE_LOOPBACK);
           
                loopbackResponseContainer = ResponseContainerAccess.getResponseContainer(request);
                serviceRequest = loopbackResponseContainer.getLoopbackServiceRequest();
                if (serviceRequest == null) {
                    serviceRequest = new SourceBean(Constants.SERVICE_REQUEST);
                } else {
                    Object newServiceRequest = serviceRequest
                            .getAttribute(Constants.SERVICE_REQUEST);
                    if ((newServiceRequest != null) && (newServiceRequest instanceof SourceBean))
                        serviceRequest = (SourceBean) newServiceRequest;
                } // if (serviceRequest == null)
                requestContainer.setServiceRequest(serviceRequest);
               
                // The errors are kept in loop mode, so retrieve old error handler
                emfErrorHandler = loopbackResponseContainer.getErrorHandler();
               
                if (emfErrorHandler == null) {
                    emfErrorHandler = new EMFErrorHandler();
                }
            } // if (loopbackResponseContainer != null)
            else {
                monitor = MonitorFactory.start("controller.adapter.http");
                serviceRequest = new SourceBean(Constants.SERVICE_REQUEST);
                requestContainer.setServiceRequest(serviceRequest);

                // Get header parameter before parsing the request
                setHttpRequestData(request, requestContainer);
               
                // Check if the service was invoked with the .action or .page URL
                handleServiceName(serviceRequest, requestContainer);
               
                boolean isMultipart = ServletFileUpload.isMultipartContent(new ServletRequestContext(request));
                if (isMultipart) {
                  handleMultipartForm(request, requestContext);
                } else {
                  handleSimpleForm(request, requestContext);
                }

                emfErrorHandler = new EMFErrorHandler();
            } // if (loopbackResponseContainer != null) else

           
            //***************** NAVIGATION CONTROL *******************************************************
            serviceRequest = LightNavigationManager.controlLightNavigation(request, serviceRequest);
            requestContainer.setServiceRequest(serviceRequest);
            //********************************************************************************************
           
            Exception serviceException = null;
            CoordinatorIFace coordinator = null;
            try {
              responseContainer.setErrorHandler(emfErrorHandler);
             
              String channelType = Constants.HTTP_CHANNEL;
              String channelTypeParameter = (String) (serviceRequest
                      .getAttribute(Constants.CHANNEL_TYPE));
              String channelTypeHeader = (String) (requestContainer.getAttribute(HTTP_ACCEPT_HEADER));
              if (((channelTypeParameter != null) && channelTypeParameter
                      .equalsIgnoreCase(Constants.WAP_CHANNEL))
                      || ((channelTypeHeader != null) && (channelTypeHeader.indexOf(WAP_MIME_TYPE) != -1)))
                  channelType = Constants.WAP_CHANNEL;
              requestContainer.setChannelType(channelType);
              requestContainer.setInternalRequest(request);
              requestContainer.setInternalResponse(response);
              requestContainer.setAdapterConfig(getServletConfig());
              TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.DEBUG,
                      "AdapterHTTP::service: requestContainer", requestContainer);
              TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.DEBUG,
                      "AdapterHTTP::service: sessionContainer", requestContainer
                              .getSessionContainer());
 
              SourceBean serviceResponse = new SourceBean(Constants.SERVICE_RESPONSE);
              responseContainer.setServiceResponse(serviceResponse);

              checkSession(session, requestContext);
                Navigator.checkNavigation(requestContainer);
             
              // Refresh service request because Navigator services can changed it
              serviceRequest = requestContainer.getServiceRequest();
             
              // Suspend/Resume service
              handleSuspendResume(serviceRequest, requestContainer);
             
              coordinator = DispatcherManager.getCoordinator(requestContext);
              if (coordinator == null) {
                  TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.WARNING,
                          "AdapterHTTP::service: coordinator nullo !");
                  serviceException = new Exception("Coordinatore non trovato");
                  emfErrorHandler.addError(new EMFInternalError(EMFErrorSeverity.ERROR,
                          "Coordinatore non trovato !"));
              } // if (coordinator == null)
              else {
                  ((RequestContextIFace) coordinator).setRequestContext(requestContext);
                  responseContainer.setBusinessType(coordinator.getBusinessType());
                  responseContainer.setBusinessName(coordinator.getBusinessName());
                  responseContainer.setPublisherName(coordinator.getPublisherName());
                      coordinator.service(serviceRequest, serviceResponse);
                     
                    ((RequestContextIFace) coordinator).setRequestContext(null);
//                    requestContainer.setInternalRequest(null);
              } // if (coordinator == null) else

            } // try
            catch (Exception ex) {
              ServiceIFace service = (coordinator != null)? coordinator.getService() : null;
              exceptionHandler.handleException(ex, service, requestContext);
            } // catch (Exception ex)
           
//            requestContainer.setInternalResponse(null);
//            requestContainer.setAdapterConfig(null);
            // nel caso in cui sia attiva la persistenza della sessione
            // forza la scrittura sul database
            synchronized (session) {
                session.setAttribute(Constants.REQUEST_CONTAINER, session.getAttribute(Constants.REQUEST_CONTAINER));
            } // synchronized (session)
           
            TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.DEBUG,
                    "AdapterHTTP::service: responseContainer", responseContainer);
            TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.DEBUG,
                    "AdapterHTTP::service: sessionContainer", requestContainer
                            .getSessionContainer());

            if (serializeSession) {
                TracerSingleton
                        .log(Constants.NOME_MODULO, TracerSingleton.DEBUG,
                                "AdapterHTTP::service: sessionContainer size ["
                                        + Serializer.serialize(requestContainer
                                                .getSessionContainer()).length + "]");
            }

            render(requestContext, serviceException);
        } // try
        catch (Exception ex) {
            TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.CRITICAL,
                    "AdapterHTTP::service: ", ex);
        } // catch (Excpetion ex) try
        finally {
            RequestContainer.delRequestContainer();
            ResponseContainer.delResponseContainer();
            if (monitor != null) {
                monitor.stop();
            }
           
            if (eventNotifier != null) {
              eventNotifier.notifyEvent(
                new ServiceEndEvent(null),
View Full Code Here

   * @throws Exception If any Exception occurred
   */
  public void runReport(Connection conn, Map parameters, OutputStream out, ServletContext servletContext,
      HttpServletResponse servletResponse, HttpServletRequest servletRequest) throws Exception {
    logger.debug("IN");
    Monitor monitor =MonitorFactory.start("JasperReportRunner.service");
    documentId=(String)servletRequest.getParameter("document");

    HttpSession session=servletRequest.getSession();
    IEngUserProfile profile=(IEngUserProfile)session.getAttribute(IEngUserProfile.ENG_USER_PROFILE);
    userId=(String)((UserProfile)profile).getUserId();
    userUniqueIdentifier=(String)profile.getUserUniqueIdentifier();

    logger.debug("Read user data from the request. userId="+userId+". DocumentId="+documentId);

    String resourcePath=EnginConf.getInstance().getResourcePath()+"/img/";
    String entity=(String)parameters.get(SpagoBIConstants.SBI_ENTITY);
    // IF exist an ENTITY  parameter concat to resourcePath
    if (entity!=null && entity.length()>0){
      resourcePath=resourcePath.concat(entity+"/");
    }
    logger.debug("SetUp resourcePath:"+resourcePath);

    String prefixDirTemplate = (String)parameters.get("prefixName");
    logger.debug("prefixDirTemplate:"+prefixDirTemplate);

    parameters.put("SBI_USERID", userUniqueIdentifier);
    parameters.put("SBI_HTTP_SESSION", session);
    parameters.put("SBI_RESOURCE_PATH", resourcePath);


    /* TODO Since this is the back-end (logic) part of the JasperEngine the direct use of  HttpServletResponse,
     * HttpServletRequest and ServletContext objects shuold be pushed back to JasperReportServlet that is
     * the front-end (control) part of the engine */   
    File[] compiledSubreports = null;
    SpagoBIAccessUtils util = new SpagoBIAccessUtils();
    // identity string for object execution
    UUIDGenerator uuidGen  = UUIDGenerator.getInstance();
    UUID uuid_local = uuidGen.generateTimeBasedUUID();
    //String executionId = uuid_local.toString();
    //executionId = executionId.replaceAll("-", "");
    String flgTemplateStandard = "true";

    //ContentServiceProxy contentProxy=new ContentServiceProxy(userId,session);
    ContentServiceProxy contentProxy=new ContentServiceProxy(userUniqueIdentifier,session);

    try {               
      String tmpDirectory = System.getProperty("java.io.tmpdir");

//      all jar needed by JR to succesfully compile a report should be on this path
      // (by default is WEB_INF/lib)
      setJRClasspath(getJRLibDir(servletContext));

      HashMap requestParameters = ParametersDecoder.getDecodedRequestParameters(servletRequest);
      Content template=contentProxy.readTemplate( documentId,requestParameters);
      if (template==null){
        logger.error("The document haven't the template.documentId="+documentId+" userUniqueIdentifier="+userUniqueIdentifier);       
        return;
      }
      logger.debug("Read the template."+template.getFileName());
      InputStream is = null;   
      BASE64Decoder bASE64Decoder = new BASE64Decoder();
      byte[] templateContent = bASE64Decoder.decodeBuffer(template.getContent());
      is = new java.io.ByteArrayInputStream(templateContent);

      if (template.getFileName().indexOf(".zip") > -1) {
        flgTemplateStandard = "false";
      }

      /* Dynamic template management: if the template is a zip file it is opened and every class are added to
       * the classpath
       *
       */
      boolean propertiesLoaded=false;
      if (flgTemplateStandard.equalsIgnoreCase("false")) {
        logger.debug("The template is a .ZIP file");
        File fileZip = new File(getJRTempDir(servletContext, prefixDirTemplate), JS_FILE_ZIP + JS_EXT_ZIP);
        FileOutputStream foZip = new FileOutputStream(fileZip);
        foZip.write(templateContent);
        foZip.close();
        util.unzip(fileZip, getJRTempDir(servletContext, prefixDirTemplate));
        JarFile zipFile = new JarFile(fileZip);
        Enumeration totalZipEntries = zipFile.entries();
        File jarFile = null;
        while (totalZipEntries.hasMoreElements()) {
          ZipEntry entry = (ZipEntry) totalZipEntries.nextElement();
          if (entry.getName().endsWith(".jar")) {
            jarFile = new File(getJRTempDirName(servletContext, prefixDirTemplate)+ entry.getName());
            // set classloader with jar
            ClassLoader previous = Thread.currentThread().getContextClassLoader();
            DynamicClassLoader dcl = new DynamicClassLoader(jarFile, previous);
            Thread.currentThread().setContextClassLoader(dcl);
          }
          else if (entry.getName().endsWith(".jrxml")) {
            // set InputStream with jrxml
            File jrxmlFile = new File(getJRTempDirName(servletContext, prefixDirTemplate)+ entry.getName());
            InputStream isJrxml = new FileInputStream(jrxmlFile);
            byte[] templateJrxml = new byte[0];
            templateJrxml = util.getByteArrayFromInputStream(isJrxml);
            is = new java.io.ByteArrayInputStream(templateJrxml);
          }
          if (entry.getName().endsWith(".properties")) {

            propertiesLoaded=true;
          }         
        }
      }

      // Set the temporary location for the files generated on-the-fly by JR
      // (by default is the current user tmp-dir)
      setJRTempDir(tmpDirectory);

      logger.debug("Compiling template file ...");
      Monitor monitorCompileTemplate =MonitorFactory.start("JasperReportRunner.compileTemplate");
      JasperReport report  = JasperCompileManager.compileReport(is)
      monitorCompileTemplate.stop();
      logger.debug("Template file compiled  succesfully");

      parameters = adaptReportParams(parameters, report);

      // Add locale
      if(parameters.get("SBI_LANGUAGE")!=null && parameters.get("SBI_COUNTRY")!=null){
        Locale locale=null;
        String language=(String)parameters.get("SBI_LANGUAGE");
        String country=(String)parameters.get("SBI_COUNTRY");
        logger.debug("Internazionalization in "+language);
        locale=new Locale(language,country,"");

        parameters.put("REPORT_LOCALE", locale);

        ResourceBundle rs=null;


        if(propertiesLoaded==false){

          //if properties file are not loaded by template load them from resources
          SourceBean config=null;
          if (getClass().getResource("/engine-config.xml")!=null){
            InputSource source=new InputSource(getClass().getResourceAsStream("/engine-config.xml"));
            config = SourceBean.fromXMLStream(source);  
          }
          SourceBean sb = (SourceBean)config.getAttribute("RESOURCE_PATH_JNDI_NAME");
          String path = (String) sb.getCharacters();
          String resPath= SpagoBIUtilities.readJndiResource(path);     
          resPath+="/jasper_messages/";

          ClassLoader previous = Thread.currentThread().getContextClassLoader();
          ResourceClassLoader dcl = new ResourceClassLoader(resPath,previous);
          //Thread.currentThread().setContextClassLoader(dcl);
          try
            //rs=PropertyResourceBundle.getBundle("messages",locale, Thread.currentThread().getContextClassLoader());
            rs=PropertyResourceBundle.getBundle("messages",locale, dcl);
          }
          catch (Exception e) {
            logger.error("could not find properties message");
          }
          parameters.put("REPORT_RESOURCE_BUNDLE", rs);
        }
      }

      Monitor monitorSubReport = MonitorFactory.start("JasperReportRunner.compileSubReport");
      // compile subreports
      //compiledSubreports = compileSubreports(parameters, getJRCompilationDir(servletContext, executionId),contentProxy, requestParameters);
      compiledSubreports = compileSubreports(parameters, servletContext, contentProxy, requestParameters);
      monitorSubReport.stop();   
      // set classloader
      ClassLoader previous = Thread.currentThread().getContextClassLoader();
      ClassLoader current = URLClassLoader.newInstance(new URL[]{getJRCompilationDir(servletContext, prefixDirTemplate).toURL()}, previous);
      Thread.currentThread().setContextClassLoader(current);

      // Create the virtualizer                 
      if(isVirtualizationActive()) {
        logger.debug("Virtualization of fill process is active");
        //parameters.put(JRParameter.REPORT_VIRTUALIZER, getVirtualizer(tmpDirectory, servletContext));
        parameters.put(JRParameter.REPORT_VIRTUALIZER, getSwapVirtualizer(tmpDirectory, servletContext));
        //parameters.put(JRParameter.REPORT_VIRTUALIZER, getGzipVirtualizer());
      }

      logger.debug("Filling report ...");
      Monitor monitorFillingReport =MonitorFactory.start("JasperReportRunner.FillingReport");
      JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameters, conn);
      monitorFillingReport.stop();
      logger.debug("Report filled succesfully");

      logger.debug("Exporting report ...");
      String outputType = (String) parameters.get("outputType");
      if(outputType == null) {
        logger.debug("Output type is not specified. Default type will be used");
        outputType = "html";
        //outputType = ExporterFactory.getDefaultType();
      }
      logger.debug("Output format is [" + outputType + "]");
      Monitor monitorExportReport =MonitorFactory.start("JasperReportRunner.ExportReport");
      JRExporter exporter = ExporterFactory.getExporter(outputType)
      String mimeType = ExporterFactory.getMIMEType(outputType);

      if(exporter != null) logger.debug("Configured exporter class [" + exporter.getClass().getName() + "]");
      else logger.debug("Exporter class [null]");
      logger.debug("Configured MIME type [" + mimeType + "]");

      // for base types use default exporter, mimeType and parameters if these
      // are not specified by configuration file
      if (outputType.equalsIgnoreCase("csv")) {
        if(mimeType == null) mimeType = "text/plain";
        servletResponse.setContentType(mimeType);
        if(exporter == null) exporter = new JRCsvExporter();
      } else if (outputType.equalsIgnoreCase("html")) {
        if(mimeType == null) mimeType = "text/html";
        servletResponse.setContentType(mimeType);
        if(exporter == null) exporter = new JRHtmlExporter();
        exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
        exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "");
        // define the map structure for report images
        HashMap m_imagesMap = new HashMap();
        String mapName = uuid_local.toString();
        servletRequest.getSession().setAttribute(mapName, m_imagesMap);
        exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP ,m_imagesMap);         
        //exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "image.jsp?mapname="+mapName+"&image=");
        exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "JRImageServlet?mapname="+mapName+"&image=");
       
        /* commented by Davide Zerbetto on 12/10/2009: there are problems with MIF (Ext ManagedIFrame library) library
        // setting HTML header: this is necessary in order to inject the document.domain directive
        String head = getHTMLHeader();
        exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER, head);
        */
      } else if (outputType.equalsIgnoreCase("xls")) {
        if(mimeType == null) mimeType = "application/vnd.ms-excel";
        servletResponse.setContentType(mimeType);
        //if(exporter == null) exporter = new JRXlsExporter();
        if(exporter == null) exporter = new JExcelApiExporter();
      } else if (outputType.equalsIgnoreCase("rtf")) {
        if(mimeType == null) mimeType = "application/rtf";
        servletResponse.setContentType(mimeType);
        if(exporter == null) exporter = new JRRtfExporter();
      } else if (outputType.equalsIgnoreCase("xml")) {
        if(mimeType == null) mimeType = "text/xml";
        servletResponse.setContentType(mimeType);
        if(exporter == null) exporter = new JRXmlExporter();
      } else if (outputType.equalsIgnoreCase("txt")) {
        if(mimeType == null) mimeType = "text/plain";
        servletResponse.setContentType(mimeType);
        if(exporter == null) exporter = new JRTextExporter();
        exporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT,new Integer(100));
        exporter.setParameter(JRTextExporterParameter.PAGE_WIDTH,new Integer(100));
      } else if (outputType.equalsIgnoreCase("pdf"))  {     
        if(mimeType == null) mimeType = "application/pdf";
        servletResponse.setContentType(mimeType);
        if(exporter == null) exporter = new JRPdfExporter();  
      } else if (outputType.equalsIgnoreCase("JPG"))  { 
        byte[] bytes = getImageBytes(report, jasperPrint);
        if(mimeType == null) mimeType = "application/jpeg";
        out.write(bytes);
        return;
      } else if (outputType.equalsIgnoreCase("JPGBASE64"))  { 
        byte[] bytes = getImagesBase64Bytes(report, jasperPrint);
        if(mimeType == null) mimeType = "text/plain";
        out.write(bytes);
        return;
      } else {
        if(mimeType != null && exporter != null) servletResponse.setContentType(mimeType);
        else {
          logger.warn("Impossible to load exporter for type " + outputType);
          logger.warn("Pdf exporter will be used");
          servletResponse.setContentType("application/pdf");
          exporter = new JRPdfExporter();
        }
      }

      logger.debug("MIME type of response is [" + servletResponse.getContentType()+ "]");
      logger.debug("Exporter class used is  [" + exporter.getClass().getName()+ "]");


      exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
      exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
      exporter.exportReport();
      monitorExportReport.stop();
      logger.debug("Report exported succesfully");


    } catch(Throwable e) {
      logger.error("An exception has occured", e);
View Full Code Here


  public byte[] executeChart(String token,String userId,String label,HashMap parameters){

    logger.debug("IN");
    Monitor monitor =MonitorFactory.start("spagobi.service.execute.executeChart");
    logger.debug("Getting profile");
   
    byte[] returnImage=null;
    IEngUserProfile userProfile=null;

    try {
      userProfile=it.eng.spagobi.commons.utilities.GeneralUtilities.createNewUserProfile(userId);
    } catch (Exception e2) {
      logger.error("Error recovering profile",e2);
      return "".getBytes();
    }


    logger.debug("Getting the chart object");

    IBIObjectDAO dao;
    BIObject obj=null;
    try {
      dao = DAOFactory.getBIObjectDAO();
      if(label!=null)
        obj=dao.loadBIObjectByLabel(label);
    } catch (EMFUserError e) {
      logger.error("Error in recovering object",e);
      return "".getBytes();
    }


    //***************************** GET THE TEMPLATE******************************************

    if(obj!=null){

      logger.debug("Getting template");

      SourceBean content = null;
      byte[] contentBytes = null;
      try{
        ObjTemplate template = DAOFactory.getObjTemplateDAO().getBIObjectActiveTemplate(obj.getId());
        if(template==null) throw new Exception("Active Template null");
        contentBytes = template.getContent();
        if(contentBytes==null) throw new Exception("Content of the Active template null");

        // get bytes of template and transform them into a SourceBean

        String contentStr = new String(contentBytes);
        content = SourceBean.fromXMLString(contentStr);
      } catch (Exception e) {
        logger.error("Error in reading template",e);
        return "".getBytes();
      }

      String type=content.getName();
      String subtype = (String)content.getAttribute("type");

      String data="";
      try{
        if(obj.getDataSetId()!=null){
          data=obj.getDataSetId().toString();
        } else {
          throw new Exception("Data Set not defined");           
        }
      }catch (Exception e) {
        logger.error("Error in reading dataset",e);
        return "".getBytes();
      }



      //***************************** GET PARAMETERS******************************************


      logger.debug("Getting parameters");

      HashMap parametersMap=null;

      //Search if the chart has parameters

      List parametersList=null;
      try {
        parametersList=DAOFactory.getBIObjectDAO().getBIObjectParameters(obj);
      } catch (EMFUserError e1) {
        logger.error("Error in retrieving parameters", e1);
        return "".getBytes();      }
      parametersMap=new HashMap();
      if(parametersList!=null && !parametersList.isEmpty()){
        for (Iterator iterator = parametersList.iterator(); iterator.hasNext();) {
          BIObjectParameter par= (BIObjectParameter) iterator.next();
          String url=par.getParameterUrlName();

          String value=(String)parameters.get(url);
          //List values=par.getParameterValues();
          if(value!=null){
            parametersMap.put(url, value);
          }
        } 
      }
     
      // if there are other parameters (like targets or baseline) that do not belong to the BiObject pass those anyway, extend this behaviour if necessary
      for (Iterator iterator = parameters.keySet().iterator(); iterator.hasNext();) {
        String namePar = (String) iterator.next();
        if(namePar.startsWith("target") || namePar.startsWith("baseline")){
          Object value=parameters.get(namePar);
          parametersMap.put(namePar, value);
        }
      }
     

      logger.debug("Creating the chart");

      ChartImpl sbi=null

      // set the right chart type
      sbi=ChartImpl.createChart(type, subtype);
      sbi.setProfile(userProfile);
      sbi.setType(type);
      sbi.setSubtype(subtype);
      sbi.setData(data);
      sbi.setParametersObject(parametersMap);
      // configure the chart with template parameters
      sbi.configureChart(content);


      DatasetMap datasets=null;
      try{
        datasets=sbi.calculateValue();
     
      catch (Exception e) {
        logger.error("Error in reading the value, check the dataset",e);
        return "".getBytes();
      }

      JFreeChart chart=null;
      // create the chart
      chart = sbi.createChart(datasets);

      ByteArrayOutputStream out=null;
      try{

        logger.debug("Write PNG Image");

        out=new ByteArrayOutputStream()
        ChartUtilities.writeChartAsPNG(out, chart, sbi.getWidth(), sbi.getHeight());
        returnImage=out.toByteArray();

      }
      catch (Exception e) {
        logger.error("Error while creating the image",e);
        return "".getBytes();
      }
      finally{
        try {
          out.close();
        } catch (IOException e) {
          logger.error("Error while closing stream",e);
        }
        monitor.stop();
      }
      //out.flush();
    }

    return returnImage;
View Full Code Here

TOP

Related Classes of com.jamonapi.Monitor

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.