Search in sources :

Example 1 with CarbonException

use of org.wso2.carbon.CarbonException in project core-util by WSO2Telco.

the class BasicAuthenticator method isAuthenticatedUser.

public boolean isAuthenticatedUser(String userName, String password) {
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class, null);
    RegistryService registryService = (RegistryService) carbonContext.getOSGiService(RegistryService.class, null);
    String tenantDomain = MultitenantUtils.getTenantDomain(userName);
    try {
        UserRealm userRealm = null;
        userRealm = AnonymousSessionUtil.getRealmByTenantDomain(registryService, realmService, tenantDomain);
        if (userRealm == null) {
            log.error("invalid domain or unactivated tenant login");
            return false;
        }
        String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(userName);
        if (userRealm.getUserStoreManager().authenticate(tenantAwareUsername, password)) {
            return true;
        } else {
            log.error("authentication failed. please check your username/password");
            return false;
        }
    } catch (CarbonException | UserStoreException e) {
        log.error("authentication failed for user : " + userName, e);
        return false;
    }
}
Also used : UserRealm(org.wso2.carbon.user.core.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) CarbonException(org.wso2.carbon.CarbonException) UserStoreException(org.wso2.carbon.user.core.UserStoreException) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) RegistryService(org.wso2.carbon.registry.core.service.RegistryService)

Example 2 with CarbonException

use of org.wso2.carbon.CarbonException in project carbon-business-process by wso2.

the class BPELUploadExecutor method execute.

public boolean execute(HttpServletRequest request, HttpServletResponse response) throws CarbonException, IOException {
    String errMsg;
    response.setContentType("text/html; charset=utf-8");
    PrintWriter out = response.getWriter();
    String webContext = (String) request.getAttribute(CarbonConstants.WEB_CONTEXT);
    String serverURL = (String) request.getAttribute(CarbonConstants.SERVER_URL);
    String cookie = (String) request.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
    Map<String, ArrayList<FileItemData>> fileItemsMap = getFileItemsMap();
    if (fileItemsMap == null || fileItemsMap.isEmpty()) {
        String msg = "File uploading failed.";
        log.error(msg);
        out.write("<textarea>" + "(function(){i18n.fileUplodedFailed();})();" + "</textarea>");
        return true;
    }
    BPELUploaderClient uploaderClient = new BPELUploaderClient(configurationContext, serverURL + "BPELUploader", cookie);
    SaveExtractReturn uploadedFiles = null;
    ArrayList<String> extractedFiles = new ArrayList<String>();
    try {
        for (FileItemData fieldData : fileItemsMap.get("bpelFileName")) {
            String fileName = getFileName(fieldData.getFileItem().getName());
            // Check filename for \ charactors. This cannot be handled at the lower stages.
            if (fileName.matches("(.*[\\\\].*[/].*|.*[/].*[\\\\].*)")) {
                log.error("BPEL Package Validation Failure: one or many of the following illegal characters are " + "in " + "the package.\n ~!@#$;%^*()+={}[]| \\<>");
                throw new Exception("BPEL Package Validation Failure: one or many of the following illegal " + "characters " + "are in the package. ~!@#$;%^*()+={}[]| \\<>");
            }
            // Check file extension.
            checkServiceFileExtensionValidity(fileName, ALLOWED_FILE_EXTENSIONS);
            if (fileName.lastIndexOf('\\') != -1) {
                int indexOfColon = fileName.lastIndexOf('\\') + 1;
                fileName = fileName.substring(indexOfColon, fileName.length());
            }
            if (fieldData.getFileItem().getFieldName().equals("bpelFileName")) {
                uploadedFiles = saveAndExtractUploadedFile(fieldData.getFileItem());
                extractedFiles.add(uploadedFiles.extractedFile);
                validateBPELPackage(uploadedFiles.extractedFile);
                DataSource dataSource = new FileDataSource(uploadedFiles.zipFile);
                uploaderClient.addUploadedFileItem(new DataHandler(dataSource), fileName, "zip");
            }
        }
        uploaderClient.uploadFileItems();
        String msg = "Your BPEL package been uploaded successfully. Please refresh this page in a" + " while to see the status of the new process.";
        CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.INFO, request, response, getContextRoot(request) + "/" + webContext + "/bpel/process_list.jsp");
        return true;
    } catch (Exception e) {
        errMsg = "File upload failed :" + e.getMessage();
        log.error(errMsg, e);
        CarbonUIMessage.sendCarbonUIMessage(errMsg, CarbonUIMessage.ERROR, request, response, getContextRoot(request) + "/" + webContext + "/bpel/upload_bpel.jsp");
    } finally {
        for (String s : extractedFiles) {
            File extractedFile = new File(s);
            if (log.isDebugEnabled()) {
                log.debug("Cleaning temporarily extracted BPEL artifacts in " + extractedFile.getParent());
            }
            try {
                FileUtils.cleanDirectory(new File(extractedFile.getParent()));
            } catch (IOException ex) {
                log.warn("Failed to clean temporary extractedFile.", ex);
            }
        }
    }
    return false;
}
Also used : FileItemData(org.wso2.carbon.utils.FileItemData) ArrayList(java.util.ArrayList) DataHandler(javax.activation.DataHandler) IOException(java.io.IOException) IOException(java.io.IOException) CarbonException(org.wso2.carbon.CarbonException) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) FileDataSource(javax.activation.FileDataSource) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 3 with CarbonException

use of org.wso2.carbon.CarbonException in project carbon-business-process by wso2.

the class BPMNUploadExecutor method execute.

@Override
public boolean execute(HttpServletRequest request, HttpServletResponse response) throws CarbonException, IOException {
    String errMsg;
    response.setContentType("text/html; charset=utf-8");
    PrintWriter out = response.getWriter();
    String webContext = (String) request.getAttribute(CarbonConstants.WEB_CONTEXT);
    String serverURL = (String) request.getAttribute(CarbonConstants.SERVER_URL);
    String cookie = (String) request.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
    Map<String, ArrayList<FileItemData>> fileItemsMap = getFileItemsMap();
    if (fileItemsMap == null || fileItemsMap.isEmpty()) {
        String msg = "File uploading failed.";
        log.error(msg);
        out.write("<textarea>" + "(function(){i18n.fileUplodedFailed();})();" + "</textarea>");
        return true;
    }
    BPMNUploaderClient uploaderClient = new BPMNUploaderClient(configurationContext, serverURL + "BPMNUploaderService", cookie);
    File uploadedTempFile;
    try {
        for (FileItemData fileData : fileItemsMap.get("bpmnFileName")) {
            String fileName = getFileName(fileData.getFileItem().getName());
            // Check filename for \ charactors. This cannot be handled at the lower stages.
            if (fileName.matches("(.*[\\\\].*[/].*|.*[/].*[\\\\].*)")) {
                log.error("BPMN Package Validation Failure: one or more of the following illegal characters are in " + "the package.\n ~!@#$;%^*()+={}[]| \\<>");
                throw new Exception("BPMN Package Validation Failure: one or more of the following illegal characters " + "are in the package. ~!@#$;%^*()+={}[]| \\<>");
            }
            // Check file extension.
            checkServiceFileExtensionValidity(fileName, ALLOWED_FILE_EXTENSIONS);
            if (fileName.lastIndexOf('\\') != -1) {
                int indexOfColon = fileName.lastIndexOf('\\') + 1;
                fileName = fileName.substring(indexOfColon, fileName.length());
            }
            if (fileData.getFileItem().getFieldName().equals("bpmnFileName")) {
                uploadedTempFile = new File(CarbonUtils.getTmpDir(), fileName);
                fileData.getFileItem().write(uploadedTempFile);
                DataSource dataSource = new FileDataSource(uploadedTempFile);
                uploaderClient.addUploadedFileItem(new DataHandler(dataSource), fileName, "bar");
            }
        }
        uploaderClient.uploadFileItems();
        String msg = "Your BPMN package has been uploaded successfully. Please refresh this page in a" + " while to see the status of the new process.";
        CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.INFO, request, response, getContextRoot(request) + "/" + webContext + "/bpmn/process_list_view.jsp");
        return true;
    } catch (Exception e) {
        errMsg = "File upload failed :" + e.getMessage();
        log.error(errMsg, e);
        CarbonUIMessage.sendCarbonUIMessage(errMsg, CarbonUIMessage.ERROR, request, response, getContextRoot(request) + "/" + webContext + "/bpmn/process_list_view.jsp");
    }
    return false;
}
Also used : FileItemData(org.wso2.carbon.utils.FileItemData) ArrayList(java.util.ArrayList) FileDataSource(javax.activation.FileDataSource) DataHandler(javax.activation.DataHandler) File(java.io.File) IOException(java.io.IOException) CarbonException(org.wso2.carbon.CarbonException) PrintWriter(java.io.PrintWriter) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource)

Example 4 with CarbonException

use of org.wso2.carbon.CarbonException in project jaggery by wso2.

the class TomcatJaggeryWebappsDeployer method handleZipWebappDeployment.

/**
 * Handle the deployment of a an archive Jaggery app. i.e., a WAR
 *
 * @param webapp                    The WAR Jaggery app file
 * @param webContextParams          ServletContext params for this webapp
 * @param applicationEventListeners Application event listeners
 * @throws CarbonException If a deployment error occurs
 */
@SuppressFBWarnings("PATH_TRAVERSAL_IN")
protected void handleZipWebappDeployment(File webapp, List<WebContextParameter> webContextParams, List<Object> applicationEventListeners) throws CarbonException {
    synchronized (this) {
        String appPath = webapp.getAbsolutePath().substring(0, webapp.getAbsolutePath().indexOf(".zip"));
        try {
            JaggeryDeploymentUtil.unZip(new FileInputStream(webapp), appPath);
            if (!webapp.delete()) {
                throw new CarbonException(appPath + "could not be deleted");
            }
        } catch (FileNotFoundException e) {
            throw new CarbonException(e);
        }
        File unzippedWebapp = new File(appPath);
        handleExplodedWebappDeployment(unzippedWebapp, webContextParams, applicationEventListeners);
    }
}
Also used : CarbonException(org.wso2.carbon.CarbonException) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 5 with CarbonException

use of org.wso2.carbon.CarbonException in project jaggery by wso2.

the class TomcatJaggeryWebappsDeployer method handleWebappDeployment.

/**
 * Deployment procedure of Jaggery apps
 *
 * @param webappFile                The Jaggery app file to be deployed
 * @param contextStr                jaggery app context string
 * @param webContextParams          context-params for this Jaggery app
 * @param applicationEventListeners Application event listeners
 * @throws CarbonException If a deployment error occurs
 */
protected void handleWebappDeployment(File webappFile, String contextStr, List<WebContextParameter> webContextParams, List<Object> applicationEventListeners) throws CarbonException {
    String filename = webappFile.getName();
    ArrayList<Object> listeners = new ArrayList<Object>(1);
    // listeners.add(new CarbonServletRequestListener());
    SecurityConstraint securityConstraint = new SecurityConstraint();
    securityConstraint.setAuthConstraint(true);
    SecurityCollection securityCollection = new SecurityCollection();
    securityCollection.setName("ConfigDir");
    securityCollection.setDescription("Jaggery Configuration Dir");
    securityCollection.addPattern("/" + JaggeryCoreConstants.JAGGERY_CONF_FILE);
    securityConstraint.addCollection(securityCollection);
    WebApplicationsHolder webApplicationsHolder = WebAppUtils.getWebappHolder(webappFile.getAbsolutePath(), configurationContext);
    try {
        JSONObject jaggeryConfigObj = readJaggeryConfig(webappFile);
        Tomcat tomcat = DataHolder.getCarbonTomcatService().getTomcat();
        Context context = DataHolder.getCarbonTomcatService().addWebApp(contextStr, webappFile.getAbsolutePath(), new JaggeryDeployerManager.JaggeryConfListener(jaggeryConfigObj, securityConstraint));
        // deploying web app for url mapping inside virtual host
        if (DataHolder.getHotUpdateService() != null) {
            List<String> hostNames = DataHolder.getHotUpdateService().getMappigsPerWebapp(contextStr);
            for (String hostName : hostNames) {
                Host host = DataHolder.getHotUpdateService().addHost(hostName);
                /*                    ApplicationContext.getCurrentApplicationContext().putUrlMappingForApplication(hostName, contextStr);
  */
                Context contextForHost = DataHolder.getCarbonTomcatService().addWebApp(host, "/", webappFile.getAbsolutePath(), new JaggeryDeployerManager.JaggeryConfListener(jaggeryConfigObj, securityConstraint));
                log.info("Deployed JaggeryApp on host: " + contextForHost);
            }
        }
        Manager manager = context.getManager();
        if (isDistributable(context, jaggeryConfigObj)) {
            // Clusterable manager implementation as DeltaManager
            context.setDistributable(true);
            // Using clusterable manager
            CarbonTomcatClusterableSessionManager sessionManager;
            if (manager instanceof CarbonTomcatClusterableSessionManager) {
                sessionManager = (CarbonTomcatClusterableSessionManager) manager;
                sessionManager.setOwnerTenantId(tenantId);
            } else {
                sessionManager = new CarbonTomcatClusterableSessionManager(tenantId);
                context.setManager(sessionManager);
            }
            Object alreadyinsertedSMMap = configurationContext.getProperty(CarbonConstants.TOMCAT_SESSION_MANAGER_MAP);
            if (alreadyinsertedSMMap != null) {
                ((Map<String, CarbonTomcatClusterableSessionManager>) alreadyinsertedSMMap).put(context.getName(), sessionManager);
            } else {
                sessionManagerMap.put(context.getName(), sessionManager);
                configurationContext.setProperty(CarbonConstants.TOMCAT_SESSION_MANAGER_MAP, sessionManagerMap);
            }
        } else {
            if (manager instanceof CarbonTomcatSessionManager) {
                ((CarbonTomcatSessionManager) manager).setOwnerTenantId(tenantId);
            } else if (manager instanceof CarbonTomcatSessionPersistentManager) {
                ((CarbonTomcatSessionPersistentManager) manager).setOwnerTenantId(tenantId);
                log.debug(manager.getInfo() + " enabled Tomcat HTTP Session Persistent mode using " + ((CarbonTomcatSessionPersistentManager) manager).getStore().getInfo());
            } else {
                context.setManager(new CarbonTomcatSessionManager(tenantId));
            }
        }
        context.setReloadable(false);
        JaggeryApplication webapp = new JaggeryApplication(this, context, webappFile);
        webapp.setServletContextParameters(webContextParams);
        webapp.setState("Started");
        webApplicationsHolder.getStartedWebapps().put(filename, webapp);
        webApplicationsHolder.getFaultyWebapps().remove(filename);
        registerApplicationEventListeners(applicationEventListeners, context);
        log.info("Deployed webapp: " + webapp);
    } catch (Throwable e) {
        // catching a Throwable here to avoid web-apps crashing the server during startup
        StandardContext context = new StandardContext();
        context.setName(webappFile.getName());
        context.addParameter(WebappsConstants.FAULTY_WEBAPP, "true");
        JaggeryApplication webapp = new JaggeryApplication(this, context, webappFile);
        webapp.setProperty(WebappsConstants.WEBAPP_FILTER, JaggeryConstants.JAGGERY_WEBAPP_FILTER_PROP);
        String msg = "Error while deploying webapp: " + webapp;
        log.error(msg, e);
        webapp.setFaultReason(new Exception(msg, e));
        webApplicationsHolder.getFaultyWebapps().put(filename, webapp);
        webApplicationsHolder.getStartedWebapps().remove(filename);
        throw new CarbonException(msg, e);
    }
}
Also used : ConfigurationContext(org.apache.axis2.context.ConfigurationContext) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) Context(org.apache.catalina.Context) StandardContext(org.apache.catalina.core.StandardContext) Tomcat(org.apache.catalina.startup.Tomcat) JaggeryDeployerManager(org.jaggeryjs.jaggery.core.manager.JaggeryDeployerManager) ArrayList(java.util.ArrayList) CarbonException(org.wso2.carbon.CarbonException) Host(org.apache.catalina.Host) CarbonTomcatClusterableSessionManager(org.wso2.carbon.core.session.CarbonTomcatClusterableSessionManager) Manager(org.apache.catalina.Manager) JaggeryDeployerManager(org.jaggeryjs.jaggery.core.manager.JaggeryDeployerManager) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) CarbonException(org.wso2.carbon.CarbonException) JSONObject(org.json.simple.JSONObject) CarbonTomcatClusterableSessionManager(org.wso2.carbon.core.session.CarbonTomcatClusterableSessionManager) StandardContext(org.apache.catalina.core.StandardContext) JSONObject(org.json.simple.JSONObject) Map(java.util.Map) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection)

Aggregations

CarbonException (org.wso2.carbon.CarbonException)9 ArrayList (java.util.ArrayList)5 FileItemData (org.wso2.carbon.utils.FileItemData)4 IOException (java.io.IOException)3 DataHandler (javax.activation.DataHandler)3 DataSource (javax.activation.DataSource)3 FileDataSource (javax.activation.FileDataSource)3 File (java.io.File)2 PrintWriter (java.io.PrintWriter)2 ScriptException (org.jaggeryjs.scriptengine.exceptions.ScriptException)2 PrivilegedCarbonContext (org.wso2.carbon.context.PrivilegedCarbonContext)2 RegistryException (org.wso2.carbon.registry.api.RegistryException)2 ResourceData (org.wso2.carbon.registry.common.ResourceData)2 AdvancedSearchResultsBean (org.wso2.carbon.registry.search.beans.AdvancedSearchResultsBean)2 UserStoreException (org.wso2.carbon.user.core.UserStoreException)2 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)1 DateFormat (java.text.DateFormat)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Map (java.util.Map)1 ConfigurationContext (org.apache.axis2.context.ConfigurationContext)1