Search in sources :

Example 26 with PrintWriter

use of java.io.PrintWriter in project groovy by apache.

the class GroovyScriptEngineImpl method eval.

// package-privates
Object eval(Class<?> scriptClass, final ScriptContext ctx) throws ScriptException {
    /*
         * We use the following Binding instance so that global variable lookup
         * will be done in the current ScriptContext instance.
         */
    Binding binding = new Binding(ctx.getBindings(ScriptContext.ENGINE_SCOPE)) {

        @Override
        public Object getVariable(String name) {
            synchronized (ctx) {
                int scope = ctx.getAttributesScope(name);
                if (scope != -1) {
                    return ctx.getAttribute(name, scope);
                }
                // Redirect script output to context writer, if out var is not already provided
                if ("out".equals(name)) {
                    Writer writer = ctx.getWriter();
                    if (writer != null) {
                        return (writer instanceof PrintWriter) ? (PrintWriter) writer : new PrintWriter(writer, true);
                    }
                }
                // Provide access to engine context, if context var is not already provided
                if ("context".equals(name)) {
                    return ctx;
                }
            }
            throw new MissingPropertyException(name, getClass());
        }

        @Override
        public void setVariable(String name, Object value) {
            synchronized (ctx) {
                int scope = ctx.getAttributesScope(name);
                if (scope == -1) {
                    scope = ScriptContext.ENGINE_SCOPE;
                }
                ctx.setAttribute(name, value, scope);
            }
        }
    };
    try {
        // then simply return that class
        if (!Script.class.isAssignableFrom(scriptClass)) {
            return scriptClass;
        } else {
            // it's a script
            Script scriptObject = InvokerHelper.createScript(scriptClass, binding);
            // save all current closures into global closures map
            Method[] methods = scriptClass.getMethods();
            for (Method m : methods) {
                String name = m.getName();
                globalClosures.put(name, new MethodClosure(scriptObject, name));
            }
            MetaClass oldMetaClass = scriptObject.getMetaClass();
            /*
                * We override the MetaClass of this script object so that we can
                * forward calls to global closures (of previous or future "eval" calls)
                * This gives the illusion of working on the same "global" scope.
                */
            scriptObject.setMetaClass(new DelegatingMetaClass(oldMetaClass) {

                @Override
                public Object invokeMethod(Object object, String name, Object args) {
                    if (args == null) {
                        return invokeMethod(object, name, MetaClassHelper.EMPTY_ARRAY);
                    }
                    if (args instanceof Tuple) {
                        return invokeMethod(object, name, ((Tuple) args).toArray());
                    }
                    if (args instanceof Object[]) {
                        return invokeMethod(object, name, (Object[]) args);
                    } else {
                        return invokeMethod(object, name, new Object[] { args });
                    }
                }

                @Override
                public Object invokeMethod(Object object, String name, Object[] args) {
                    try {
                        return super.invokeMethod(object, name, args);
                    } catch (MissingMethodException mme) {
                        return callGlobal(name, args, ctx);
                    }
                }

                @Override
                public Object invokeStaticMethod(Object object, String name, Object[] args) {
                    try {
                        return super.invokeStaticMethod(object, name, args);
                    } catch (MissingMethodException mme) {
                        return callGlobal(name, args, ctx);
                    }
                }
            });
            return scriptObject.run();
        }
    } catch (Exception e) {
        throw new ScriptException(e);
    }
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script) CompiledScript(javax.script.CompiledScript) MissingPropertyException(groovy.lang.MissingPropertyException) Method(java.lang.reflect.Method) MethodClosure(org.codehaus.groovy.runtime.MethodClosure) MissingPropertyException(groovy.lang.MissingPropertyException) ScriptException(javax.script.ScriptException) MissingMethodException(groovy.lang.MissingMethodException) IOException(java.io.IOException) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) ScriptException(javax.script.ScriptException) MissingMethodException(groovy.lang.MissingMethodException) MetaClass(groovy.lang.MetaClass) DelegatingMetaClass(groovy.lang.DelegatingMetaClass) DelegatingMetaClass(groovy.lang.DelegatingMetaClass) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) Tuple(groovy.lang.Tuple) PrintWriter(java.io.PrintWriter)

Example 27 with PrintWriter

use of java.io.PrintWriter in project hadoop by apache.

the class JMXJsonServlet method doGet.

/**
   * Process a GET request for the specified resource.
   * 
   * @param request
   *          The servlet request we are processing
   * @param response
   *          The servlet response we are creating
   */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
    try {
        // If user is a static user and auth Type is null, that means
        // there is a non-security environment and no need authorization,
        // otherwise, do the authorization.
        final ServletContext servletContext = getServletContext();
        if (!HttpServer2.isStaticUserAndNoneAuthType(servletContext, request) && !isInstrumentationAccessAllowed(request, response)) {
            return;
        }
        JsonGenerator jg = null;
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            response.setContentType("application/json; charset=utf8");
            response.setHeader(ACCESS_CONTROL_ALLOW_METHODS, "GET");
            response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
            jg = jsonFactory.createGenerator(writer);
            jg.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
            jg.useDefaultPrettyPrinter();
            jg.writeStartObject();
            // query per mbean attribute
            String getmethod = request.getParameter("get");
            if (getmethod != null) {
                String[] splitStrings = getmethod.split("\\:\\:");
                if (splitStrings.length != 2) {
                    jg.writeStringField("result", "ERROR");
                    jg.writeStringField("message", "query format is not as expected.");
                    jg.flush();
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    return;
                }
                listBeans(jg, new ObjectName(splitStrings[0]), splitStrings[1], response);
                return;
            }
            // query per mbean
            String qry = request.getParameter("qry");
            if (qry == null) {
                qry = "*:*";
            }
            listBeans(jg, new ObjectName(qry), null, response);
        } finally {
            if (jg != null) {
                jg.close();
            }
            if (writer != null) {
                writer.close();
            }
        }
    } catch (IOException e) {
        LOG.error("Caught an exception while processing JMX request", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (MalformedObjectNameException e) {
        LOG.error("Caught an exception while processing JMX request", e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}
Also used : MalformedObjectNameException(javax.management.MalformedObjectNameException) ServletContext(javax.servlet.ServletContext) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) IOException(java.io.IOException) PrintWriter(java.io.PrintWriter) ObjectName(javax.management.ObjectName)

Example 28 with PrintWriter

use of java.io.PrintWriter in project flink by apache.

the class PlanJSONDumpGenerator method dumpOptimizerPlanAsJSON.

public void dumpOptimizerPlanAsJSON(OptimizedPlan plan, File toFile) throws IOException {
    PrintWriter pw = null;
    try {
        pw = new PrintWriter(new FileOutputStream(toFile), false);
        dumpOptimizerPlanAsJSON(plan, pw);
        pw.flush();
    } finally {
        if (pw != null) {
            pw.close();
        }
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) PrintWriter(java.io.PrintWriter)

Example 29 with PrintWriter

use of java.io.PrintWriter in project flink by apache.

the class PlanJSONDumpGenerator method getOptimizerPlanAsJSON.

public String getOptimizerPlanAsJSON(OptimizedPlan plan) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    dumpOptimizerPlanAsJSON(plan, pw);
    pw.close();
    return sw.toString();
}
Also used : StringWriter(java.io.StringWriter) PrintWriter(java.io.PrintWriter)

Example 30 with PrintWriter

use of java.io.PrintWriter in project hadoop by apache.

the class FsckServlet method doGet.

/** Handle fsck request */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    @SuppressWarnings("unchecked") final Map<String, String[]> pmap = request.getParameterMap();
    final PrintWriter out = response.getWriter();
    final InetAddress remoteAddress = InetAddress.getByName(request.getRemoteAddr());
    final ServletContext context = getServletContext();
    final Configuration conf = NameNodeHttpServer.getConfFromContext(context);
    final UserGroupInformation ugi = getUGI(request, conf);
    try {
        ugi.doAs(new PrivilegedExceptionAction<Object>() {

            @Override
            public Object run() throws Exception {
                NameNode nn = NameNodeHttpServer.getNameNodeFromContext(context);
                final FSNamesystem namesystem = nn.getNamesystem();
                final BlockManager bm = namesystem.getBlockManager();
                final int totalDatanodes = namesystem.getNumberOfDatanodes(DatanodeReportType.LIVE);
                new NamenodeFsck(conf, nn, bm.getDatanodeManager().getNetworkTopology(), pmap, out, totalDatanodes, remoteAddress).fsck();
                return null;
            }
        });
    } catch (InterruptedException e) {
        response.sendError(400, e.getMessage());
    }
}
Also used : Configuration(org.apache.hadoop.conf.Configuration) IOException(java.io.IOException) BlockManager(org.apache.hadoop.hdfs.server.blockmanagement.BlockManager) ServletContext(javax.servlet.ServletContext) InetAddress(java.net.InetAddress) PrintWriter(java.io.PrintWriter) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation)

Aggregations

PrintWriter (java.io.PrintWriter)3529 StringWriter (java.io.StringWriter)1062 IOException (java.io.IOException)653 File (java.io.File)532 Test (org.junit.Test)432 FileOutputStream (java.io.FileOutputStream)293 FileWriter (java.io.FileWriter)274 OutputStreamWriter (java.io.OutputStreamWriter)255 BufferedReader (java.io.BufferedReader)180 ArrayList (java.util.ArrayList)171 HttpServletResponse (javax.servlet.http.HttpServletResponse)141 ByteArrayOutputStream (java.io.ByteArrayOutputStream)139 FastPrintWriter (com.android.internal.util.FastPrintWriter)124 InputStreamReader (java.io.InputStreamReader)123 HttpServletRequest (javax.servlet.http.HttpServletRequest)121 Date (java.util.Date)120 HashMap (java.util.HashMap)113 Map (java.util.Map)106 BufferedWriter (java.io.BufferedWriter)105 Writer (java.io.Writer)87