Search in sources :

Example 16 with Extension

use of org.wso2.siddhi.annotation.Extension in project charon by wso2.

the class AbstractSCIMObject method deleteSubSubAttribute.

/*
     * This deletion method is only applicable for extension schema
     * Deleting a sub attribute of complex attribute is the responsibility of an attribute holder.
     *
     * @param grandParentAttribute
     * @param parentAttribute
     * @param childAttribute
     */
public void deleteSubSubAttribute(String childAttribute, String parentAttribute, String grandParentAttribute) throws CharonException {
    if (attributeList.containsKey(grandParentAttribute)) {
        ComplexAttribute grandParent = (ComplexAttribute) attributeList.get(grandParentAttribute);
        Attribute parent = ((ComplexAttribute) grandParent).getSubAttribute(parentAttribute);
        ((ComplexAttribute) (parent)).removeSubAttribute(childAttribute);
    }
}
Also used : MultiValuedAttribute(org.wso2.charon3.core.attributes.MultiValuedAttribute) ComplexAttribute(org.wso2.charon3.core.attributes.ComplexAttribute) Attribute(org.wso2.charon3.core.attributes.Attribute) SimpleAttribute(org.wso2.charon3.core.attributes.SimpleAttribute) ComplexAttribute(org.wso2.charon3.core.attributes.ComplexAttribute)

Example 17 with Extension

use of org.wso2.siddhi.annotation.Extension 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 18 with Extension

use of org.wso2.siddhi.annotation.Extension 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 19 with Extension

use of org.wso2.siddhi.annotation.Extension in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method apisImportDefinitionPost.

/**
 * Import an API from a Swagger or WSDL
 *
 * @param type                 definition type. If not specified, default will be SWAGGER
 * @param fileInputStream      file content stream, can be either archive or a single text file
 * @param fileDetail           file details
 * @param url                  URL of the definition
 * @param additionalProperties Additional attributes specified as a stringified JSON with API's schema
 * @param ifMatch              If-Match header value
 * @param ifUnmodifiedSince    If-Unmodified-Since header value
 * @param implementationType   WSDL based API implementation type (SOAP or HTTP_BINDING)
 * @param request              msf4j request object
 * @return Imported API
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response apisImportDefinitionPost(String type, InputStream fileInputStream, FileInfo fileDetail, String url, String additionalProperties, String implementationType, String ifMatch, String ifUnmodifiedSince, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        if (StringUtils.isBlank(type)) {
            type = APIDefinitionValidationResponseDTO.DefinitionTypeEnum.SWAGGER.toString();
        }
        Response response = buildResponseIfParamsInvalid(type, fileInputStream, url);
        if (response != null) {
            return response;
        }
        API.APIBuilder apiBuilder = null;
        APIDTO additionalPropertiesAPI = null;
        if (!StringUtils.isBlank(additionalProperties)) {
            if (log.isDebugEnabled()) {
                log.debug("Deseriallizing additionalProperties: " + additionalProperties);
            }
            ObjectMapper mapper = new ObjectMapper();
            additionalPropertiesAPI = mapper.readValue(additionalProperties, APIDTO.class);
            apiBuilder = MappingUtil.toAPI(additionalPropertiesAPI);
            if (log.isDebugEnabled()) {
                log.debug("Successfully deseriallized additionalProperties: " + additionalProperties);
            }
        }
        APIPublisher apiPublisher = RestAPIPublisherUtil.getApiPublisher(username);
        String uuid = "";
        if (APIDefinitionValidationResponseDTO.DefinitionTypeEnum.SWAGGER.toString().equals(type)) {
            if (log.isDebugEnabled()) {
                log.debug("Adding an API by importing a swagger.");
            }
            if (fileInputStream != null) {
                uuid = apiPublisher.addApiFromDefinition(fileInputStream);
            } else {
                URL swaggerUrl = new URL(url);
                HttpURLConnection urlConn = (HttpURLConnection) swaggerUrl.openConnection();
                uuid = apiPublisher.addApiFromDefinition(urlConn);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Adding an API by importing a WSDL.");
            }
            // context, version when creating an API from WSDL
            if (additionalPropertiesAPI != null) {
                final String soap = RestApiConstants.IMPORT_DEFINITION_WSDL_IMPL_TYPE_SOAP;
                final String httpBinding = RestApiConstants.IMPORT_DEFINITION_WSDL_IMPL_TYPE_HTTP;
                if (implementationType != null && !soap.equals(implementationType) && !httpBinding.equals(implementationType)) {
                    String msg = "Invalid implementation type. Should be one of '" + soap + "' or '" + httpBinding + "'";
                    log.error(msg);
                    ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900700L, msg);
                    return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
                }
                boolean isHttpBinding = httpBinding.equals(implementationType);
                if (fileInputStream != null) {
                    if (fileDetail.getFileName() == null) {
                        String msg = "File name cannot be null.";
                        log.error(msg);
                        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900700L, msg);
                        return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
                    }
                    if (fileDetail.getFileName().endsWith(".zip")) {
                        uuid = apiPublisher.addAPIFromWSDLArchive(apiBuilder, fileInputStream, isHttpBinding);
                        if (log.isDebugEnabled()) {
                            log.debug("Successfully added API with WSDL archive " + fileDetail.getFileName());
                        }
                    } else if (fileDetail.getFileName().endsWith(".wsdl")) {
                        uuid = apiPublisher.addAPIFromWSDLFile(apiBuilder, fileInputStream, isHttpBinding);
                        if (log.isDebugEnabled()) {
                            log.debug("Successfully added API with WSDL file " + fileDetail.getFileName());
                        }
                    } else {
                        String msg = "Unsupported extension type of file: " + fileDetail.getFileName();
                        log.error(msg);
                        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900700L, msg);
                        return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
                    }
                } else {
                    uuid = apiPublisher.addAPIFromWSDLURL(apiBuilder, url, isHttpBinding);
                    if (log.isDebugEnabled()) {
                        log.debug("Successfully added API with WSDL URL " + url);
                    }
                }
            } else {
                String msg = "'additionalProperties' should be specified when creating an API from WSDL";
                log.error(msg);
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900700L, msg);
                return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
            }
        }
        API returnAPI = apiPublisher.getAPIbyUUID(uuid);
        return Response.status(Response.Status.CREATED).entity(MappingUtil.toAPIDto(returnAPI)).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding new API";
        HashMap<String, String> paramList = new HashMap<String, String>();
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    } catch (IOException e) {
        String errorMessage = "Error while adding new API";
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorMessage, 900313L, errorMessage);
        log.error(errorMessage, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorDTO).build();
    }
}
Also used : HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) IOException(java.io.IOException) URL(java.net.URL) WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) Response(javax.ws.rs.core.Response) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO) HttpURLConnection(java.net.HttpURLConnection) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) API(org.wso2.carbon.apimgt.core.models.API) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 20 with Extension

use of org.wso2.siddhi.annotation.Extension in project siddhi by wso2.

the class DocumentationUtils method updateHeadingsInMarkdownFile.

/**
 * Update the documentation home page
 *
 * @param inputFile                  The path to the input file
 * @param outputFile                 The path to the output file
 * @param extensionRepositoryName    The name of  the extension repository
 * @param latestDocumentationVersion The version of the latest documentation generated
 * @param namespaceMetaDataList      Metadata in this repository
 * @throws MojoFailureException if the Mojo fails to find template file or create new documentation file
 */
public static void updateHeadingsInMarkdownFile(File inputFile, File outputFile, String extensionRepositoryName, String latestDocumentationVersion, List<NamespaceMetaData> namespaceMetaDataList) throws MojoFailureException {
    // Retrieving the content of the README.md file
    List<String> inputFileLines = new ArrayList<>();
    try {
        inputFileLines = Files.readLines(inputFile, Constants.DEFAULT_CHARSET);
    } catch (IOException ignored) {
    }
    // Generating data model
    Map<String, Object> rootDataModel = new HashMap<>();
    rootDataModel.put("inputFileLines", inputFileLines);
    rootDataModel.put("extensionRepositoryName", extensionRepositoryName);
    rootDataModel.put("latestDocumentationVersion", latestDocumentationVersion);
    rootDataModel.put("metaData", namespaceMetaDataList);
    rootDataModel.put("formatDescription", new FormatDescriptionMethod());
    generateFileFromTemplate(Constants.MARKDOWN_HEADINGS_UPDATE_TEMPLATE + Constants.MARKDOWN_FILE_EXTENSION + Constants.FREEMARKER_TEMPLATE_FILE_EXTENSION, rootDataModel, outputFile.getParent(), outputFile.getName());
}
Also used : HashMap(java.util.HashMap) FormatDescriptionMethod(org.wso2.siddhi.doc.gen.core.freemarker.FormatDescriptionMethod) ArrayList(java.util.ArrayList) IOException(java.io.IOException)

Aggregations

ArrayList (java.util.ArrayList)12 Attribute (org.wso2.charon3.core.attributes.Attribute)10 ComplexAttribute (org.wso2.charon3.core.attributes.ComplexAttribute)10 MultiValuedAttribute (org.wso2.charon3.core.attributes.MultiValuedAttribute)10 SimpleAttribute (org.wso2.charon3.core.attributes.SimpleAttribute)10 SiddhiAppCreationException (org.wso2.siddhi.core.exception.SiddhiAppCreationException)7 Extension (org.wso2.siddhi.query.api.extension.Extension)7 IOException (java.io.IOException)6 HashMap (java.util.HashMap)6 List (java.util.List)6 BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)6 ConfigReader (org.wso2.siddhi.core.util.config.ConfigReader)6 Test (org.testng.annotations.Test)5 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)5 SiddhiManager (org.wso2.siddhi.core.SiddhiManager)5 Event (org.wso2.siddhi.core.event.Event)5 StringConcatAggregatorString (org.wso2.siddhi.core.query.extension.util.StringConcatAggregatorString)5 QueryCallback (org.wso2.siddhi.core.query.output.callback.QueryCallback)5 InputHandler (org.wso2.siddhi.core.stream.input.InputHandler)5 Map (java.util.Map)4