R
R
random2014-11-23 10:09:28
Java
random, 2014-11-23 10:09:28

Are there any unhandled errors?

@WebServlet(
        description = "generator servlet",  
        urlPatterns = {"/generator"})
public class Generator extends HttpServlet {

    private static final Category LOG = Category.getInstance(Generator.class);

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        PrintWriter out = null;
        try {
            //Задаем тип страницы
            response.setContentType("text/html");

            //Для вывода
            out = response.getWriter();

            //Находим путь к файлу 'сonfig.properties'
            Properties props = new Properties();
            String propsFile = "config.properties";
            InputStream input = getClass().getClassLoader().getResourceAsStream(propsFile);

            //Если файл properties не найден
            if (input == null) {
                LOG.error("property file " + propsFile + " not found");

                out.print("<h1>Sorry, config file not found!</h1>");
                return;
            }

            props.load(input);

            //Задаем переменным значения
            String pr = props.getProperty("product");
            String clientsCount = request.getParameter("numUser");
            String otpCount = request.getParameter("numUtp");
            String lices = request.getParameter("licesee");
            String date = request.getParameter("data");
            String certPeriod = request.getParameter("certPeriod");
            String pass = props.getProperty("password");
            String lic = props.getProperty("license");

            //Задаем имя файла
            String fileName = lices + "_" + clientsCount + "_" + otpCount + "_" + date + ".lic";
            //Место хранения файла
            String outFile = props.getProperty("outFile");
            //Путь к ключу
            String keyFile = props.getProperty("keyFile");

            //Добавляем в массив данные
            ArrayList<String> snlist = new ArrayList<>();
            for (int i = 10; i < 10; i++) {
                snlist.add(pr);
                snlist.add(clientsCount);
                snlist.add(otpCount);
                snlist.add(lices);
                snlist.add(date);
                snlist.add(certPeriod);
                snlist.add(outFile);
                snlist.add(keyFile);
                snlist.add(pass);
                snlist.add(lic);
            }

            //Вставляем в config.properties данные
            props.put("ActiveOtpCount", otpCount);
            props.put("ActiveClientsCount", clientsCount);
            props.put("Licensee", lices);
            props.put("LicenseExpired", date);
            props.put("CertificatesPeriod", certPeriod);

            //Инициализация утилит
            LicenseGenerator.init();

            KeyStore ks = KeyStore.getInstance("AKS", AkSigProv.PROV_NAME);
            ks.load(new FileInputStream(keyFile), pass.toCharArray());
            String a = ks.aliases().nextElement();
            PrivateKey pk = (PrivateKey) ks.getKey(a, pass.toCharArray());
            X509Certificate cert = (X509Certificate) ks.getCertificate(a);

            //Генерируем лиценцию, и записываем в файл
            String x = LicenseGenerator.generateLicense(pr, snlist, props, cert, pk);
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outFile + fileName);
                fos.write(x.getBytes());
            } catch (Exception e) {
                LOG.info("Exception:" + e);
            } finally {
                fos.close();
            }
            
            //Записываем в файл
            OutputStream outStream = null;
            FileInputStream inStream = null;
            try {
                //Создаем файл
                File downloadFile = new File(outFile + fileName);
                //Считываем с файла
                inStream = new FileInputStream(downloadFile);
                out.print(x);

                //Сохраняем файл
                String headerKey = "Content-Disposition";
                String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
                response.setHeader(headerKey, headerValue);

                outStream = response.getOutputStream();
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
            } catch (Exception e) {
                LOG.error(e);
            } finally {
                outStream.close();
                inStream.close();
            }

        } catch (NoSuchAlgorithmException ex) {
            LOG.error(ex);
        } catch (CertificateException ex) {
            LOG.error(ex);
        } catch (Exception ex) {
            LOG.error(ex);
        } finally {
            out.close();
        }
    }
}

The code is working!
Hello everyone, Do I have unhandled errors, and when I have an error, it writes to the log, but it does not specifically say where the error occurred, how can I fix it? And they also remarked to me that I have 2 requests and 1 response, but I need to make it so that there is 1 request and 1 response (I didn’t really understand what they meant)?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
yahorfilipcyk, 2014-11-23
@yahorfilipcyk

Does your code really work? :) Or do you not quite understand what is happening in it?

for (int i = 10; i < 10; i++) {
     snlist.add(pr);
     snlist.add(clientsCount);
     snlist.add(otpCount);
     snlist.add(lices);
     snlist.add(date);
     snlist.add(certPeriod);
     snlist.add(outFile);
     snlist.add(keyFile);
     snlist.add(pass);
     snlist.add(lic);
}

Another note: you are calling response.getWriter() and response.getOutputStream() from the same response object. And close both OutputStream and Writer. Both objects refer to the same Stream. You need to choose one thing. You also write the license to a file, then read the same file and send the contents to the client. Wouldn't it be easier to send the contents of String x to the client instead of reading it from a file?
About exceptions... It is not necessary to write catch (Exception ex) everywhere. Catch those exceptions that can tell you something and you can take some action.
And yet, be a man :) break different functional blocks of code into separate methods, otherwise it's hard to understand the sheets of code. I didn't even try to figure out what your code actually does. Therefore, not all comments are listed, there are suspicions.

R
random, 2014-11-24
@demon123

@WebServlet(
        description = "generator servlet",
        urlPatterns = {"/generator"})
public class Generator extends HttpServlet {

    private static final Category LOG = Category.getInstance(Generator.class);

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        PrintWriter out = null;
        try {
            //Задаем тип страницы
            response.setContentType("text/html");

            //Для вывода
            out = response.getWriter();

            //Находим путь к файлу 'сonfig.properties'
            Properties props = new Properties();
            String propsFile = "config.properties";
            InputStream input = getClass().getClassLoader().getResourceAsStream(propsFile);
            
            //Если файл properties не найден
            if (input == null) {
                LOG.error("property file " + propsFile + " not found");

                out.print("<h1>Sorry, config file not found!</h1>");
                return;
            }

            props.load(input);

            //Задаем переменным значения
            String pr = props.getProperty("product");
            String clientsCount = request.getParameter("numUser");
            String otpCount = request.getParameter("numUtp");
            String lices = request.getParameter("licesee");
            String date = request.getParameter("data");
            String certPeriod = request.getParameter("certPeriod");
            String pass = props.getProperty("password");
            String lic = props.getProperty("license");

            //Задаем имя файла
            String fileName = lices + "_" + clientsCount + "_" + otpCount + "_" + date + ".lic";
            //Место хранения файла
            String outFile = props.getProperty("outFile");
            //Путь к ключу
            String keyFile = props.getProperty("keyFile");

            //Добавляем в массив данные
            ArrayList<String> snlist = new ArrayList<>();
            for (int i = 10; i < 10; i++) {
                snlist.add(pr);
                snlist.add(clientsCount);
                snlist.add(otpCount);
                snlist.add(lices);
                snlist.add(date);
                snlist.add(certPeriod);
                snlist.add(outFile);
                snlist.add(keyFile);
                snlist.add(pass);
                snlist.add(lic);
            }

            //Вставляем в config.properties данные
            props.put("ActiveOtpCount", otpCount);
            props.put("ActiveClientsCount", clientsCount);
            props.put("Licensee", lices);
            props.put("LicenseExpired", date);
            props.put("CertificatesPeriod", certPeriod);

            //Инициализация утилит
            LicenseGenerator.init();

            KeyStore ks = KeyStore.getInstance("AKS", AkSigProv.PROV_NAME);
            ks.load(new FileInputStream(keyFile), pass.toCharArray());
            String a = ks.aliases().nextElement();
            PrivateKey pk = (PrivateKey) ks.getKey(a, pass.toCharArray());
            X509Certificate cert = (X509Certificate) ks.getCertificate(a);

            //Генерируем лиценцию, и записываем в файл
            String x = LicenseGenerator.generateLicense(pr, snlist, props, cert, pk);

            saveLicense(response, x, outFile, fileName);

        } catch (Exception ex) {
            LOG.error(response, ex);
        } finally {
            out.close();
        }
    }

    public void saveLicense(HttpServletResponse response, String x, String outFile, String fileName)
            throws IOException, ServletException {
        PrintWriter out = null;
        FileOutputStream fos = null;
        try {

            fos = new FileOutputStream(outFile + fileName);
            fos.write(x.getBytes());

            String headerKey = "Content-Disposition";
            String headerValue = String.format("attachment; filename=\"%s\"", fileName);
            response.setHeader(headerKey, headerValue);
            out.write(x);

        } catch (IOException ex) {
            LOG.error(response, ex);
        } finally {
            out.close();
            fos.close();
        }
    }
}

Fixed something that can still be fixed?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question