/**
   * Method getTemplateName.
   *
   * @param id int
   * @return String
   * @see com.percussion.pso.restservice.support.IImportItemSystemInfo#getTemplateName(int)
   */
  public String getTemplateName(int id) {
    initServices();
    log.debug("Getting template name");
    String templatename = null;
    //		String templatename=templateNameMap.get(id);

    if (templatename == null) {
      try {
        IPSAssemblyTemplate template =
            aService.loadTemplate(new PSGuid(PSTypeEnum.TEMPLATE, id), false);
        templatename = template.getName();
      } catch (PSAssemblyException e) {
        log.error("cannot get template for id " + id, e);
        templatename = String.valueOf(id);
      }
    }

    IPSAssemblyTemplate template = null;
    try {
      template = aService.loadTemplate(new PSGuid(PSTypeEnum.TEMPLATE, id), false);
    } catch (PSAssemblyException e) {
      log.error("Cannot find template with id " + id);
    }
    log.debug("Got template name");
    return (template == null) ? Integer.toString(id) : template.getName();
  }
예제 #2
0
  private void setJasperResourceNames(ToolBoxDTO toolBoxDTO, String barDir)
      throws BAMToolboxDeploymentException {
    String jasperDirectory =
        barDir
            + File.separator
            + BAMToolBoxDeployerConstants.DASHBOARD_DIR
            + File.separator
            + BAMToolBoxDeployerConstants.JASPER_DIR;
    if (new File(jasperDirectory).exists()) {
      toolBoxDTO.setJasperParentDirectory(
          barDir
              + File.separator
              + BAMToolBoxDeployerConstants.DASHBOARD_DIR
              + File.separator
              + BAMToolBoxDeployerConstants.JASPER_DIR);
      Properties properties = new Properties();
      try {
        properties.load(
            new FileInputStream(
                barDir
                    + File.separator
                    + BAMToolBoxDeployerConstants.DASHBOARD_DIR
                    + File.separator
                    + BAMToolBoxDeployerConstants.JASPER_META_FILE));

        setJasperTabAndJrxmlNames(toolBoxDTO, properties);

        toolBoxDTO.setDataSource(properties.getProperty(BAMToolBoxDeployerConstants.DATASOURCE));
        toolBoxDTO.setDataSourceConfiguration(
            barDir
                + File.separator
                + BAMToolBoxDeployerConstants.DASHBOARD_DIR
                + File.separator
                + properties.getProperty(BAMToolBoxDeployerConstants.DATASOURCE_CONFIGURATION));
      } catch (FileNotFoundException e) {
        log.error(
            "No "
                + BAMToolBoxDeployerConstants.JASPER_META_FILE
                + " found in dir:"
                + barDir
                + File.separator
                + BAMToolBoxDeployerConstants.DASHBOARD_DIR,
            e);
        throw new BAMToolboxDeploymentException(
            "No "
                + BAMToolBoxDeployerConstants.JASPER_META_FILE
                + " found in dir:"
                + barDir
                + File.separator
                + BAMToolBoxDeployerConstants.DASHBOARD_DIR,
            e);
      } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new BAMToolboxDeploymentException(e.getMessage(), e);
      }
    } else {
      toolBoxDTO.setJasperParentDirectory(null);
      toolBoxDTO.setJasperTabs(new ArrayList<JasperTabDTO>());
    }
  }
예제 #3
0
  @Test
  public void testInheritedMethodsImplemented() throws Exception {
    int errors = 0;
    for (Method m : FileSystem.class.getDeclaredMethods()) {
      if (Modifier.isStatic(m.getModifiers())
          || Modifier.isPrivate(m.getModifiers())
          || Modifier.isFinal(m.getModifiers())) {
        continue;
      }

      try {
        MustNotImplement.class.getMethod(m.getName(), m.getParameterTypes());
        try {
          HarFileSystem.class.getDeclaredMethod(m.getName(), m.getParameterTypes());
          LOG.error("HarFileSystem MUST not implement " + m);
          errors++;
        } catch (NoSuchMethodException ex) {
          // Expected
        }
      } catch (NoSuchMethodException exc) {
        try {
          HarFileSystem.class.getDeclaredMethod(m.getName(), m.getParameterTypes());
        } catch (NoSuchMethodException exc2) {
          LOG.error("HarFileSystem MUST implement " + m);
          errors++;
        }
      }
    }
    assertTrue((errors + " methods were not overridden correctly - see log"), errors <= 0);
  }
 protected void loadComponents(Bundle bundle, RuntimeContext ctx) throws Exception {
   String list = getComponentsList(bundle);
   String name = bundle.getSymbolicName();
   log.debug("Bundle: " + name + " components: " + list);
   if (list == null) {
     return;
   }
   StringTokenizer tok = new StringTokenizer(list, ", \t\n\r\f");
   while (tok.hasMoreTokens()) {
     String path = tok.nextToken();
     URL url = bundle.getEntry(path);
     log.debug("Loading component for: " + name + " path: " + path + " url: " + url);
     if (url != null) {
       try {
         ctx.deploy(url);
       } catch (Exception e) {
         // just log error to know where is the cause of the
         // exception
         log.error("Error deploying resource: " + url);
         Framework.handleDevError(e);
         throw e;
       }
     } else {
       String message = "Unknown component '" + path + "' referenced by bundle '" + name + "'";
       log.error(message + ". Check the MANIFEST.MF");
       Framework.handleDevError(null);
       warnings.add(message);
     }
   }
 }
예제 #5
0
  public void doArtefactConfiguration() {
    if (!pluginBean.isReadableProperty(ARTEFACTS)) {
      return;
    }

    List l = (List) plugin.getProperty(ARTEFACTS);
    for (Object artefact : l) {
      if (artefact instanceof Class) {
        Class artefactClass = (Class) artefact;
        if (ArtefactHandler.class.isAssignableFrom(artefactClass)) {
          try {
            application.registerArtefactHandler((ArtefactHandler) artefactClass.newInstance());
          } catch (InstantiationException e) {
            LOG.error("Cannot instantiate an Artefact Handler:" + e.getMessage(), e);
          } catch (IllegalAccessException e) {
            LOG.error(
                "The constructor of the Artefact Handler is not accessible:" + e.getMessage(), e);
          }
        } else {
          LOG.error("This class is not an ArtefactHandler:" + artefactClass.getName());
        }
      } else {
        if (artefact instanceof ArtefactHandler) {
          application.registerArtefactHandler((ArtefactHandler) artefact);
        } else {
          LOG.error(
              "This object is not an ArtefactHandler:"
                  + artefact
                  + "["
                  + artefact.getClass().getName()
                  + "]");
        }
      }
    }
  }
  private int getHttpsPort() {
    try {
      MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
      QueryExp query = Query.eq(Query.attr("Scheme"), Query.value("https"));
      Set<ObjectName> objectNames = mBeanServer.queryNames(null, query);

      if (objectNames != null && objectNames.size() > 0) {
        for (ObjectName objectName : objectNames) {
          String name = objectName.toString();
          if (name.indexOf("port=") > -1) {
            String[] parts = name.split("port=");
            String port = parts[1];
            try {
              int portNum = Integer.parseInt(port);
              return portNum;
            } catch (NumberFormatException e) {
              logger.error("Error parsing https port:" + port);
              return -1;
            }
          }
        }
      }
    } catch (Throwable t) {
      logger.error("Error getting https port:", t);
    }

    return -1;
  }
 @Override
 public void receive(Message msg) {
   try {
     LOG.debug(
         "Table "
             + Bytes.toString(idxCoprocessor.getTableName())
             + " received message: Table "
             + Bytes.toString((byte[]) msg.getObject())
             + " must update its index columns cache.");
     if (Arrays.equals((byte[]) msg.getObject(), idxCoprocessor.getTableName())) {
       LOG.debug(
           "Table "
               + Bytes.toString(idxCoprocessor.getTableName())
               + " is updating its indexed columns cache.");
       idxCoprocessor.initIndexedColumnsForTable();
     }
   } catch (IOException e1) {
     LOG.error("Failed to update from the master index table.", e1);
   } catch (Exception e) {
     LOG.error(
         "Failed to read contents of message; updating from master index table just in case.", e);
     try {
       idxCoprocessor.initIndexedColumnsForTable();
     } catch (IOException e1) {
       LOG.error("Failed to update from the master index table.", e1);
     }
   }
 }
예제 #8
0
  /**
   * Adds a trust bundle to the system.
   *
   * @param uriInfo Injected URI context used for building the location URI.
   * @param bundle The bundle to add to the system.
   * @return Status of 201 if the bundle was added or a status of 409 if a bundle with the same name
   *     already exists.
   */
  @PUT
  @Consumes(MediaType.APPLICATION_JSON)
  public Response addTrustBundle(@Context UriInfo uriInfo, TrustBundle bundle) {
    // make sure it doesn't exist
    try {
      if (bundleDao.getTrustBundleByName(bundle.getBundleName()) != null)
        return Response.status(Status.CONFLICT).cacheControl(noCache).build();
    } catch (Exception e) {
      log.error("Error looking up bundle.", e);
      return Response.serverError().cacheControl(noCache).build();
    }

    try {
      final org.nhindirect.config.store.TrustBundle entityBundle =
          EntityModelConversion.toEntityTrustBundle(bundle);

      bundleDao.addTrustBundle(entityBundle);

      final UriBuilder newLocBuilder = uriInfo.getBaseUriBuilder();
      final URI newLoc = newLocBuilder.path("trustbundle/" + bundle.getBundleName()).build();

      // the trust bundle does not contain any of the anchors
      // they must be fetched from the URL... use the
      // refresh route to force downloading the anchors
      template.sendBody(entityBundle);

      return Response.created(newLoc).cacheControl(noCache).build();
    } catch (Exception e) {
      log.error("Error adding trust bundle.", e);
      return Response.serverError().cacheControl(noCache).build();
    }
  }
예제 #9
0
  /**
   * Updates the signing certificate of a trust bundle.
   *
   * @param bundleName The name of the trust bundle to update.
   * @param certData A DER encoded representation of the new signing certificate.
   * @return Status of 204 if the trust bundle's signing certificate was updated, status of 400 if
   *     the signing certificate is invalid, or a status 404 if a trust bundle with the given name
   *     does not exist.
   */
  @POST
  @Path("{bundle}/signingCert")
  @Consumes(MediaType.APPLICATION_JSON)
  public Response updateSigningCert(@PathParam("bundle") String bundleName, byte[] certData) {
    X509Certificate signingCert = null;
    if (certData.length > 0) {
      try {
        signingCert = CertUtils.toX509Certificate(certData);
      } catch (CertificateConversionException ex) {
        log.error("Signing certificate is not in a valid format " + bundleName, ex);
        return Response.status(Status.BAD_REQUEST).cacheControl(noCache).build();
      }
    }

    // make sure the bundle exists
    org.nhindirect.config.store.TrustBundle entityBundle;
    try {
      entityBundle = bundleDao.getTrustBundleByName(bundleName);
      if (entityBundle == null)
        return Response.status(Status.NOT_FOUND).cacheControl(noCache).build();
    } catch (Exception e) {
      log.error("Error looking up bundle.", e);
      return Response.serverError().cacheControl(noCache).build();
    }

    // now update
    try {
      bundleDao.updateTrustBundleSigningCertificate(entityBundle.getId(), signingCert);

      return Response.noContent().cacheControl(noCache).build();
    } catch (Exception e) {
      log.error("Error updating trust bundle signing certificate.", e);
      return Response.serverError().cacheControl(noCache).build();
    }
  }
  /**
   * Verifies user id with underline user store
   *
   * @param sequence TODO
   * @param userDTO bean class that contains user and tenant Information
   * @return true/false whether user is verified or not. If user is a tenant user then always return
   *     false
   */
  public VerificationBean verifyUserForRecovery(int sequence, UserDTO userDTO) {

    String userId = userDTO.getUserId();
    int tenantId = userDTO.getTenantId();
    boolean success = false;
    VerificationBean bean = null;
    try {
      UserStoreManager userStoreManager =
          IdentityMgtServiceComponent.getRealmService()
              .getTenantUserRealm(tenantId)
              .getUserStoreManager();

      if (userStoreManager.isExistingUser(userId)) {
        if (IdentityMgtConfig.getInstance().isAuthPolicyAccountLockCheck()) {
          String accountLock =
              userStoreManager.getUserClaimValue(userId, UserIdentityDataStore.ACCOUNT_LOCK, null);
          if (!Boolean.parseBoolean(accountLock)) {
            success = true;
          }
        } else {
          success = true;
        }
      } else {
        log.error(
            "User with user name : "
                + userId
                + " does not exists in tenant domain : "
                + userDTO.getTenantDomain());
        bean =
            new VerificationBean(
                VerificationBean.ERROR_CODE_INVALID_USER + " " + "User does not exists");
      }

      if (success) {
        String internalCode = generateUserCode(sequence, userId);
        String key = UUID.randomUUID().toString();
        UserRecoveryDataDO dataDO = new UserRecoveryDataDO(userId, tenantId, internalCode, key);
        if (sequence != 3) {
          dataStore.invalidate(userId, tenantId);
        }
        dataStore.store(dataDO);
        log.info(
            "User verification successful for user : "******" from tenant domain :"
                + userDTO.getTenantDomain());

        bean = new VerificationBean(userId, getUserExternalCodeStr(internalCode));
      }
    } catch (Exception e) {
      String errorMessage = "Error verifying user : "******" " + errorMessage);
    }

    if (bean == null) {
      bean = new VerificationBean(VerificationBean.ERROR_CODE_UNEXPECTED);
    }
    return bean;
  }
  /**
   * @param compositeUrl
   * @param scaZipUrls
   * @return
   * @throws Exception
   */
  public Composite readComposite(URL compositeUrl, int mode, URL... scaZipUrls) throws Exception {

    if (frascati == null) {
      String msg =
          "No FraSCAtiService attached to this FraSCAti Registry Service "
              + "when reading composite "
              + compositeUrl;
      log.debug(msg);
      throw new Exception(msg);
    }
    // Create a processing context with where to find ref'd classes
    log.debug("composite URL = " + compositeUrl);
    log.debug("scaZipUrls = " + scaZipUrls);

    String compositeName = null;

    try {
      compositeName = frascati.processComposite(compositeUrl.toString(), mode, scaZipUrls);
    } catch (FraSCAtiServiceException fe) {
      log.error("The number of checking errors is equals to " + frascati.getErrors());
      log.error("The number of checking warnings is equals to " + frascati.getWarnings());
      log.error(fe);
    }
    // TODO feed parsing errors / warnings up to UI ?!
    log.warn("\nErrors while parsing " + compositeUrl + ":\n" + frascati.getErrorMessages());
    log.info("\nWarnings while parsing " + compositeUrl + ":\n" + frascati.getWarningMessages());

    Composite composite = frascati.getComposite(compositeName);

    if (composite == null) {
      throw new FraSCAtiRegistryException("Composite '" + compositeUrl + "' can not be loaded");
    }
    return composite;
  }
예제 #12
0
  /** Rename the file to a good format. */
  @Override
  public void renameFiles() {
    updateModel();

    // check for validation errors, if any then do no changes
    if (hasErrors()) {
      LOG.error(Resources.getString("messages.editorerrors"));
      MessageUtil.showError(this, Resources.getString("messages.editorerrors")); // AZ
      return;
    }

    if (musicTag == null) {
      LOG.error(Resources.getString("messages.filenotexists"));
      MessageUtil.showError(this, Resources.getString("messages.filenotexists")); // AZ
      return;
    }

    try {
      setBusyCursor(true);
      if (this.musicTag.renameFile(this.getSettings().getFileFormatMusic())) {
        getTrack().setTrackUrl(this.musicTag.getAbsolutePath());
        commit();
      }
    } catch (InfrastructureException ex) {
      LOG.error(ex.getMessage());
      MessageUtil.showError(this, ex.getMessage());
    } catch (Exception ex) {
      LOG.error(Resources.getString("messages.ErrorRenamingFile"), ex);
      MessageUtil.showError(this, Resources.getString("messages.ErrorRenamingFile"));
    } finally {
      setBusyCursor(false);
    }
  }
  /**
   *
   *
   * <PRE>
   * Desc : Retrieve SQL
   * </PRE>
   *
   * @param Connection
   * @param RetrieveModel
   * @return RetrieveModel
   */
  public RetrieveModel retrieve(Connection con, RetrieveModel retrieve) throws StoreException {
    PreparedStatement pstmt = null;
    ResultSet rset = null;

    try {
      pstmt = con.prepareStatement(makeSql(retrieve));

      int index = 1;
      pstmt.setString(index++, retrieve.getString("pay_yymm"));
      pstmt.setString(index++, retrieve.getString("pay_times"));
      pstmt.setString(index++, retrieve.getString("entp_code"));

      rset = pstmt.executeQuery();

      retrieve.put("RESULT", makeSheet(rset));

    } catch (SQLException se) {
      log.error(
          "[AccountPaymentRegSvc.retrieve() SQLException : ERR-" + se.getErrorCode() + ":" + se);
      throw new StoreException(se.getMessage());
    } catch (Exception e) {
      log.error("[AccountPaymentRegSvc.retrieve() Exception : ERR-" + e.getMessage());
      throw new StoreException(e.getMessage());
    } finally {
      DBUtils.freeConnection(null, pstmt, rset);
    }
    return retrieve;
  }
예제 #14
0
  protected Object executeScript(
      ScriptFactory scriptFactory,
      HttpServletRequest request,
      HttpServletResponse response,
      String scriptUrl) {
    Map<String, Object> scriptVariables = createScriptVariables(request, response);

    try {
      return scriptFactory.getScript(scriptUrl).execute(scriptVariables);
    } catch (ScriptNotFoundException e) {
      logger.error("Script not found at " + scriptUrl, e);

      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

      return Collections.singletonMap(errorMessageModelAttributeName, "REST script not found");
    } catch (Exception e) {
      logger.error("Error executing REST script at " + scriptUrl, e);

      HttpStatusCodeAwareException cause =
          ExceptionUtils.getThrowableOfType(e, HttpStatusCodeAwareException.class);
      String errorMsg;

      if (cause != null) {
        response.setStatus(cause.getStatusCode());

        errorMsg = ((Exception) cause).getMessage();
      } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        errorMsg = e.getMessage();
      }

      return Collections.singletonMap(errorMessageModelAttributeName, errorMsg);
    }
  }
예제 #15
0
 public static long getScriptLastModified(ServletContext context, String scriptPath)
     throws ScriptException {
   long result = -1;
   URLConnection uc = null;
   try {
     URL scriptUrl = context.getResource(canonicalURI(scriptPath));
     if (scriptUrl == null) {
       String msg = "Requested resource " + scriptPath + " cannot be found";
       log.error(msg);
       throw new ScriptException(msg);
     }
     uc = scriptUrl.openConnection();
     if (uc instanceof JarURLConnection) {
       result = ((JarURLConnection) uc).getJarEntry().getTime();
     } else {
       result = uc.getLastModified();
     }
   } catch (IOException e) {
     log.warn("Error getting last modified time for " + scriptPath, e);
     result = -1;
   } finally {
     if (uc != null) {
       try {
         uc.getInputStream().close();
       } catch (IOException e) {
         log.error("Error closing input stream for script " + scriptPath, e);
       }
     }
   }
   return result;
 }
예제 #16
0
  public void onException(ErrorMessage msg) throws MuleException {
    Class eClass = null;
    ExceptionHandler eh = null;

    try {
      eClass = msg.getException().toException().getClass();
      eh = getHandler(eClass);
      eh.onException(msg);
    } catch (Exception e) {
      logger.error(e);

      if (eh instanceof DefaultHandler) {
        logger.error(LocaleMessage.defaultFatalHandling(FatalHandler.class));
        handleFatal(e);

      } else if (eh instanceof FatalHandler) {
        logger.fatal(LocaleMessage.fatalHandling(e));
        MuleServer.getMuleContext().dispose();
        System.exit(-1);
      } else {
        logger.error(LocaleMessage.defaultHandling(DefaultHandler.class, eh, e));
        handleDefault(msg, e);
      }
    }
  }
예제 #17
0
  private void logIOException(NHttpServerConnection conn, IOException e) {
    // this check feels like crazy! But weird things happened, when load testing.
    if (e == null) {
      return;
    }
    if (e instanceof ConnectionClosedException
        || (e.getMessage() != null
            && (e.getMessage().toLowerCase().contains("connection reset by peer")
                || e.getMessage().toLowerCase().contains("forcibly closed")))) {
      if (log.isDebugEnabled()) {
        log.debug(
            conn
                + ": I/O error (Probably the keepalive connection "
                + "was closed):"
                + e.getMessage());
      }
    } else if (e.getMessage() != null) {
      String msg = e.getMessage().toLowerCase();
      if (msg.indexOf("broken") != -1) {
        log.warn(
            "I/O error (Probably the connection "
                + "was closed by the remote party):"
                + e.getMessage());
      } else {
        log.error("I/O error: " + e.getMessage(), e);
      }

      metrics.incrementFaultsReceiving();
    } else {
      log.error("Unexpected I/O error: " + e.getClass().getName(), e);

      metrics.incrementFaultsReceiving();
    }
  }
예제 #18
0
 public String transform(String type, String input, Map<String, String> transformModel)
     throws TransformException {
   if (log.isDebugEnabled()) {
     log.debug("transform(input=" + input + ")");
   }
   try {
     Templates template = templates.get(type);
     if (log.isDebugEnabled()) {
       log.debug("template=" + template);
     }
     if (template != null) {
       Transformer transformer = template.newTransformer();
       StringWriter writer = new StringWriter(INITIAL_BUFFER_SIZE);
       transformer.setErrorListener(new DefaultErrorListener());
       if (transformModel != null) {
         for (Map.Entry<String, String> entry : transformModel.entrySet()) {
           transformer.setParameter(entry.getKey(), entry.getValue());
         }
       }
       transformer.transform(new StreamSource(new StringReader(input)), new StreamResult(writer));
       String result = writer.toString().trim();
       if (log.isDebugEnabled()) {
         log.debug("result=" + result);
       }
       return result;
     } else {
       String errMsg = "Transformation '" + type + "' not available";
       log.error(errMsg);
       throw new RuntimeException(errMsg);
     }
   } catch (Exception e) {
     log.error("Error during transform", e);
     throw new TransformException(e);
   }
 }
예제 #19
0
  public void initCapability() {

    try {
      log.info("INFO: Before test, getting queue...");
      Assert.assertNotNull(queueManagerFactory);

      queueCapability = queueManagerFactory.create(mockResource);
      queueCapability.initialize();

      protocolManager.getProtocolSessionManagerWithContext(
          mockResource.getResourceId(), newSessionContextNetconf());

      // Test elements not null
      log.info("Checking chassis factory");
      Assert.assertNotNull(chassisFactory);
      log.info("Checking capability descriptor");
      Assert.assertNotNull(mockResource.getResourceDescriptor().getCapabilityDescriptor("chassis"));
      log.info("Creating chassis capability");
      chassisCapability = chassisFactory.create(mockResource);
      Assert.assertNotNull(chassisCapability);
      chassisCapability.initialize();

      mockResource.addCapability(chassisCapability);
      mockResource.addCapability(queueCapability);

    } catch (Exception e) {
      e.printStackTrace();
      log.error(e.getMessage());
      if (ExceptionUtils.getRootCause(e) != null)
        log.error(ExceptionUtils.getRootCause(e).getMessage());
      Assert.fail(e.getMessage());
    }
  }
예제 #20
0
 /**
  * Creates a serializable blob from a stream, with filename and mimetype detection.
  *
  * <p>Creates an in-memory blob if data is under 64K, otherwise constructs a serializable FileBlob
  * which stores data in a temporary file on the hard disk.
  *
  * @param file the input stream holding data
  * @param filename the file name. Will be set on the blob and will used for mimetype detection.
  * @param mimeType the detected mimetype at upload. Can be null. Will be verified by the mimetype
  *     service.
  */
 public static Blob createSerializableBlob(InputStream file, String filename, String mimeType) {
   Blob blob = null;
   try {
     // persisting the blob makes it possible to read the binary content
     // of the request stream several times (mimetype sniffing, digest
     // computation, core binary storage)
     blob = StreamingBlob.createFromStream(file, mimeType).persist();
     // filename
     if (filename != null) {
       filename = getCleanFileName(filename);
     }
     blob.setFilename(filename);
     // mimetype detection
     MimetypeRegistry mimeService = Framework.getService(MimetypeRegistry.class);
     String detectedMimeType =
         mimeService.getMimetypeFromFilenameAndBlobWithDefault(filename, blob, null);
     if (detectedMimeType == null) {
       if (mimeType != null) {
         detectedMimeType = mimeType;
       } else {
         // default
         detectedMimeType = "application/octet-stream";
       }
     }
     blob.setMimeType(detectedMimeType);
   } catch (MimetypeDetectionException e) {
     log.error(String.format("could not fetch mimetype for file %s", filename), e);
   } catch (IOException e) {
     log.error(e);
   } catch (Exception e) {
     log.error(e);
   }
   return blob;
 }
예제 #21
0
 private void extractToUnicodeEncoding() {
   COSName encodingName = null;
   String cmapName = null;
   COSBase toUnicode = getToUnicode();
   if (toUnicode != null) {
     setHasToUnicode(true);
     if (toUnicode instanceof COSStream) {
       try {
         toUnicodeCmap =
             parseCmap(resourceRootCMAP, ((COSStream) toUnicode).getUnfilteredStream());
       } catch (IOException exception) {
         LOG.error("Error: Could not load embedded ToUnicode CMap");
       }
     } else if (toUnicode instanceof COSName) {
       encodingName = (COSName) toUnicode;
       toUnicodeCmap = cmapObjects.get(encodingName.getName());
       if (toUnicodeCmap == null) {
         cmapName = encodingName.getName();
         String resourceName = resourceRootCMAP + cmapName;
         try {
           toUnicodeCmap = parseCmap(resourceRootCMAP, ResourceLoader.loadResource(resourceName));
         } catch (IOException exception) {
           LOG.error(
               "Error: Could not find predefined ToUnicode CMap file for '" + cmapName + "'");
         }
         if (toUnicodeCmap == null) {
           LOG.error(
               "Error: Could not parse predefined ToUnicode CMap file for '" + cmapName + "'");
         }
       }
     }
   }
 }
예제 #22
0
  /**
   * Normally called to initialize CoherenceCache. To be able to test the method without having
   * <code>com.tangosol.net.CacheFactory</code> implementation, it can also be called with a test
   * implementations classname.
   *
   * @param implementation Cache implementation classname to initialize.
   * @param params Parameters to initialize the cache (e.g. name, capacity).
   * @throws CacheAcquireException If cache can not be initialized.
   */
  @SuppressWarnings("unchecked")
  public void initialize(final String implementation, final Properties params)
      throws CacheAcquireException {
    super.initialize(params);

    String cacheURL = params.getProperty("cacheURL", DEFAULT_CACHE_URL);
    String cacheProperties = params.getProperty("cacheProperties", DEFAULT_CACHE_PROPERTIES);

    StringBuffer clusterURL = new StringBuffer();
    clusterURL.append(cacheURL);
    clusterURL.append(getName());
    clusterURL.append("?");
    clusterURL.append(cacheProperties);

    if (LOG.isDebugEnabled()) {
      LOG.debug(clusterURL.toString());
    }

    try {
      ClassLoader ldr = this.getClass().getClassLoader();
      Class<?> cls = ldr.loadClass(implementation);
      setCache(
          (Map)
              invokeStaticMethod(
                  cls, "find", TYPES_FIND_CACHE, new Object[] {clusterURL.toString()}));
    } catch (Exception e) {
      LOG.error("Problem!", e);
      String msg = "Error creating Gigaspaces cache: " + e.getMessage();
      LOG.error(msg, e);
      throw new CacheAcquireException(msg, e);
    }
  }
  protected void activate(ComponentContext context) {
    try {
      bundleContext = context.getBundleContext();
      if (CommonUtil.getStratosConfig() == null) {
        StratosConfiguration stratosConfig = CommonUtil.loadStratosConfiguration();
        CommonUtil.setStratosConfig(stratosConfig);
      }

      // Loading the EULA
      if (CommonUtil.getEula() == null) {
        String eula = CommonUtil.loadTermsOfUsage();
        CommonUtil.setEula(eula);
      }

      // packageInfos = new PackageInfoHolder();
      // context.getBundleContext().registerService(
      //		PackageInfoHolder.class.getName(), packageInfos, null);

      // Register manager configuration OSGI service
      try {
        StratosConfiguration stratosConfiguration = CommonUtil.loadStratosConfiguration();
        bundleContext.registerService(
            StratosConfiguration.class.getName(), stratosConfiguration, null);
        if (log.isDebugEnabled()) {
          log.debug("******* Cloud Common Service bundle is activated ******* ");
        }
      } catch (Exception ex) {
        String msg = "An error occurred while initializing Cloud Common Service as an OSGi Service";
        log.error(msg, ex);
      }
    } catch (Throwable e) {
      log.error("Error in activating Cloud Common Service Component" + e.toString());
    }
  }
예제 #24
0
  /**
   * @param sqlstr
   * @return boolean
   */
  public boolean query(String sqlstr, boolean useInternalTx) {
    try {

      rs = stmt.executeQuery(sqlstr);
      if (useInternalTx) {
        conn.commit();
      }
    } catch (SQLException e) {

      logger.error(QUERY_ERROR + e.getMessage() + " -- " + sqlstr);
      try {
        if (useInternalTx) {
          conn.rollback();
        }
      } catch (SQLException e1) {
        logger.error(ROLLBACK_ERROR + e1.getMessage());
      }
      return false;
    } catch (Exception e) {
      logger.error(QUERY_ERROR + e.getMessage() + ")");
      errorCode = 2;

      return false;
    }

    return true;
  }
예제 #25
0
 public void setEntitySubtypeSchemaEnum(String schemaEnumId) {
   String[] params = TextUtils.getInstance().split(schemaEnumId, ",", true);
   if (params.length != 2)
     log.error(
         "the entity-subtype-schema-enum attribute in the entity page requires 2 params: schema.enum-table,enum-id-or-caption");
   else {
     Project project = getOwner().getProject();
     Table table = project.getSchemas().getTable(params[0]);
     if (table == null || !(table instanceof EnumerationTable))
       log.error(
           "the entity-subtype-schema-enum attribute in the entity page has an invalid schema.enum-table: "
               + params[0]);
     else {
       EnumerationTable enumTable = (EnumerationTable) table;
       EnumerationTableRows enumRows = (EnumerationTableRows) enumTable.getData();
       EnumerationTableRow enumRow = enumRows.getByIdOrCaptionOrAbbrev(params[1]);
       if (enumRow == null)
         log.error(
             "the entity-subtype-schema-enum attribute in the entity page has an invalid enum value for "
                 + params[0]
                 + ": "
                 + params[1]);
       else {
         setEntitySubtypeId(enumRow.getId());
         setEntitySubtypeName(enumRow.getCaption());
       }
     }
   }
 }
예제 #26
0
  public boolean update(String sqlstr, boolean useInternalTx) {
    try {
      logger.info("exec:" + sqlstr);
      stmt.executeUpdate(sqlstr);
      if (useInternalTx) {
        conn.commit();
      }
    } catch (SQLException e) {
      logger.error("SQLException", e);

      logger.error(UPDATE_ERROR + e.getMessage() + " -- " + sqlstr);
      if (getErrorCode(e.getMessage()).equalsIgnoreCase("ORA-02292")) {
        errorCode = 3;
      }
      try {
        if (useInternalTx) {
          conn.rollback();
        }
      } catch (SQLException e1) {
        logger.error(ROLLBACK_ERROR + e1.getMessage());
      }
      return false;
    } catch (Exception e) {
      logger.error(UPDATE_ERROR + e.getMessage() + ")");
      errorCode = 2;

      return false;
    }

    return true;
  }
예제 #27
0
  /**
   * Stop the proxy. Proxy must either implement {@link Closeable} or must have associated {@link
   * RpcInvocationHandler}.
   *
   * @param proxy the RPC proxy object to be stopped
   * @throws HadoopIllegalArgumentException if the proxy does not implement {@link Closeable}
   *     interface or does not have closeable {@link InvocationHandler}
   */
  public static void stopProxy(Object proxy) {
    if (proxy == null) {
      throw new HadoopIllegalArgumentException("Cannot close proxy since it is null");
    }
    try {
      if (proxy instanceof Closeable) {
        ((Closeable) proxy).close();
        return;
      } else {
        InvocationHandler handler = Proxy.getInvocationHandler(proxy);
        if (handler instanceof Closeable) {
          ((Closeable) handler).close();
          return;
        }
      }
    } catch (IOException e) {
      LOG.error("Closing proxy or invocation handler caused exception", e);
    } catch (IllegalArgumentException e) {
      LOG.error("RPC.stopProxy called on non proxy: class=" + proxy.getClass().getName(), e);
    }

    // If you see this error on a mock object in a unit test you're
    // developing, make sure to use MockitoUtil.mockProtocol() to
    // create your mock.
    throw new HadoopIllegalArgumentException(
        "Cannot close proxy - is not Closeable or "
            + "does not provide closeable invocation handler "
            + proxy.getClass());
  }
예제 #28
0
 public static void undeploy(org.apache.catalina.Context context) {
   String contextPath = context.getServletContext().getContextPath();
   List<String> taskIds = timeouts.get(contextPath);
   if (taskIds != null) {
     for (String taskId : taskIds) {
       try {
         log.debug("clearTimeout : " + taskId);
         RhinoTopLevel.clearTimeout(taskId);
       } catch (ScriptException e) {
         log.error(e.getMessage(), e);
       }
     }
   }
   taskIds = intervals.get(contextPath);
   if (taskIds != null) {
     for (String taskId : taskIds) {
       try {
         log.debug("clearInterval : " + taskId);
         RhinoTopLevel.clearInterval(taskId);
       } catch (ScriptException e) {
         log.error(e.getMessage(), e);
       }
     }
   }
   log.debug("Releasing resources of : " + context.getServletContext().getContextPath());
 }
  /** Generates JMS messages */
  public void generateAndSendMessages(final CacheFlushMessageJms cacheFlushMessageJms) {
    try {
      final String valueJMSMessage =
          xmlMapper.getXmlMapper().writeValueAsString(cacheFlushMessageJms);

      if (StringUtils.isNotEmpty(valueJMSMessage)) {
        jmsTemplate.send(
            new MessageCreator() {
              public Message createMessage(Session session) throws JMSException {
                TextMessage message = session.createTextMessage(valueJMSMessage);
                if (logger.isDebugEnabled()) {
                  logger.info("Sending JMS message: " + valueJMSMessage);
                }
                return message;
              }
            });
      } else {
        logger.warn("Cache Flush Message Jms Message is empty");
      }

    } catch (JmsException e) {
      logger.error("Exception during create/send message process");
    } catch (JsonProcessingException e) {
      logger.error("Exception during build message process");
    }
  }
예제 #30
0
  private static File getHumanMediaTypeMappingsFile() throws RegistryException {

    String carbonHome = System.getProperty("carbon.home");

    if (carbonHome == null) {
      carbonHome = System.getenv("CARBON_HOME");
    }

    if (carbonHome != null) {

      File mediaTypesFile =
          new File(
              CarbonUtils.getEtcCarbonConfigDirPath(), HUMAN_READABLE_MEDIA_TYPE_MAPPINGS_FILE);
      if (!mediaTypesFile.exists()) {
        String msg =
            "Resource human readable media type mappings file (mime.mappings) file does "
                + "not exist in the path "
                + CarbonUtils.getEtcCarbonConfigDirPath();
        log.error(msg);
        throw new RegistryException(msg);
      }

      return mediaTypesFile;

    } else {
      String msg =
          "carbon.home system property is not set. It is required to to derive "
              + "the path of the media type definitions file (mime.types).";
      log.error(msg);
      throw new RegistryException(msg);
    }
  }