Search in sources :

Example 36 with Target

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.Target in project product-iots by wso2.

the class CarbonServerManagerExtension method setUpCarbonHome.

/**
 * Unzip carbon zip file and return the carbon home. Based on the coverage configuration in automation.xml
 * This method will inject jacoco agent to the carbon server startup scripts.
 *
 * @param carbonServerZipFile - Carbon zip file, which should be specified in test module pom
 * @return - carbonHome - carbon home
 * @throws IOException - If pack extraction fails
 */
public synchronized String setUpCarbonHome(String carbonServerZipFile) throws IOException, AutomationFrameworkException {
    if (this.process != null) {
        return this.carbonHome;
    } else {
        int indexOfZip = carbonServerZipFile.lastIndexOf(".zip");
        if (indexOfZip == -1) {
            throw new IllegalArgumentException(carbonServerZipFile + " is not a zip file");
        } else {
            String fileSeparator = File.separator.equals("\\") ? "\\" : "/";
            if (fileSeparator.equals("\\")) {
                carbonServerZipFile = carbonServerZipFile.replace("/", "\\");
            }
            String extractedCarbonDir = carbonServerZipFile.substring(carbonServerZipFile.lastIndexOf(fileSeparator) + 1, indexOfZip);
            FileManipulator.deleteDir(extractedCarbonDir);
            String extractDir = "carbontmp" + System.currentTimeMillis();
            String baseDir = System.getProperty("basedir", ".") + File.separator + "target";
            log.info("Extracting carbon zip file.. ");
            (new ArchiveExtractor()).extractFile(carbonServerZipFile, baseDir + File.separator + extractDir);
            this.carbonHome = (new File(baseDir)).getAbsolutePath() + File.separator + extractDir + File.separator + extractedCarbonDir;
            try {
                this.isCoverageEnable = Boolean.parseBoolean(this.automationContext.getConfigurationValue("//coverage"));
            } catch (XPathExpressionException var8) {
                throw new AutomationFrameworkException("Coverage configuration not found in automation.xml", var8);
            }
            if (this.isCoverageEnable) {
                this.instrumentForCoverage();
            }
            return this.carbonHome;
        }
    }
}
Also used : AutomationFrameworkException(org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException) XPathExpressionException(javax.xml.xpath.XPathExpressionException) ArchiveExtractor(org.wso2.carbon.automation.extensions.servers.utils.ArchiveExtractor) File(java.io.File)

Example 37 with Target

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.Target in project carbon-apimgt by wso2.

the class APIProviderImpl method sendLCStateChangeNotification.

/**
 * @param apiName           Name of the API
 * @param apiType           API Type
 * @param apiContext        API or Product context
 * @param apiVersion        API or Product version
 * @param targetStatus      Target Lifecycle status
 * @param provider          Provider of the API or Product
 * @param apiOrApiProductId unique ID of API or API product
 * @param uuid              unique UUID of API or API Product
 */
private void sendLCStateChangeNotification(String apiName, String apiType, String apiContext, String apiVersion, String targetStatus, String provider, int apiOrApiProductId, String uuid) {
    APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_LIFECYCLE_CHANGE.name(), tenantId, tenantDomain, apiName, apiOrApiProductId, uuid, apiVersion, apiType, apiContext, APIUtil.replaceEmailDomainBack(provider), targetStatus);
    APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
}
Also used : APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent)

Example 38 with Target

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.Target in project carbon-apimgt by wso2.

the class CommonUtil method extractArchive.

/**
 * This method decompresses API the archive.
 *
 * @param sourceFile  The archive containing the API
 * @param destination location of the archive to be extracted
 * @return Name of the extracted directory
 * @throws APIImportExportException If the decompressing fails
 */
public static String extractArchive(File sourceFile, String destination) throws APIImportExportException {
    String archiveName = null;
    try (ZipFile zip = new ZipFile(sourceFile)) {
        Enumeration zipFileEntries = zip.entries();
        int index = 0;
        // Process each entry
        while (zipFileEntries.hasMoreElements()) {
            // grab a zip file entry
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();
            // This index variable is used to get the extracted folder name; that is root directory
            if (index == 0) {
                archiveName = currentEntry.substring(0, currentEntry.indexOf(ImportExportConstants.ZIP_FILE_SEPARATOR));
                --index;
            }
            File destinationFile = new File(destination, currentEntry);
            File destinationParent = destinationFile.getParentFile();
            String canonicalizedDestinationFilePath = destinationFile.getCanonicalPath();
            if (!canonicalizedDestinationFilePath.startsWith(new File(destination).getCanonicalPath())) {
                String errorMessage = "Attempt to upload invalid zip archive with file at " + currentEntry + ". File path is outside target directory";
                throw new APIImportExportException(errorMessage);
            }
            // create the parent directory structure
            if (destinationParent.mkdirs()) {
                log.info("Creation of folder is successful. Directory Name : " + destinationParent.getName());
            }
            if (!entry.isDirectory()) {
                // write the current file to the destination
                try (InputStream zipInputStream = zip.getInputStream(entry);
                    BufferedInputStream inputStream = new BufferedInputStream(zipInputStream);
                    FileOutputStream outputStream = new FileOutputStream(destinationFile)) {
                    IOUtils.copy(inputStream, outputStream);
                }
            }
        }
        return archiveName;
    } catch (IOException e) {
        String errorMessage = "Failed to extract the archive (zip) file. ";
        throw new APIImportExportException(errorMessage, e);
    }
}
Also used : Enumeration(java.util.Enumeration) ZipFile(java.util.zip.ZipFile) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ZipEntry(java.util.zip.ZipEntry) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) ZipFile(java.util.zip.ZipFile) File(java.io.File)

Example 39 with Target

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.Target in project carbon-apimgt by wso2.

the class SuccessRequestDataCollector method collectData.

public void collectData() throws AnalyticsException {
    log.debug("Handling success analytics types");
    long requestInTime = provider.getRequestTime();
    String offsetDateTime = getTimeInISO(requestInTime);
    Event event = new Event();
    API api = provider.getApi();
    Operation operation = provider.getOperation();
    Target target = provider.getTarget();
    Application application;
    if (provider.isAnonymous()) {
        application = getAnonymousApp();
    } else {
        application = provider.getApplication();
    }
    Latencies latencies = provider.getLatencies();
    MetaInfo metaInfo = provider.getMetaInfo();
    String userAgent = provider.getUserAgentHeader();
    String userIp = provider.getEndUserIP();
    if (userIp == null) {
        userIp = Constants.UNKNOWN_VALUE;
    }
    event.setApi(api);
    event.setOperation(operation);
    event.setTarget(target);
    event.setApplication(application);
    event.setLatencies(latencies);
    event.setProxyResponseCode(provider.getProxyResponseCode());
    event.setRequestTimestamp(offsetDateTime);
    event.setMetaInfo(metaInfo);
    event.setUserAgentHeader(userAgent);
    event.setUserIp(userIp);
    this.processor.publish(event);
}
Also used : Target(org.wso2.carbon.apimgt.common.analytics.publishers.dto.Target) Latencies(org.wso2.carbon.apimgt.common.analytics.publishers.dto.Latencies) MetaInfo(org.wso2.carbon.apimgt.common.analytics.publishers.dto.MetaInfo) Event(org.wso2.carbon.apimgt.common.analytics.publishers.dto.Event) API(org.wso2.carbon.apimgt.common.analytics.publishers.dto.API) Operation(org.wso2.carbon.apimgt.common.analytics.publishers.dto.Operation) Application(org.wso2.carbon.apimgt.common.analytics.publishers.dto.Application)

Example 40 with Target

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.Target in project carbon-apimgt by wso2.

the class APIFileUtil method extractArchive.

/**
 * Extracts a a given zip archive
 *
 * @param archiveFilePath path of the zip archive
 * @param destination     extract location
 * @return name of the extracted zip archive
 * @throws APIManagementException if an error occurs while extracting the archive
 */
public static String extractArchive(String archiveFilePath, String destination) throws APIManagementException {
    int bufferSize = 512;
    // Max size of unzipped data, 100MB
    long sizeLimit = 0x6400000;
    int maxEntryCount = 1024;
    String archiveName = null;
    try {
        FileInputStream fis = new FileInputStream(archiveFilePath);
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
        ZipEntry entry;
        int entries = 0;
        long total = 0;
        // Process each entry
        while ((entry = zis.getNextEntry()) != null) {
            String currentEntry = entry.getName();
            int index = 0;
            // This index variable is used to get the extracted folder name; that is root directory
            if (index == 0 && currentEntry.indexOf('/') != -1) {
                archiveName = currentEntry.substring(0, currentEntry.indexOf('/'));
                --index;
            }
            File destinationFile = new File(destination, currentEntry);
            File destinationParent = destinationFile.getParentFile();
            String canonicalizedDestinationFilePath = destinationFile.getCanonicalPath();
            if (!canonicalizedDestinationFilePath.startsWith(new File(destination).getCanonicalPath())) {
                String errorMessage = "Attempt to upload invalid zip archive with file at " + currentEntry + ". File path is outside target directory";
                log.error(errorMessage);
                throw new APIManagementException(errorMessage);
            }
            if (entry.isDirectory()) {
                log.debug("Creating directory " + destinationFile.getAbsolutePath());
                destinationFile.mkdir();
                continue;
            }
            // create the parent directory structure
            if (destinationParent.mkdirs()) {
                log.debug("Creation of folder is successful. Directory Name : " + destinationParent.getName());
            }
            int count;
            byte[] data = new byte[bufferSize];
            FileOutputStream fos = new FileOutputStream(destinationFile);
            BufferedOutputStream dest = new BufferedOutputStream(fos, bufferSize);
            while (total + bufferSize <= sizeLimit && (count = zis.read(data, 0, bufferSize)) != -1) {
                dest.write(data, 0, count);
                total += count;
            }
            dest.flush();
            dest.close();
            zis.closeEntry();
            entries++;
            if (entries > maxEntryCount) {
                throw new APIManagementException("Too many files to unzip.");
            }
            if (total + bufferSize > sizeLimit) {
                throw new APIManagementException("File being unzipped is too big.");
            }
        }
        return archiveName;
    } catch (IOException e) {
        String errorMsg = "Failed to extract archive file: " + archiveFilePath + " to destination: " + destination;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e);
    }
}
Also used : ZipEntry(java.util.zip.ZipEntry) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) ZipInputStream(java.util.zip.ZipInputStream) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) BufferedInputStream(java.io.BufferedInputStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File) ZipFile(java.util.zip.ZipFile) BufferedOutputStream(java.io.BufferedOutputStream)

Aggregations

BLangAssignment (org.wso2.ballerinalang.compiler.tree.statements.BLangAssignment)11 DiagnosticPos (org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos)11 ArrayList (java.util.ArrayList)9 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)8 File (java.io.File)7 IOException (java.io.IOException)7 Element (org.w3c.dom.Element)6 BLangBinaryExpr (org.wso2.ballerinalang.compiler.tree.expressions.BLangBinaryExpr)5 Target (org.wso2.carbon.apimgt.common.analytics.publishers.dto.Target)5 Gson (com.google.gson.Gson)4 List (java.util.List)4 Map (java.util.Map)4 OMElement (org.apache.axiom.om.OMElement)4 NodeList (org.w3c.dom.NodeList)4 BLangIndexBasedAccess (org.wso2.ballerinalang.compiler.tree.expressions.BLangIndexBasedAccess)4 JsonElement (com.google.gson.JsonElement)3 FileOutputStream (java.io.FileOutputStream)3 HashMap (java.util.HashMap)3 Iterator (java.util.Iterator)3 Set (java.util.Set)3