Example usage for java.util.zip ZipInputStream close

List of usage examples for java.util.zip ZipInputStream close

Introduction

In this page you can find the example usage for java.util.zip ZipInputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:com.visural.stereotyped.ui.service.StereotypeServiceImpl.java

public ComponentLibrary readComponentLibrary(String name) {
    File jar = new File(getComponentJarsPath() + "/" + name);
    if (jar.exists()) {
        ZipInputStream zis = null;
        try {//  w  w w  .  j a  v a 2  s.  c  o  m
            ComponentLibrary cl = new ComponentLibrary(jar.getName(), new HashSet(), new HashMap());
            File ovrDir = getOverrideLibPath(cl);
            zis = new ZipInputStream(new FileInputStream(jar));
            ZipEntry ze;
            while ((ze = zis.getNextEntry()) != null) {
                if (!ze.isDirectory()) {
                    if (!ze.getName().endsWith(".class")) {
                        // check for override first
                        File ovr = new File(ovrDir.getCanonicalPath() + "/" + ze.getName());
                        if (ovr.exists()) {
                            byte[] data = IOUtil.fileToByteArray(ovr.getCanonicalPath());
                            cl.getTemplate().put(ze.getName(), new Binary(data, true));
                        } else {
                            // no override, read from JAR
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            int r;
                            while ((r = zis.read()) != -1) {
                                baos.write(r);
                            }
                            cl.getTemplate().put(ze.getName(), new Binary(baos.toByteArray()));
                        }
                    } else {
                        Class c = getComponentClassWithName(ze.getName()
                                .substring(0, ze.getName().lastIndexOf(".class")).replace("/", "."));
                        if (c != null) {
                            cl.getComponents().add(c);
                        }
                    }
                }
            }
            addOverrideFiles(ovrDir.getAbsolutePath(), cl, ovrDir);
            return cl;
        } catch (IOException e) {
            throw new IllegalStateException(e);
        } finally {
            if (zis != null) {
                try {
                    zis.close();
                } catch (IOException ex) {
                    Logger.getLogger(StereotypeServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    } else {
        throw new IllegalArgumentException("Library " + name + " does not exist.");
    }
}

From source file:com.ibm.mf.geofence.MFGeofencingManager.java

/**
 * Load a set of geofences from a reosurce file.
 * @param resource the path to the resource to load the geofences from.
 *///from ww  w  .j  a  va 2s  . c  o  m
public void loadGeofencesFromResource(final String resource) {
    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        private GeofenceList geofenceList;
        private HttpRequestError error;

        @Override
        protected Void doInBackground(Void... params) {
            ZipInputStream zis = null;
            try {
                InputStream is = getClass().getClassLoader().getResourceAsStream(resource);
                zis = new ZipInputStream(is);
                ZipEntry entry;
                Map<String, PersistentGeofence> allGeofences = new HashMap<>();
                while ((entry = zis.getNextEntry()) != null) {
                    byte[] bytes = GeofencingUtils.loadBytes(zis);
                    if (bytes != null) {
                        int fileSize = bytes.length;
                        JSONObject json = new JSONObject(new String(bytes, "UTF-8"));
                        bytes = null; // the byte[] may be large, we make sure it can be GC-ed ASAP
                        GeofenceList list = GeofencingJSONUtils.parseGeofences(json);
                        List<PersistentGeofence> geofences = list.getGeofences();
                        if ((geofences != null) && !geofences.isEmpty()) {
                            PersistentGeofence.saveInTx(geofences);
                            log.debug(String.format(Locale.US,
                                    "loaded %,d geofences from resource '[%s]/%s' (%,d bytes)",
                                    geofences.size(), resource, entry.getName(), fileSize));
                        }

                        for (PersistentGeofence pg : list.getGeofences()) {
                            allGeofences.put(pg.getCode(), pg);
                        }
                    } else {
                        log.debug(String.format("the zip entry [%s]/%s is empty", resource, entry.getName()));
                    }
                }
                geofenceList = new GeofenceList(new ArrayList<>(allGeofences.values()));
                log.debug(String.format(Locale.US, "loaded %,d geofences from resource '[%s]'",
                        allGeofences.size(), resource));
            } catch (Exception e) {
                error = new HttpRequestError(-1, e, String.format("error loading resource '%s'", resource));
            } finally {
                try {
                    zis.close();
                } catch (Exception e) {
                    log.error(String.format("error closing zip input stream for resource %s", resource), e);
                    if (error == null) {
                        error = new HttpRequestError(-1, e,
                                String.format("error loading resource '%s'", resource));
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if (error != null) {
                log.error(String.format("error loading resource %s : %s", resource, error));
            } else {
                try {
                    Intent broadcastIntent = new Intent(MFGeofenceEvent.ACTION_GEOFENCE_EVENT);
                    broadcastIntent.setPackage(mContext.getPackageName());
                    MFGeofenceEvent.toIntent(broadcastIntent, MFGeofenceEvent.Type.SERVER_SYNC,
                            geofenceList.getGeofences(), null);
                    mContext.sendBroadcast(broadcastIntent);
                } catch (Exception e) {
                    log.error("error sending broadcast event", e);
                }
            }
        }
    };
    task.execute();
}

From source file:com.permeance.utility.scriptinghelper.portlets.ScriptingHelperPortlet.java

public void execute(ActionRequest actionRequest, ActionResponse actionResponse) {
    try {//from   w  w w  . j a  va2s. co m
        sCheckPermissions(actionRequest);

        String portletId = "_" + PortalUtil.getPortletId(actionRequest) + "_";

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(100 * 1024 * 1024);
        PortletFileUpload upload = new PortletFileUpload(factory);

        FileItem fileUploaded = null;
        List<FileItem> items = upload.parseRequest(actionRequest);
        for (FileItem fi : items) {
            if (fi.isFormField()) {
                actionRequest.setAttribute(fi.getFieldName(), fi.getString());
                if (fi.getFieldName().startsWith(portletId)) {
                    actionRequest.setAttribute(fi.getFieldName().substring(portletId.length()), fi.getString());
                }
            } else {
                fileUploaded = fi;
            }
        }

        String cmd = (String) actionRequest.getAttribute("cmd");
        String language = (String) actionRequest.getAttribute("language");
        String script = (String) actionRequest.getAttribute("script");
        String editorheight = (String) actionRequest.getAttribute("editorheight");
        String themesel = (String) actionRequest.getAttribute("themesel");
        if (language == null) {
            language = getDefaultLanguage();
        }
        if (script == null) {
            script = StringPool.BLANK;
        }
        actionResponse.setRenderParameter("language", language);
        actionResponse.setRenderParameter("script", script);
        actionResponse.setRenderParameter("editorheight", editorheight);
        actionResponse.setRenderParameter("themesel", themesel);

        if ("execute".equals(cmd)) {

            Map<String, Object> portletObjects = ScriptingHelperUtil.getPortletObjects(getPortletConfig(),
                    getPortletContext(), actionRequest, actionResponse);

            UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

            UnsyncPrintWriter unsyncPrintWriter = UnsyncPrintWriterPool.borrow(unsyncByteArrayOutputStream);

            portletObjects.put("out", unsyncPrintWriter);

            _log.info("Executing script");
            ScriptingUtil.exec(null, portletObjects, language, script, StringPool.EMPTY_ARRAY);
            unsyncPrintWriter.flush();
            actionResponse.setRenderParameter("script_output", unsyncByteArrayOutputStream.toString());
        } else if ("save".equals(cmd)) {
            String newscriptname = (String) actionRequest.getAttribute("newscriptname");
            if (newscriptname == null || newscriptname.trim().length() == 0) {
                actionResponse.setRenderParameter("script_trace", "No script name specified to save into!");
                SessionErrors.add(actionRequest, "error");
                return;
            }

            _log.info("Saving new script: " + newscriptname.trim());
            PortletPreferences prefs = actionRequest.getPreferences();
            prefs.setValue("savedscript." + newscriptname.trim(), script);
            prefs.setValue("lang." + newscriptname.trim(), language);
            prefs.store();
        } else if ("saveinto".equals(cmd)) {
            String scriptname = (String) actionRequest.getAttribute("savedscript");
            if (scriptname == null) {
                actionResponse.setRenderParameter("script_trace", "No script specified to save into!");
                SessionErrors.add(actionRequest, "error");
                return;
            }

            _log.info("Saving saved script: " + scriptname);
            PortletPreferences prefs = actionRequest.getPreferences();
            prefs.setValue("savedscript." + scriptname, script);
            prefs.setValue("lang." + scriptname, language);
            prefs.store();
        } else if ("loadfrom".equals(cmd)) {
            String scriptname = (String) actionRequest.getAttribute("savedscript");
            if (scriptname == null) {
                actionResponse.setRenderParameter("script_trace", "No script specified to load from!");
                SessionErrors.add(actionRequest, "error");
                return;
            }
            _log.info("Loading saved script: " + scriptname);
            PortletPreferences prefs = actionRequest.getPreferences();
            language = prefs.getValue("lang." + scriptname, getDefaultLanguage());
            script = prefs.getValue("savedscript." + scriptname, StringPool.BLANK);
            actionResponse.setRenderParameter("language", language);
            actionResponse.setRenderParameter("script", script);
        } else if ("delete".equals(cmd)) {
            String scriptname = (String) actionRequest.getAttribute("savedscript");
            if (scriptname == null) {
                actionResponse.setRenderParameter("script_trace", "No script specified to delete!");
                SessionErrors.add(actionRequest, "error");
                return;
            }
            _log.info("Deleting saved script: " + scriptname);
            PortletPreferences prefs = actionRequest.getPreferences();
            prefs.reset("savedscript." + scriptname);
            prefs.reset("lang." + scriptname);
            prefs.store();
        } else if ("import".equals(cmd)) {
            if (fileUploaded == null) {
                actionResponse.setRenderParameter("script_trace", "No file was uploaded for import!");
                SessionErrors.add(actionRequest, "error");
                return;
            }

            StringBuilder output = new StringBuilder();

            InputStream instream = fileUploaded.getInputStream();
            ZipInputStream zipstream = null;
            try {
                zipstream = new ZipInputStream(instream);
                ZipEntry entry = zipstream.getNextEntry();
                while (entry != null) {
                    String filename = entry.getName();
                    if (filename.contains("/")) {
                        int qs = filename.lastIndexOf("/");
                        if (qs != -1) {
                            filename = filename.substring(qs + 1);
                        }
                    }
                    if (filename.contains("\\")) {
                        int qs = filename.lastIndexOf("\\");
                        if (qs != -1) {
                            filename = filename.substring(qs + 1);
                        }
                    }

                    String ext = StringPool.BLANK;
                    if (filename.length() > 0) {
                        int qs = filename.lastIndexOf(".");
                        if (qs > 0) {
                            ext = filename.substring(qs + 1);
                            filename = filename.substring(0, qs);
                        }
                    }

                    String lang = resolveLanguage(ext);
                    String imscript = getStreamAsString(zipstream, "utf-8", false);

                    if (imscript != null && imscript.length() > 0) {
                        _log.info("Importing script \"" + filename + "\" of type " + lang);
                        output.append("Importing script \"" + filename + "\" of type " + lang + "\n");

                        PortletPreferences prefs = actionRequest.getPreferences();
                        prefs.setValue("savedscript." + filename, imscript);
                        prefs.setValue("lang." + filename, lang);
                        prefs.store();
                    }

                    entry = zipstream.getNextEntry();
                }

                actionResponse.setRenderParameter("script_output", output.toString());
            } finally {
                try {
                    if (zipstream != null) {
                        zipstream.close();
                    }
                } catch (Exception e) {
                }
                try {
                    if (instream != null) {
                        instream.close();
                    }
                } catch (Exception e) {
                }
            }

            _log.info(fileUploaded.getName());
        }
        SessionMessages.add(actionRequest, "success");
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        pw.close();
        actionResponse.setRenderParameter("script_trace", sw.toString());
        _log.error(e);
        SessionErrors.add(actionRequest, e.toString());
    }
}

From source file:com.seer.datacruncher.services.ServiceScheduledJob.java

@Override
protected synchronized void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
    long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId");
    JobsEntity jobEntity = jobsDao.find(jobId);
    if (!jobEntity.isWorking()) {

        if (jobsDao.setWorkStatus(jobId, true)) {
            try {
                long eventTriggerId = arg0.getJobDetail().getJobDataMap().getString("eventTriggerId") == null
                        ? -1l//from w ww  . j  a  v a2s.co m
                        : Long.parseLong(arg0.getJobDetail().getJobDataMap().getString("eventTriggerId"));
                if (eventTriggerId > 0) {
                    EventTriggerEntity entity = eventTriggerDao.findEventTriggerById(eventTriggerId);
                    String className = entity.getName();
                    try {
                        String sourceCode = entity.getCode();
                        EventTrigger eventTrigger;
                        String response;
                        eventTrigger = (EventTrigger) CommonUtils.getClassInstance(className,
                                "com.seer.datacruncher.eventtrigger.EventTrigger", EventTrigger.class,
                                sourceCode);
                        assert eventTrigger != null;
                        response = eventTrigger.trigger();
                        log.info("Response From EventTrigger(" + className + ") :" + response);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("EventTrigger(" + className + ") :" + e.getMessage(), e);
                        logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + e.getMessage());
                    } catch (NoClassDefFoundError err) {
                        log.error("EventTrigger(" + className + ") :" + err.getMessage(), err);
                        logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + err.getMessage());
                    }
                    return;
                }

                int day = arg0.getJobDetail().getJobDataMap().getString("day") == null ? -1
                        : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("day"));
                int month = arg0.getJobDetail().getJobDataMap().getString("month") == null ? -1
                        : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("month"));
                if ((day > 0 && day != Calendar.getInstance().get(Calendar.DAY_OF_MONTH))
                        || (month > 0 && month != (Calendar.getInstance().get(Calendar.MONTH) + 1))) {
                    return;
                }
                StandardFileSystemManager fsManager = new StandardFileSystemManager();
                boolean isDataStream = true;
                try {
                    fsManager.init();
                    long schemaId = arg0.getJobDetail().getJobDataMap().getLong("schemaId");
                    long schedulerId = arg0.getJobDetail().getJobDataMap().getLong("schedulerId");
                    //long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId");
                    long connectionId = arg0.getJobDetail().getJobDataMap().getLong("connectionId");

                    String datastream = "";
                    int idSchemaType = schemasDao.find(schemaId).getIdSchemaType();

                    TasksEntity taskEntity = tasksDao.find(schedulerId);
                    //JobsEntity jobEntity = jobsDao.find(jobId);
                    if (taskEntity.getIsOneShoot()) {
                        jobEntity.setIsActive(0);
                        jobsDao.update(jobEntity);
                    }
                    if (idSchemaType == SchemaType.GENERATION) {
                        StreamGenerationUtils sgu = new StreamGenerationUtils();
                        datastream = sgu.getStream(schemaId);

                        log.debug("Content stream: " + schemaId);

                        if (datastream.trim().length() > 0) {
                            log.debug("Datastream to validate: " + datastream);
                            DatastreamsInput datastreamsInput = new DatastreamsInput();
                            String result = datastreamsInput.datastreamsInput(datastream, schemaId, null);
                            log.debug("Validation result: " + result);
                        } else {
                            isDataStream = false;
                            log.debug("No datastream create");
                        }
                    }
                    if (connectionId != 0) {
                        int serviceId = Integer
                                .parseInt(arg0.getJobDetail().getJobDataMap().getString("serviceId"));

                        String hostName = arg0.getJobDetail().getJobDataMap().getString("ftpServerIp");
                        String port = arg0.getJobDetail().getJobDataMap().getString("port");
                        String userName = arg0.getJobDetail().getJobDataMap().getString("userName");
                        String password = arg0.getJobDetail().getJobDataMap().getString("password");
                        String inputDirectory = arg0.getJobDetail().getJobDataMap().getString("inputDirectory");
                        String fileName = arg0.getJobDetail().getJobDataMap().getString("fileName");

                        ConnectionsEntity conn;

                        conn = connectionsDao.find(connectionId);

                        if (inputDirectory == null || inputDirectory.trim().length() == 0) {
                            inputDirectory = fileName;
                        } else if (!(conn.getIdConnType() == GenericType.uploadTypeConn
                                && serviceId == Servers.HTTP.getDbCode())) {
                            inputDirectory = inputDirectory + "/" + fileName;
                        }

                        log.info("(jobId:" + jobEntity.getName() + ") - Trying to Server polling at server ["
                                + hostName + ":" + port + "] with user[" + userName + "].");
                        String url = "";
                        if (serviceId == Servers.SAMBA.getDbCode()) {
                            if (!fsManager.hasProvider("smb")) {
                                fsManager.addProvider("smb", new SmbFileProvider());
                            }
                            url = "smb://" + userName + ":" + password + "@" + hostName + ":" + port + "/"
                                    + inputDirectory;
                        } else if (serviceId == Servers.HTTP.getDbCode()) {
                            if (!fsManager.hasProvider("http")) {
                                fsManager.addProvider("http", new HttpFileProvider());
                            }
                            url = "http://" + hostName + ":" + port + "/" + inputDirectory;
                        } else if (serviceId == Servers.FTP.getDbCode()) {
                            if (!fsManager.hasProvider("ftp")) {
                                fsManager.addProvider("ftp", new FtpFileProvider());
                            }
                            url = "ftp://" + userName + ":" + password + "@" + hostName + ":" + port + "/"
                                    + inputDirectory;
                        }
                        log.info("url:" + url);
                        final FileObject fileObject = fsManager.resolveFile(url);

                        if (conn.getIdConnType() == GenericType.DownloadTypeConn) {

                            if (conn.getFileDateTime() != null && conn.getFileDateTime().getTime() == fileObject
                                    .getContent().getLastModifiedTime()) {
                                log.info("There is no New or Updated '" + fileName
                                        + "' file on server to validate. Returning ...");
                                return;
                            } else {
                                log.info("There is New or Updated '" + fileName
                                        + "' file on server to validate. Validating ...");
                                ConnectionsEntity connection = connectionsDao.find(connectionId);
                                connection.setFileDateTime(
                                        new Date(fileObject.getContent().getLastModifiedTime()));
                                ApplicationContext ctx = AppContext.getApplicationContext();
                                ConnectionsDao connDao = (ctx.getBean(ConnectionsDao.class));

                                if (connDao != null) {
                                    connDao.update(connection);
                                }

                                Map<String, byte[]> resultMap = new HashMap<String, byte[]>();
                                byte data[] = new byte[(int) fileObject.getContent().getSize()];
                                fileObject.getContent().getInputStream().read(data);
                                resultMap.put(fileObject.getName().getBaseName(), data);

                                Set<String> keySet = resultMap.keySet();
                                Iterator<String> itr = keySet.iterator();
                                while (itr.hasNext()) {

                                    String strFileName = itr.next();
                                    String result = "";
                                    try {

                                        Long longSchemaId = schemaId;
                                        SchemaEntity schemaEntity = schemasDao.find(longSchemaId);
                                        if (schemaEntity == null) {
                                            result = "No schema found in database with Id [" + longSchemaId
                                                    + "]";
                                            log.error(result);
                                            logDao.setErrorLogMessage(result);
                                        } else {
                                            if (strFileName.endsWith(FileExtensionType.ZIP.getAbbreviation())) {
                                                // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one
                                                ZipInputStream inStream = null;
                                                try {
                                                    inStream = new ZipInputStream(
                                                            new ByteArrayInputStream(resultMap.get(fileName)));
                                                    ZipEntry entry;
                                                    while (!(isStreamClose(inStream))
                                                            && (entry = inStream.getNextEntry()) != null) {
                                                        if (!entry.isDirectory()) {
                                                            DatastreamsInput datastreamsInput = new DatastreamsInput();
                                                            datastreamsInput
                                                                    .setUploadedFileName(entry.getName());
                                                            byte[] byteInput = IOUtils.toByteArray(inStream);
                                                            result += datastreamsInput.datastreamsInput(
                                                                    new String(byteInput), longSchemaId,
                                                                    byteInput);
                                                        }
                                                        inStream.closeEntry();
                                                    }
                                                    log.debug(result);
                                                } catch (IOException ex) {
                                                    result = "Error occured during fetch records from ZIP file.";
                                                    log.error(result);
                                                    logDao.setErrorLogMessage(result);
                                                } finally {
                                                    if (inStream != null)
                                                        inStream.close();
                                                }
                                            } else {
                                                DatastreamsInput datastreamsInput = new DatastreamsInput();
                                                datastreamsInput.setUploadedFileName(strFileName);
                                                result = datastreamsInput.datastreamsInput(
                                                        new String(resultMap.get(strFileName)), longSchemaId,
                                                        resultMap.get(strFileName));
                                                log.debug(result);
                                            }
                                        }
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                        result = "Exception occured during process the message for xml file "
                                                + strFileName + " Error - " + ex.getMessage();
                                        log.error(result);
                                        logDao.setErrorLogMessage(result);
                                    }
                                }
                            }
                        } else if (isDataStream && (conn.getIdConnType() == GenericType.uploadTypeConn)) {

                            File uploadFile = File.createTempFile(fileName, ".tmp");

                            try {
                                BufferedWriter bw = new BufferedWriter(new FileWriter(uploadFile));
                                bw.write(datastream);
                                bw.flush();
                                bw.close();
                            } catch (IOException ioex) {
                                log.error("Datastream file can't be created");
                                logDao.setErrorLogMessage("Datastream file can't be created");
                                return;
                            }

                            if (serviceId == Servers.HTTP.getDbCode()) {
                                try {
                                    HttpClient httpclient = new HttpClient();
                                    PostMethod method = new PostMethod(url);

                                    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                                            new DefaultHttpMethodRetryHandler(3, false));

                                    Part[] parts = new Part[] {
                                            new FilePart("file", uploadFile.getName(), uploadFile) };
                                    method.setRequestEntity(
                                            new MultipartRequestEntity(parts, method.getParams()));
                                    method.setDoAuthentication(true);

                                    int statusCode = httpclient.executeMethod(method);

                                    String responseBody = new String(method.getResponseBody());

                                    if (statusCode != HttpStatus.SC_OK) {
                                        throw new HttpException(method.getStatusLine().toString());
                                    } else {
                                        System.out.println(responseBody);
                                    }

                                    method.releaseConnection();

                                } catch (Exception ex) {
                                    log.error("Exception occurred during uploading of file at HTTP Server: "
                                            + ex.getMessage());
                                    logDao.setErrorLogMessage(
                                            "Exception occurred during uploading of file at HTTP Server: "
                                                    + ex.getMessage());
                                }
                            } else {
                                try {
                                    FileObject localFileObject = fsManager
                                            .resolveFile(uploadFile.getAbsolutePath());
                                    fileObject.copyFrom(localFileObject, Selectors.SELECT_SELF);
                                    System.out.println("File uploaded at : " + new Date());
                                    if (uploadFile.exists()) {
                                        uploadFile.delete();
                                    }
                                } catch (Exception ex) {
                                    log.error(
                                            "Exception occurred during uploading of file: " + ex.getMessage());
                                    logDao.setErrorLogMessage(
                                            "Exception occurred during uploading of file: " + ex.getMessage());
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    log.error("Error " + ": " + ex.getMessage());
                } finally {
                    fsManager.close();
                }
            } finally {
                jobsDao.setWorkStatus(jobId, false);
            }
        } else {
            log.error("Can not set " + jobEntity.getName() + "working.");
        }
    } else {
        log.debug("Job " + jobEntity.getName() + " is working.");
    }

}

From source file:it.openprj.jValidator.services.ServiceScheduledJob.java

@Override
protected synchronized void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
    long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId");
    JobsEntity jobEntity = jobsDao.find(jobId);
    if (!jobEntity.isWorking()) {

        if (jobsDao.setWorkStatus(jobId, true)) {
            try {
                long eventTriggerId = arg0.getJobDetail().getJobDataMap().getString("eventTriggerId") == null
                        ? -1l/*  www .j  av a2s .c  o  m*/
                        : Long.parseLong(arg0.getJobDetail().getJobDataMap().getString("eventTriggerId"));
                if (eventTriggerId > 0) {
                    EventTriggerEntity entity = eventTriggerDao.findEventTriggerById(eventTriggerId);
                    String className = entity.getName();
                    try {
                        String sourceCode = entity.getCode();
                        EventTrigger eventTrigger;
                        String response;
                        eventTrigger = (EventTrigger) CommonUtils.getClassInstance(className,
                                "it.openprj.jValidator.eventtrigger.EventTrigger", EventTrigger.class,
                                sourceCode);
                        assert eventTrigger != null;
                        response = eventTrigger.trigger();
                        log.info("Response From EventTrigger(" + className + ") :" + response);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("EventTrigger(" + className + ") :" + e.getMessage(), e);
                        logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + e.getMessage());
                    } catch (NoClassDefFoundError err) {
                        log.error("EventTrigger(" + className + ") :" + err.getMessage(), err);
                        logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + err.getMessage());
                    }
                    return;
                }

                int day = arg0.getJobDetail().getJobDataMap().getString("day") == null ? -1
                        : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("day"));
                int month = arg0.getJobDetail().getJobDataMap().getString("month") == null ? -1
                        : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("month"));
                if ((day > 0 && day != Calendar.getInstance().get(Calendar.DAY_OF_MONTH))
                        || (month > 0 && month != (Calendar.getInstance().get(Calendar.MONTH) + 1))) {
                    return;
                }
                StandardFileSystemManager fsManager = new StandardFileSystemManager();
                boolean isDataStream = true;
                try {
                    fsManager.init();
                    long schemaId = arg0.getJobDetail().getJobDataMap().getLong("schemaId");
                    long schedulerId = arg0.getJobDetail().getJobDataMap().getLong("schedulerId");
                    //long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId");
                    long connectionId = arg0.getJobDetail().getJobDataMap().getLong("connectionId");

                    String datastream = "";
                    int idSchemaType = schemasDao.find(schemaId).getIdSchemaType();

                    TasksEntity taskEntity = tasksDao.find(schedulerId);
                    //JobsEntity jobEntity = jobsDao.find(jobId);
                    if (taskEntity.getIsOneShoot()) {
                        jobEntity.setIsActive(0);
                        jobsDao.update(jobEntity);
                    }
                    if (idSchemaType == SchemaType.GENERATION) {
                        StreamGenerationUtils sgu = new StreamGenerationUtils();
                        datastream = sgu.getStream(schemaId);

                        log.debug("Content stream: " + schemaId);

                        if (datastream.trim().length() > 0) {
                            log.debug("Datastream to validate: " + datastream);
                            DatastreamsInput datastreamsInput = new DatastreamsInput();
                            String result = datastreamsInput.datastreamsInput(datastream, schemaId, null);
                            log.debug("Validation result: " + result);
                        } else {
                            isDataStream = false;
                            log.debug("No datastream create");
                        }
                    }
                    if (connectionId != 0) {
                        int serviceId = Integer
                                .parseInt(arg0.getJobDetail().getJobDataMap().getString("serviceId"));

                        String hostName = arg0.getJobDetail().getJobDataMap().getString("ftpServerIp");
                        String port = arg0.getJobDetail().getJobDataMap().getString("port");
                        String userName = arg0.getJobDetail().getJobDataMap().getString("userName");
                        String password = arg0.getJobDetail().getJobDataMap().getString("password");
                        String inputDirectory = arg0.getJobDetail().getJobDataMap().getString("inputDirectory");
                        String fileName = arg0.getJobDetail().getJobDataMap().getString("fileName");

                        ConnectionsEntity conn;

                        conn = connectionsDao.find(connectionId);

                        if (inputDirectory == null || inputDirectory.trim().length() == 0) {
                            inputDirectory = fileName;
                        } else if (!(conn.getIdConnType() == GenericType.uploadTypeConn
                                && serviceId == Servers.HTTP.getDbCode())) {
                            inputDirectory = inputDirectory + "/" + fileName;
                        }

                        log.info("(jobId:" + jobEntity.getName() + ") - Trying to Server polling at server ["
                                + hostName + ":" + port + "] with user[" + userName + "].");
                        String url = "";
                        if (serviceId == Servers.SAMBA.getDbCode()) {
                            if (!fsManager.hasProvider("smb")) {
                                fsManager.addProvider("smb", new SmbFileProvider());
                            }
                            url = "smb://" + userName + ":" + password + "@" + hostName + ":" + port + "/"
                                    + inputDirectory;
                        } else if (serviceId == Servers.HTTP.getDbCode()) {
                            if (!fsManager.hasProvider("http")) {
                                fsManager.addProvider("http", new HttpFileProvider());
                            }
                            url = "http://" + hostName + ":" + port + "/" + inputDirectory;
                        } else if (serviceId == Servers.FTP.getDbCode()) {
                            if (!fsManager.hasProvider("ftp")) {
                                fsManager.addProvider("ftp", new FtpFileProvider());
                            }
                            url = "ftp://" + userName + ":" + password + "@" + hostName + ":" + port + "/"
                                    + inputDirectory;
                        }
                        log.info("url:" + url);
                        final FileObject fileObject = fsManager.resolveFile(url);

                        if (conn.getIdConnType() == GenericType.DownloadTypeConn) {

                            if (conn.getFileDateTime() != null && conn.getFileDateTime().getTime() == fileObject
                                    .getContent().getLastModifiedTime()) {
                                log.info("There is no New or Updated '" + fileName
                                        + "' file on server to validate. Returning ...");
                                return;
                            } else {
                                log.info("There is New or Updated '" + fileName
                                        + "' file on server to validate. Validating ...");
                                ConnectionsEntity connection = connectionsDao.find(connectionId);
                                connection.setFileDateTime(
                                        new Date(fileObject.getContent().getLastModifiedTime()));
                                ApplicationContext ctx = AppContext.getApplicationContext();
                                ConnectionsDao connDao = (ctx.getBean(ConnectionsDao.class));

                                if (connDao != null) {
                                    connDao.update(connection);
                                }

                                Map<String, byte[]> resultMap = new HashMap<String, byte[]>();
                                byte data[] = new byte[(int) fileObject.getContent().getSize()];
                                fileObject.getContent().getInputStream().read(data);
                                resultMap.put(fileObject.getName().getBaseName(), data);

                                Set<String> keySet = resultMap.keySet();
                                Iterator<String> itr = keySet.iterator();
                                while (itr.hasNext()) {

                                    String strFileName = itr.next();
                                    String result = "";
                                    try {

                                        Long longSchemaId = schemaId;
                                        SchemaEntity schemaEntity = schemasDao.find(longSchemaId);
                                        if (schemaEntity == null) {
                                            result = "No schema found in database with Id [" + longSchemaId
                                                    + "]";
                                            log.error(result);
                                            logDao.setErrorLogMessage(result);
                                        } else {
                                            if (strFileName.endsWith(FileExtensionType.ZIP.getAbbreviation())) {
                                                // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one
                                                ZipInputStream inStream = null;
                                                try {
                                                    inStream = new ZipInputStream(
                                                            new ByteArrayInputStream(resultMap.get(fileName)));
                                                    ZipEntry entry;
                                                    while (!(isStreamClose(inStream))
                                                            && (entry = inStream.getNextEntry()) != null) {
                                                        if (!entry.isDirectory()) {
                                                            DatastreamsInput datastreamsInput = new DatastreamsInput();
                                                            datastreamsInput
                                                                    .setUploadedFileName(entry.getName());
                                                            byte[] byteInput = IOUtils.toByteArray(inStream);
                                                            result += datastreamsInput.datastreamsInput(
                                                                    new String(byteInput), longSchemaId,
                                                                    byteInput);
                                                        }
                                                        inStream.closeEntry();
                                                    }
                                                    log.debug(result);
                                                } catch (IOException ex) {
                                                    result = "Error occured during fetch records from ZIP file.";
                                                    log.error(result);
                                                    logDao.setErrorLogMessage(result);
                                                } finally {
                                                    if (inStream != null)
                                                        inStream.close();
                                                }
                                            } else {
                                                DatastreamsInput datastreamsInput = new DatastreamsInput();
                                                datastreamsInput.setUploadedFileName(strFileName);
                                                result = datastreamsInput.datastreamsInput(
                                                        new String(resultMap.get(strFileName)), longSchemaId,
                                                        resultMap.get(strFileName));
                                                log.debug(result);
                                            }
                                        }
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                        result = "Exception occured during process the message for xml file "
                                                + strFileName + " Error - " + ex.getMessage();
                                        log.error(result);
                                        logDao.setErrorLogMessage(result);
                                    }
                                }
                            }
                        } else if (isDataStream && (conn.getIdConnType() == GenericType.uploadTypeConn)) {

                            File uploadFile = File.createTempFile(fileName, ".tmp");

                            try {
                                BufferedWriter bw = new BufferedWriter(new FileWriter(uploadFile));
                                bw.write(datastream);
                                bw.flush();
                                bw.close();
                            } catch (IOException ioex) {
                                log.error("Datastream file can't be created");
                                logDao.setErrorLogMessage("Datastream file can't be created");
                                return;
                            }

                            if (serviceId == Servers.HTTP.getDbCode()) {
                                try {
                                    HttpClient httpclient = new HttpClient();
                                    PostMethod method = new PostMethod(url);

                                    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                                            new DefaultHttpMethodRetryHandler(3, false));

                                    Part[] parts = new Part[] {
                                            new FilePart("file", uploadFile.getName(), uploadFile) };
                                    method.setRequestEntity(
                                            new MultipartRequestEntity(parts, method.getParams()));
                                    method.setDoAuthentication(true);

                                    int statusCode = httpclient.executeMethod(method);

                                    String responseBody = new String(method.getResponseBody());

                                    if (statusCode != HttpStatus.SC_OK) {
                                        throw new HttpException(method.getStatusLine().toString());
                                    } else {
                                        System.out.println(responseBody);
                                    }

                                    method.releaseConnection();

                                } catch (Exception ex) {
                                    log.error("Exception occurred during uploading of file at HTTP Server: "
                                            + ex.getMessage());
                                    logDao.setErrorLogMessage(
                                            "Exception occurred during uploading of file at HTTP Server: "
                                                    + ex.getMessage());
                                }
                            } else {
                                try {
                                    FileObject localFileObject = fsManager
                                            .resolveFile(uploadFile.getAbsolutePath());
                                    fileObject.copyFrom(localFileObject, Selectors.SELECT_SELF);
                                    System.out.println("File uploaded at : " + new Date());
                                    if (uploadFile.exists()) {
                                        uploadFile.delete();
                                    }
                                } catch (Exception ex) {
                                    log.error(
                                            "Exception occurred during uploading of file: " + ex.getMessage());
                                    logDao.setErrorLogMessage(
                                            "Exception occurred during uploading of file: " + ex.getMessage());
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    log.error("Error " + ": " + ex.getMessage());
                } finally {
                    fsManager.close();
                }
            } finally {
                jobsDao.setWorkStatus(jobId, false);
            }
        } else {
            log.error("Can not set " + jobEntity.getName() + "working.");
        }
    } else {
        log.debug("Job " + jobEntity.getName() + " is working.");
    }

}

From source file:com.orange.mmp.widget.WidgetManager.java

/**
 * Add branch ID to a widget Manifest before deploying it
 * @param widgetFile/*from   w  w w  .j  a v a  2 s .c  om*/
 * @param branchId
 * @return a Widget instance
 * @throws IOException 
 * @throws MMPException 
 */
public Widget deployWidget(File widgetFile, String branchId) throws MMPException {
    Widget widget = new Widget();
    ZipInputStream zin = null;
    ZipOutputStream zout = null;

    try {
        JarFile jarFile = new JarFile(new File(widgetFile.toURI()));
        Manifest manifest = jarFile.getManifest();

        String tmpWidgetId = manifest.getMainAttributes()
                .getValue(FelixOSGiContainer.BUNDLE_SYMBOLICNAME_HEADER);
        widget.setBranchId(branchId);

        if (tmpWidgetId != null) {
            widget.setName(manifest.getMainAttributes().getValue(FelixOSGiContainer.BUNDLE_NAME_HEADER));
            widget.setId(tmpWidgetId + com.orange.mmp.widget.Constants.BRANCH_SUFFIX_PATTERN + branchId);
            manifest.getMainAttributes().putValue(FelixOSGiContainer.BUNDLE_SYMBOLICNAME_HEADER,
                    widget.getId());

            File tempFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), ".jar");

            zin = new ZipInputStream(new FileInputStream(widgetFile));
            zout = new ZipOutputStream(new FileOutputStream(tempFile));

            ZipEntry entry = zin.getNextEntry();
            while (entry != null) {
                String name = entry.getName();
                zout.putNextEntry(new ZipEntry(name));
                if (!name.equals(com.orange.mmp.midlet.Constants.JAR_MANIFEST_ENTRY)) {
                    IOUtils.copy(zin, zout);
                } else {
                    manifest.write(zout);
                }
                entry = zin.getNextEntry();
            }

            widget.setLocation(tempFile.toURI());
            widget.setId(tmpWidgetId);
            widget.setLastModified(tempFile.lastModified());
            widget.setCategory(com.orange.mmp.core.Constants.MODULE_CATEGORY_WIDGET);
            widget.setVersion(new Version(
                    manifest.getMainAttributes().getValue(FelixOSGiContainer.BUNDLE_VERSION_HEADER)));
        } else {
            throw new MMPException("Invalid module archive, missing "
                    + FelixOSGiContainer.BUNDLE_SYMBOLICNAME_HEADER + " header");
        }

    } catch (IOException ioe) {
        throw new MMPException("Failed to deploy widget", ioe);
    } finally {
        if (zin != null) {
            try {
                zin.close();
            } catch (IOException ioe) {
                //NOP
            }
        }
        if (zout != null)
            try {
                zout.close();
            } catch (IOException ioe) {
                //NOP
            }
    }

    MMPOSGiContainer moduleContainer = (MMPOSGiContainer) ModuleContainerFactory.getInstance()
            .getModuleContainer();
    moduleContainer.deployModule(new File(widget.getLocation()));

    return widget;
}

From source file:eu.europa.ec.markt.dss.validation.SignedDocumentValidator.java

private static SignedDocumentValidator getInstanceForAsics(Document document) throws IOException {

    ZipInputStream asics = new ZipInputStream(document.openStream());

    try {//from  ww w .  j a va2 s  .  c  o  m

        ByteArrayOutputStream datafile = null;
        ByteArrayOutputStream signatures = null;
        ZipEntry entry;

        boolean cadesSigned = false;
        boolean xadesSigned = false;

        while ((entry = asics.getNextEntry()) != null) {
            if (entry.getName().equalsIgnoreCase(SIGNATURES_P7S)) {
                if (xadesSigned) {
                    throw new NotETSICompliantException(MSG.MORE_THAN_ONE_SIGNATURE);
                }
                signatures = new ByteArrayOutputStream();
                IOUtils.copy(asics, signatures);
                signatures.close();
                cadesSigned = true;
            } else if (entry.getName().equalsIgnoreCase(SIGNATURES_XML)) {
                if (cadesSigned) {
                    throw new NotETSICompliantException(MSG.MORE_THAN_ONE_SIGNATURE);
                }
                signatures = new ByteArrayOutputStream();
                IOUtils.copy(asics, signatures);
                signatures.close();
                xadesSigned = true;
            } else if (entry.getName().equalsIgnoreCase(MIMETYPE)) {
                ByteArrayOutputStream mimetype = new ByteArrayOutputStream();
                IOUtils.copy(asics, mimetype);
                mimetype.close();
                if (!Arrays.equals(mimetype.toByteArray(), MIMETYPE_ASIC_S.getBytes())) {
                    throw new NotETSICompliantException(MSG.UNRECOGNIZED_TAG);
                }
            } else if (entry.getName().indexOf("/") == -1) {
                if (datafile == null) {
                    datafile = new ByteArrayOutputStream();
                    IOUtils.copy(asics, datafile);
                    datafile.close();
                } else {
                    throw new ProfileException("ASiC-S profile support only one data file");
                }
            }
        }

        if (xadesSigned) {
            ASiCXMLDocumentValidator xmlValidator = new ASiCXMLDocumentValidator(
                    new InMemoryDocument(signatures.toByteArray()), datafile.toByteArray());
            return xmlValidator;
        } else if (cadesSigned) {
            CMSDocumentValidator pdfValidator = new CMSDocumentValidator(
                    new InMemoryDocument(signatures.toByteArray()));
            pdfValidator.setExternalContent(new InMemoryDocument(datafile.toByteArray()));
            return pdfValidator;
        } else {
            throw new RuntimeException("Is not xades nor cades signed");
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        try {
            asics.close();
        } catch (IOException e) {
        }
    }

}

From source file:hudson.FilePath.java

private void unzip(File dir, InputStream in) throws IOException {
    dir = dir.getAbsoluteFile(); // without absolutization, getParentFile below seems to fail
    ZipInputStream zip = new ZipInputStream(new BufferedInputStream(in));
    java.util.zip.ZipEntry e;/*from   w w  w .  j a  va  2  s  .  com*/

    try {
        while ((e = zip.getNextEntry()) != null) {
            File f = new File(dir, e.getName());
            if (e.isDirectory()) {
                f.mkdirs();
            } else {
                File p = f.getParentFile();
                if (p != null)
                    p.mkdirs();
                FileOutputStream out = new FileOutputStream(f);
                try {
                    IOUtils.copy(zip, out);
                } finally {
                    out.close();
                }
                f.setLastModified(e.getTime());
                zip.closeEntry();
            }
        }
    } finally {
        zip.close();
    }
}

From source file:org.apache.axis2.deployment.util.Utils.java

public static URL[] getURLsForAllJars(URL url, File tmpDir) {
    FileInputStream fin = null;//from  w w w.jav a2 s  . c om
    InputStream in = null;
    ZipInputStream zin = null;
    try {
        ArrayList array = new ArrayList();
        in = url.openStream();
        String fileName = url.getFile();
        int index = fileName.lastIndexOf('/');
        if (index != -1) {
            fileName = fileName.substring(index + 1);
        }
        final File f = createTempFile(fileName, in, tmpDir);

        fin = (FileInputStream) org.apache.axis2.java.security.AccessController
                .doPrivileged(new PrivilegedExceptionAction() {
                    public Object run() throws FileNotFoundException {
                        return new FileInputStream(f);
                    }
                });
        array.add(f.toURL());
        zin = new ZipInputStream(fin);

        ZipEntry entry;
        String entryName;
        while ((entry = zin.getNextEntry()) != null) {
            entryName = entry.getName();
            /**
             * id the entry name start with /lib and end with .jar then
             * those entry name will be added to the arraylist
             */
            if ((entryName != null) && entryName.toLowerCase().startsWith("lib/")
                    && entryName.toLowerCase().endsWith(".jar")) {
                String suffix = entryName.substring(4);
                File f2 = createTempFile(suffix, zin, tmpDir);
                array.add(f2.toURL());
            }
        }
        return (URL[]) array.toArray(new URL[array.size()]);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (fin != null) {
            try {
                fin.close();
            } catch (IOException e) {
                //
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                //
            }
        }
        if (zin != null) {
            try {
                zin.close();
            } catch (IOException e) {
                //
            }
        }
    }
}

From source file:org.flowable.ui.modeler.service.AppDefinitionImportService.java

protected Model readZipFile(InputStream inputStream, Map<String, String> formMap,
        Map<String, String> decisionTableMap, Map<String, String> bpmnModelMap,
        Map<String, String> cmmnModelMap, Map<String, byte[]> thumbnailMap) {

    Model appDefinitionModel = null;//w w  w  .jav  a  2  s.c  o  m
    ZipInputStream zipInputStream = null;
    try {
        zipInputStream = new ZipInputStream(inputStream);
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        while (zipEntry != null) {
            String zipEntryName = zipEntry.getName();
            if (zipEntryName.endsWith("json") || zipEntryName.endsWith("png")) {

                String modelFileName = null;
                if (zipEntryName.contains("/")) {
                    modelFileName = zipEntryName.substring(zipEntryName.indexOf('/') + 1);
                } else {
                    modelFileName = zipEntryName;
                }

                if (modelFileName.endsWith(".png")) {
                    thumbnailMap.put(modelFileName.replace(".png", ""), IOUtils.toByteArray(zipInputStream));

                } else {
                    modelFileName = modelFileName.replace(".json", "");
                    String json = IOUtils.toString(zipInputStream, "utf-8");

                    if (zipEntryName.startsWith("bpmn-models/")) {
                        bpmnModelMap.put(modelFileName, json);

                    } else if (zipEntryName.startsWith("cmmn-models/")) {
                        cmmnModelMap.put(modelFileName, json);

                    } else if (zipEntryName.startsWith("form-models/")) {
                        formMap.put(modelFileName, json);

                    } else if (zipEntryName.startsWith("decision-table-models/")) {
                        decisionTableMap.put(modelFileName, json);

                    } else if (!zipEntryName.contains("/")) {
                        appDefinitionModel = createModelObject(json, Model.MODEL_TYPE_APP);
                    }
                }
            }

            zipEntry = zipInputStream.getNextEntry();
        }
    } catch (Exception e) {
        LOGGER.error("Error reading app definition zip file", e);
        throw new InternalServerErrorException("Error reading app definition zip file");

    } finally {
        if (zipInputStream != null) {
            try {
                zipInputStream.closeEntry();
            } catch (Exception e) {
            }

            try {
                zipInputStream.close();
            } catch (Exception e) {
            }
        }
    }

    return appDefinitionModel;
}