Example usage for java.io PrintWriter close

List of usage examples for java.io PrintWriter close

Introduction

In this page you can find the example usage for java.io PrintWriter close.

Prototype

public void close() 

Source Link

Document

Closes the stream and releases any system resources associated with it.

Usage

From source file:net.bashtech.geobot.BotManager.java

public static String postDataLinkShortener(String postData) {
    URL url;/*from www  .  j a v a  2  s. com*/
    HttpURLConnection conn;
    postData = "{\"longUrl\": \"" + postData + "\"}";

    try {
        url = new URL("https://www.googleapis.com/urlshortener/v1/url");

        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", "CoeBot");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length));

        PrintWriter out = new PrintWriter(conn.getOutputStream());
        System.out.println(postData);
        out.print(postData);
        out.close();

        String response = "";

        Scanner inStream = new Scanner(conn.getInputStream());

        while (inStream.hasNextLine())
            response += (inStream.nextLine());

        inStream.close();
        return response;

    } catch (MalformedURLException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return "";

}

From source file:de.shadowhunt.sonar.plugins.ignorecode.batch.IgnoreCoverageMeasurementFilterTest.java

@Test
public void testAcceptNotMatchedResource() throws Exception {
    final java.io.File configFile = temporaryFolder.newFile("coverage.txt");
    final PrintWriter writer = new PrintWriter(configFile);
    writer.println("src/java/net/example/Foo.java;[1-20]");
    writer.close();

    final Configuration configuration = Mockito.mock(Configuration.class);
    Mockito.when(configuration.getString(IgnoreCoverageDecorator.CONFIG_FILE))
            .thenReturn(configFile.getAbsolutePath());

    final IgnoreCoverageMeasurementFilter filter = new IgnoreCoverageMeasurementFilter(configuration);

    final File file = File.create("src/java/net/example/Bar.java");
    Assert.assertTrue("non matching file", filter.accept(file, new Measure(CoreMetrics.COVERAGE, 42.0)));
}

From source file:de.shadowhunt.sonar.plugins.ignorecode.batch.IgnoreCoverageMeasurementFilterTest.java

@Test
public void testAccept() throws Exception {
    final java.io.File configFile = temporaryFolder.newFile("coverage.txt");
    final PrintWriter writer = new PrintWriter(configFile);
    writer.println("src/java/net/example/Foo.java;[1-20]");
    writer.close();

    final Configuration configuration = Mockito.mock(Configuration.class);
    Mockito.when(configuration.getString(IgnoreCoverageDecorator.CONFIG_FILE))
            .thenReturn(configFile.getAbsolutePath());

    final IgnoreCoverageMeasurementFilter filter = new IgnoreCoverageMeasurementFilter(configuration);

    final File file = File.create("src/java/net/example/Foo.java");
    Assert.assertTrue("measure modified but accepted",
            filter.accept(file, new Measure(CoreMetrics.COVERAGE, 42.0)));
}

From source file:cn.com.sgcc.servlet.LicenseServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    {// w ww . j a  v a  2 s .c  om
        // context
        AccessControlContext context = new AccessControlContext();
        context.setIp(request.getRemoteAddr());
        //context.setIp("127.0.0.1");

        // get rid
        String[] ridNames = { "RID", "rid", "Rid" };
        String rid = null;
        for (int i = 0; i < ridNames.length; ++i) {
            rid = request.getParameter(ridNames[i]);
            if (null != rid) {
                break;
            }
        }
        if (null == rid) {
            logger.error(new StringBuilder().append(context.getIp()).append(" no rid").toString());
            response.sendError(400, "no rid");
            return;
        }

        // get uid
        String[] uidNames = { "UID", "uid", "Uid" };
        String uid = null;
        for (int i = 0; i < uidNames.length; ++i) {
            uid = request.getParameter(uidNames[i]);
            if (null != uid) {
                break;
            }
        }
        /*   
           if (null == uid)
           {
           response.sendError(ErrorCode.PARAM_NULL_UID);
           return;
           }
           */

        // user
        User user = new User();
        user.setName(uid);

        // resource 
        Resource resource = new Resource();
        resource.setNameHash(rid);

        logger.info(new StringBuilder().append(context.getIp()).append(" ").append(rid)
                .append(" license request").toString());

        // execute access control
        License license = accessControl.execute(user, resource, context);
        if (null == license || null == license.toXmlString()) {
            logger.info(new StringBuilder().append(context.getIp()).append(" ").append(rid)
                    .append(" license deny").toString());
            response.sendError(400, "Bad request: no permission or rid not exists");
            return;
        }

        // response
        response.setContentType("text/xml;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(license.toXmlString());
        out.close();

        logger.info(new StringBuilder().append(context.getIp()).append(" ").append(rid)
                .append(" license return").toString());
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.sparql.GetClazzObjectProperties.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!isAuthorizedToDisplayPage(request, response, SimplePermission.USE_MISCELLANEOUS_PAGES.ACTION)) {
        return;//from  ww  w .  j  a  v  a2s. c  o m
    }

    VitroRequest vreq = new VitroRequest(request);

    String vClassURI = vreq.getParameter("vClassURI");
    if (vClassURI == null || vClassURI.trim().equals("")) {
        return;
    }

    String respo = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    respo += "<options>";

    ObjectPropertyDao odao = vreq.getUnfilteredWebappDaoFactory().getObjectPropertyDao();
    PropertyInstanceDao piDao = vreq.getUnfilteredWebappDaoFactory().getPropertyInstanceDao();
    VClassDao vcDao = vreq.getUnfilteredWebappDaoFactory().getVClassDao();

    // incomplete list of classes to check, but better than before
    List<String> superclassURIs = vcDao.getAllSuperClassURIs(vClassURI);
    superclassURIs.add(vClassURI);
    superclassURIs.addAll(vcDao.getEquivalentClassURIs(vClassURI));

    Map<String, PropertyInstance> propInstMap = new HashMap<String, PropertyInstance>();
    for (String classURI : superclassURIs) {
        Collection<PropertyInstance> propInsts = piDao.getAllPropInstByVClass(classURI);
        try {
            for (PropertyInstance propInst : propInsts) {
                propInstMap.put(propInst.getPropertyURI(), propInst);
            }
        } catch (NullPointerException ex) {
            continue;
        }
    }
    List<PropertyInstance> propInsts = new ArrayList<PropertyInstance>();
    propInsts.addAll(propInstMap.values());
    Collections.sort(propInsts);

    Iterator propInstIt = propInsts.iterator();
    HashSet opropURIs = new HashSet();
    while (propInstIt.hasNext()) {
        PropertyInstance pi = (PropertyInstance) propInstIt.next();
        if (!(opropURIs.contains(pi.getPropertyURI()))) {
            opropURIs.add(pi.getPropertyURI());
            ObjectProperty oprop = (ObjectProperty) odao.getObjectPropertyByURI(pi.getPropertyURI());
            if (oprop != null) {
                respo += "<option>" + "<key>" + oprop.getLocalName() + "</key>" + "<value>" + oprop.getURI()
                        + "</value>" + "</option>";
            }
        }
    }
    respo += "</options>";
    response.setContentType("text/xml");
    response.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();

    out.println(respo);
    out.flush();
    out.close();
}

From source file:net.sourceforge.mavenhippo.BeanCreator.java

private void createBean(ContentTypeBean contentType) throws MojoExecutionException {
    try {/* ww w. java  2  s . c o m*/
        String[] packages = generator.getPackage(contentType);
        String className = generator.getClassName(contentType);
        File pack = fileManager.getPackage(packages);
        File classFile = fileManager.getClassFile(pack, className);
        PrintWriter writer = new PrintWriter(classFile);
        writer.print(generator.generateBean(contentType));
        writer.close();
    } catch (ContentTypeException e) {
        throw new MojoExecutionException(e.getLocalizedMessage(), e);
    } catch (TemplateException e) {
        throw new MojoExecutionException(e.getLocalizedMessage(), e);
    } catch (IOException e) {
        throw new MojoExecutionException(e.getLocalizedMessage(), e);
    }
}

From source file:de.shadowhunt.sonar.plugins.ignorecode.batch.IgnoreCoverageDecoratorTest.java

@Test
public void testLoadPatternsFile() throws IOException {
    final File tempFile = temporaryFolder.newFile("coverage.txt");
    final PrintWriter writer = new PrintWriter(tempFile);
    writer.println("**/*;*");
    writer.close();

    final Configuration configuration = Mockito.mock(Configuration.class);
    Mockito.when(configuration.getString(IgnoreCoverageDecorator.CONFIG_FILE))
            .thenReturn(tempFile.getAbsolutePath());
    final List<CoveragePattern> patterns = IgnoreCoverageDecorator.loadPatterns(configuration);
    Assert.assertNotNull("List must not be null", patterns);
    Assert.assertEquals("List must contain the exact number of entries", 1, patterns.size());
}

From source file:de.shadowhunt.sonar.plugins.ignorecode.batch.IgnoreCoverageDecoratorTest.java

@Test(expected = SonarException.class)
public void testLoadPatternsInvalidFile() throws IOException {
    final File tempFile = temporaryFolder.newFile("coverage.txt");
    final PrintWriter writer = new PrintWriter(tempFile);
    writer.println("invalid");
    writer.close();

    final Configuration configuration = Mockito.mock(Configuration.class);
    Mockito.when(configuration.getString(IgnoreCoverageDecorator.CONFIG_FILE))
            .thenReturn(tempFile.getAbsolutePath());
    IgnoreCoverageDecorator.loadPatterns(configuration);
    Assert.fail("must not load invalid file");
}

From source file:gov.nih.nci.cabig.caaers.tools.spring.tabbedflow.SimpleFormAjaxableController.java

protected void respondAjaxFreeText(ModelAndView modelAndView, HttpServletResponse response) throws Exception {
    PrintWriter pr = response.getWriter();
    pr.println(modelAndView.getModel().get(getFreeTextModelName()));
    pr.flush();//  w  w  w.j a va2  s  .  c  o  m
    pr.close();
}

From source file:org.opennms.features.vaadin.pmatrix.manual.AppContextSpecificationMarshalTest.java

public void testJaxbFromContext() {
    System.out.println("start of test:testJaxbFromContext()");
    try {/*from ww w. ja v  a 2s .com*/
        String testFileName = this.getClass().getSimpleName() + "_File.xml";
        File file = new File("target/" + testFileName);
        PrintWriter writer = new PrintWriter(file, "UTF-8");
        writer.close();
        System.out.println("file location:" + file.getAbsolutePath());

        // see http://stackoverflow.com/questions/1043109/why-cant-jaxb-find-my-jaxb-index-when-running-inside-apache-felix
        // need to provide bundles class loader
        ClassLoader cl = org.opennms.features.vaadin.pmatrix.model.DataPointDefinition.class.getClassLoader();
        JAXBContext jaxbContext = JAXBContext.newInstance("org.opennms.features.vaadin.pmatrix.model", cl);

        //JAXBContext jaxbContext = JAXBContext.newInstance("org.opennms.features.vaadin.pmatrix.model");

        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        PmatrixSpecificationList pmatrixSpecificationList_context = (PmatrixSpecificationList) appContext
                .getBean("pmatrixSpecificationList");
        //PmatrixSpecification pmatrixSpec_Context = (PmatrixSpecification) appContext.getBean("pmatrixSpecification");

        //System.out.println("list to be marshalled:");
        System.out.println(pmatrixSpecificationList_context);

        System.out.println("marshalled list:");
        //jaxbMarshaller.marshal(testDatalist, file);

        //jaxbMarshaller.marshal(pmatrixSpec, System.out); // works
        //jaxbMarshaller.marshal(pmatrixSpecificationList, System.out); //works

        //test of marshaling context data
        //jaxbMarshaller.marshal(pmatrixSpecificationList_context, System.out);
        jaxbMarshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,
                "http://xmlns.opennms.org/xsd/config/pmatrix pmatrixConfig.xsd");

        jaxbMarshaller.marshal(pmatrixSpecificationList_context, file);
        //jaxbMarshaller.marshal(pmatrixSpecificationList_context, file);

        //unmarshal test file

        Unmarshaller jaxbUnMarshaller = jaxbContext.createUnmarshaller();

        //Object o = jaxbUnMarshaller.unmarshal( new StringReader( marshalledXml )  );

        Object o = jaxbUnMarshaller.unmarshal(file);

        System.out.println("o.tostring:" + o.toString());
        if (o instanceof PmatrixSpecificationList) {
            System.out.println("unmarshalled list:");
            System.out.println((PmatrixSpecificationList) o);

        } else
            System.out.println("cant unmarshal object:");

    } catch (JAXBException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("end of test:testAppContext()");
}