Example usage for java.lang Object getClass

List of usage examples for java.lang Object getClass

Introduction

In this page you can find the example usage for java.lang Object getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.jasig.portlet.data.Exporter.java

public static void main(String[] args) throws Exception {
    String dir = args[0];/*from  w w  w.ja v  a 2  s.c  o  m*/
    String importExportContext = args[1];
    String sessionFactoryBeanName = args[2];
    String modelClassName = args[3];
    String serviceBeanName = args[4];
    String serviceBeanMethodName = args[5];

    ApplicationContext context = PortletApplicationContextLocator.getApplicationContext(importExportContext);
    SessionFactory sessionFactory = context.getBean(sessionFactoryBeanName, SessionFactory.class);
    Class<?> modelClass = Class.forName(modelClassName);

    Object service = context.getBean(serviceBeanName);
    Session session = sessionFactory.getCurrentSession();
    Transaction transaction = session.beginTransaction();

    JAXBContext jc = JAXBContext.newInstance(modelClass);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    Method method = service.getClass().getMethod(serviceBeanMethodName);
    List<?> objects = (List<?>) method.invoke(service, null);

    for (Object o : objects) {
        session.lock(o, LockMode.NONE);
        JAXBElement je2 = new JAXBElement(new QName(modelClass.getSimpleName().toLowerCase()), modelClass, o);
        String output = dir + File.separator + UUID.randomUUID().toString() + ".xml";
        try {
            marshaller.marshal(je2, new FileOutputStream(output));
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
    transaction.commit();
}

From source file:io.s4.comm.util.JSONUtil.java

public static void main(String[] args) {
    Map<String, Object> outerMap = new HashMap<String, Object>();

    outerMap.put("doubleValue", 0.3456d);
    outerMap.put("integerValue", 175647);
    outerMap.put("longValue", 0x0000005000067000l);
    outerMap.put("stringValue", "Hello there");

    Map<String, Object> innerMap = null;
    List<Map<String, Object>> innerList1 = new ArrayList<Map<String, Object>>();

    innerMap = new HashMap<String, Object>();
    innerMap.put("name", "kishore");
    innerMap.put("count", 1787265);
    innerList1.add(innerMap);//  w w w.ja  v a  2  s  . c o m
    innerMap = new HashMap<String, Object>();
    innerMap.put("name", "fred");
    innerMap.put("count", 11);
    innerList1.add(innerMap);

    outerMap.put("innerList1", innerList1);

    List<Integer> innerList2 = new ArrayList<Integer>();
    innerList2.add(65);
    innerList2.add(2387894);
    innerList2.add(456);

    outerMap.put("innerList2", innerList2);

    JSONObject jsonObject = toJSONObject(outerMap);

    String flatJSONString = null;
    try {
        System.out.println(jsonObject.toString(3));
        flatJSONString = jsonObject.toString();
        Object o = jsonObject.get("innerList1");
        if (!(o instanceof JSONArray)) {
            System.out.println("Unexpected type of list " + o.getClass().getName());
        } else {
            JSONArray jsonArray = (JSONArray) o;
            o = jsonArray.get(0);
            if (!(o instanceof JSONObject)) {
                System.out.println("Unexpected type of map " + o.getClass().getName());
            } else {
                JSONObject innerJSONObject = (JSONObject) o;
                System.out.println(innerJSONObject.get("name"));
            }
        }
    } catch (JSONException je) {
        je.printStackTrace();
    }

    if (!flatJSONString.equals(toJsonString(outerMap))) {
        System.out.println("JSON strings don't match!!");
    }

    Map<String, Object> map = getMapFromJson(flatJSONString);

    Object o = map.get("doubleValue");
    if (!(o instanceof Double)) {
        System.out.println("Expected type Double, got " + o.getClass().getName());
        Double doubleValue = (Double) o;
        if (doubleValue != 0.3456d) {
            System.out.println("Expected 0.3456, got " + doubleValue);
        }
    }

    o = map.get("innerList1");
    if (!(o instanceof List)) {
        System.out.println("Expected implementation of List, got " + o.getClass().getName());
    } else {
        List innerList = (List) o;
        o = innerList.get(0);
        if (!(o instanceof Map)) {
            System.out.println("Expected implementation of Map, got " + o.getClass().getName());
        } else {
            innerMap = (Map) o;
            System.out.println(innerMap.get("name"));
        }
    }
    System.out.println(map);
}

From source file:com.glaf.core.el.Mvel2ExpressionEvaluator.java

public static void main(String[] args) throws Exception {
    String expression = null;/* w ww .j  a v  a 2  s  . com*/
    Object obj = null;
    Map<String, Object> context = new java.util.HashMap<String, Object>();
    context.put("roleId", "admin");
    context.put("roleType", "-5");

    expression = "#{roleType > 0}";

    obj = Mvel2ExpressionEvaluator.evaluate(expression, context);
    if (obj != null) {
        System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
    }

    context.put("roleType", "2345");
    expression = "#{roleType > 0}";

    obj = Mvel2ExpressionEvaluator.evaluate(expression, context);
    if (obj != null) {
        System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
    }

    context.put("a", 123);
    context.put("b", 789);
    expression = "#{ a + b }";

    obj = Mvel2ExpressionEvaluator.evaluate(expression, context);
    if (obj != null) {
        System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
    }

    context.put("a", "123");
    context.put("b", "789");
    expression = "#{ a*1.0 + b*1.0 }";

    obj = Mvel2ExpressionEvaluator.evaluate(expression, context);
    if (obj != null) {
        System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
    }

    context.put("c", 123D);
    context.put("d", 789D);
    expression = "#{ c / d }";

    obj = Mvel2ExpressionEvaluator.evaluate(expression, context);
    if (obj != null) {
        System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
    }

    context.put("a", "123");
    context.put("b", "789");
    expression = "#{ a*1.0 / b*1.0 }";

    obj = Mvel2ExpressionEvaluator.evaluate(expression, context);
    if (obj != null) {
        System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
    }

    expression = "#{ c >= 0 and d >0 }";
    obj = Mvel2ExpressionEvaluator.evaluate(expression, context);
    if (obj != null) {
        System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
    }

    expression = "#{ c >= 0 and d > 0 and c/d > 0.16 }";
    obj = Mvel2ExpressionEvaluator.evaluate(expression, context);
    if (obj != null) {
        System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
    }

    expression = "#{ c >= 0 and d >0 and c/d > 0.15 }";
    obj = Mvel2ExpressionEvaluator.evaluate(expression, context);
    if (obj != null) {
        System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
    }

}

From source file:io.s4.MainApp.java

public static void main(String args[]) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c"));

    options.addOption(// w w w  . ja  v a  2  s  .  c o m
            OptionBuilder.withArgName("appshome").hasArg().withDescription("applications home").create("a"));

    options.addOption(OptionBuilder.withArgName("s4clock").hasArg().withDescription("s4 clock").create("d"));

    options.addOption(OptionBuilder.withArgName("seedtime").hasArg()
            .withDescription("event clock initialization time").create("s"));

    options.addOption(
            OptionBuilder.withArgName("extshome").hasArg().withDescription("extensions home").create("e"));

    options.addOption(
            OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i"));

    options.addOption(
            OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t"));

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;
    String clockType = "wall";

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    }

    int instanceId = -1;
    if (commandLine.hasOption("i")) {
        String instanceIdStr = commandLine.getOptionValue("i");
        try {
            instanceId = Integer.parseInt(instanceIdStr);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad instance id: %s" + instanceIdStr);
            System.exit(1);
        }
    }

    if (commandLine.hasOption("c")) {
        coreHome = commandLine.getOptionValue("c");
    }

    if (commandLine.hasOption("a")) {
        appsHome = commandLine.getOptionValue("a");
    }

    if (commandLine.hasOption("d")) {
        clockType = commandLine.getOptionValue("d");
    }

    if (commandLine.hasOption("e")) {
        extsHome = commandLine.getOptionValue("e");
    }

    String configType = "typical";
    if (commandLine.hasOption("t")) {
        configType = commandLine.getOptionValue("t");
    }

    long seedTime = 0;
    if (commandLine.hasOption("s")) {
        seedTime = Long.parseLong(commandLine.getOptionValue("s"));
    }

    File coreHomeFile = new File(coreHome);
    if (!coreHomeFile.isDirectory()) {
        System.err.println("Bad core home: " + coreHome);
        System.exit(1);
    }

    File appsHomeFile = new File(appsHome);
    if (!appsHomeFile.isDirectory()) {
        System.err.println("Bad applications home: " + appsHome);
        System.exit(1);
    }

    if (instanceId > -1) {
        System.setProperty("instanceId", "" + instanceId);
    } else {
        System.setProperty("instanceId", "" + S4Util.getPID());
    }

    List loArgs = commandLine.getArgList();

    if (loArgs.size() < 1) {
        // System.err.println("No bean configuration file specified");
        // System.exit(1);
    }

    // String s4ConfigXml = (String) loArgs.get(0);
    // System.out.println("s4ConfigXml is " + s4ConfigXml);

    ClassPathResource propResource = new ClassPathResource("s4-core.properties");
    Properties prop = new Properties();
    if (propResource.exists()) {
        prop.load(propResource.getInputStream());
    } else {
        System.err.println("Unable to find s4-core.properties. It must be available in classpath");
        System.exit(1);
    }

    ApplicationContext coreContext = null;
    String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType;
    String configPath = "";
    List<String> coreConfigUrls = new ArrayList<String>();
    File configFile = null;

    // load clock configuration
    configPath = configBase + File.separatorChar + clockType + "-clock.xml";
    coreConfigUrls.add(configPath);

    // load core config xml
    configPath = configBase + File.separatorChar + "s4-core-conf.xml";
    configFile = new File(configPath);
    if (!configFile.exists()) {
        System.err.printf("S4 core config file %s does not exist\n", configPath);
        System.exit(1);
    }

    coreConfigUrls.add(configPath);
    String[] coreConfigFiles = new String[coreConfigUrls.size()];
    coreConfigUrls.toArray(coreConfigFiles);

    String[] coreConfigFileUrls = new String[coreConfigFiles.length];
    for (int i = 0; i < coreConfigFiles.length; i++) {
        coreConfigFileUrls[i] = "file:" + coreConfigFiles[i];
    }

    coreContext = new FileSystemXmlApplicationContext(coreConfigFileUrls, coreContext);
    ApplicationContext context = coreContext;

    Clock s4Clock = (Clock) context.getBean("clock");
    if (s4Clock instanceof EventClock && seedTime > 0) {
        EventClock s4EventClock = (EventClock) s4Clock;
        s4EventClock.updateTime(seedTime);
        System.out.println("Intializing event clock time with seed time " + s4EventClock.getCurrentTime());
    }

    PEContainer peContainer = (PEContainer) context.getBean("peContainer");

    Watcher w = (Watcher) context.getBean("watcher");
    w.setConfigFilename(configPath);

    // load extension modules
    String[] configFileNames = getModuleConfigFiles(extsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
    }

    // load application modules
    configFileNames = getModuleConfigFiles(appsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
        // attach any beans that implement ProcessingElement to the PE
        // Container
        String[] processingElementBeanNames = context.getBeanNamesForType(ProcessingElement.class);
        for (String processingElementBeanName : processingElementBeanNames) {
            Object bean = context.getBean(processingElementBeanName);
            try {
                Method getS4ClockMethod = bean.getClass().getMethod("getS4Clock");

                if (getS4ClockMethod.getReturnType().equals(Clock.class)) {
                    if (getS4ClockMethod.invoke(bean) == null) {
                        Method setS4ClockMethod = bean.getClass().getMethod("setS4Clock", Clock.class);
                        setS4ClockMethod.invoke(bean, coreContext.getBean("clock"));
                    }
                }
            } catch (NoSuchMethodException mnfe) {
                // acceptable
            }
            System.out.println("Adding processing element with bean name " + processingElementBeanName + ", id "
                    + ((ProcessingElement) bean).getId());
            peContainer.addProcessor((ProcessingElement) bean, processingElementBeanName);
        }
    }
}

From source file:com.glaf.core.el.Jexl2ExpressionEvaluator.java

public static void main(String[] args) throws Exception {
    String expression = null;/*www  .  j av a 2 s . c o  m*/
    Object obj = null;
    Map<String, Object> context = new java.util.HashMap<String, Object>();
    context.put("roleId", "admin");
    context.put("roleType", "-5");

    expression = "#{roleType > 0}";

    obj = Jexl2ExpressionEvaluator.evaluate(expression, context);
    if (obj != null) {
        System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
    }

    context.put("roleType", "2345");
    expression = "#{roleType > 0}";

    obj = Jexl2ExpressionEvaluator.evaluate(expression, context);
    if (obj != null) {
        System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
    }

    context.put("a", 123);
    context.put("b", 789);
    expression = "#{ a + b }";

    obj = Jexl2ExpressionEvaluator.evaluate(expression, context);
    if (obj != null) {
        System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
    }

    context.put("a", "123");
    context.put("b", "789");
    expression = "#{ a*1.0 + b*1.0 }";

    obj = Jexl2ExpressionEvaluator.evaluate(expression, context);
    if (obj != null) {
        System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
    }

    context.put("c", 123D);
    context.put("d", 789D);
    expression = "#{ c / d }";

    obj = Jexl2ExpressionEvaluator.evaluate(expression, context);
    if (obj != null) {
        System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
    }

    context.put("a", "123");
    context.put("b", "789");
    expression = "#{ a*1.0 / b*1.0 }";

    obj = Jexl2ExpressionEvaluator.evaluate(expression, context);
    if (obj != null) {
        System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
    }

    expression = "#{ c >= 0 and d >0 }";
    obj = Jexl2ExpressionEvaluator.evaluate(expression, context);
    if (obj != null) {
        System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
    }

    expression = "#{ c >= 0 and d >0 and c/d > 0.16 }";
    obj = Jexl2ExpressionEvaluator.evaluate(expression, context);
    if (obj != null) {
        System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
    }

    expression = "#{ c >= 0 and d >0 and c/d > 0.15 }";
    obj = Jexl2ExpressionEvaluator.evaluate(expression, context);
    if (obj != null) {
        System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
    }

    expression = "#{ 0 > 10 }";
    obj = Jexl2ExpressionEvaluator.evaluate(expression, context);
    System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);

    expression = "#{ a +'-xy-'+ b }";
    obj = Jexl2ExpressionEvaluator.evaluate(expression, context);
    System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);

    expression = "#{ 0x10}";
    obj = Jexl2ExpressionEvaluator.evaluate(expression, context);
    System.out.println("[type]=" + obj.getClass().getName() + "\t[value]=" + obj);
}

From source file:de.uniko.west.winter.test.basics.JenaTests.java

public static void main(String[] args) {

    Model newModel = ModelFactory.createDefaultModel();
    //      //from   w w  w  . j  a  v a  2  s . com
    Model newModel2 = ModelFactory.createModelForGraph(ModelFactory.createMemModelMaker().getGraphMaker()
            .createGraph("http://www.defaultgraph.de/graph1"));
    StringBuilder updateString = new StringBuilder();
    updateString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>");
    updateString.append("PREFIX xsd: <http://bla.org/dc/elements/1.1/>");
    updateString.append("INSERT { ");
    updateString.append(
            "<http://example/egbook1> dc:title  <http://example/egbook1/#Title1>, <http://example/egbook1/#Title2>. ");
    //updateString.append("<http://example/egbook1> dc:title  \"Title1.1\". ");
    //updateString.append("<http://example/egbook1> dc:title  \"Title1.2\". ");
    updateString.append("<http://example/egbook21> dc:title  \"Title2\"; ");
    updateString.append("dc:title  \"2.0\"^^xsd:double. ");
    updateString.append("<http://example/egbook3> dc:title  \"Title3\". ");
    updateString.append("<http://example/egbook4> dc:title  \"Title4\". ");
    updateString.append("<http://example/egbook5> dc:title  \"Title5\". ");
    updateString.append("<http://example/egbook6> dc:title  \"Title6\" ");
    updateString.append("}");

    UpdateRequest update = UpdateFactory.create(updateString.toString());
    UpdateAction.execute(update, newModel);

    StmtIterator iter = newModel.listStatements();
    System.out.println("After add");
    while (iter.hasNext()) {
        System.out.println(iter.next().toString());

    }

    StringBuilder constructQueryString = new StringBuilder();
    constructQueryString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>");
    constructQueryString.append("CONSTRUCT {?sub dc:title <http://example/egbook1/#Title1>}");
    constructQueryString.append("WHERE {");
    constructQueryString.append("?sub dc:title <http://example/egbook1/#Title1>");
    constructQueryString.append("}");

    StringBuilder askQueryString = new StringBuilder();
    askQueryString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>");
    askQueryString.append("ASK {");
    askQueryString.append("?sub dc:title <http://example/egbook1/#Title1>");
    askQueryString.append("}");

    StringBuilder selectQueryString = new StringBuilder();
    selectQueryString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>");
    selectQueryString.append("SELECT * ");
    selectQueryString.append("WHERE {");
    selectQueryString.append("?sub ?pred ?obj");
    selectQueryString.append("}");

    Query cquery = QueryFactory.create(constructQueryString.toString());
    System.out.println(cquery.getQueryType());
    Query aquery = QueryFactory.create(askQueryString.toString());
    System.out.println(aquery.getQueryType());
    Query query = QueryFactory.create(selectQueryString.toString());
    System.out.println(query.getQueryType());
    QueryExecution queryExecution = QueryExecutionFactory.create(query, newModel);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    URI test = null;
    try {
        test = new URI("http://bla.org/dc/elements/1.1/double");
    } catch (URISyntaxException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    System.out.println(test.getPath().toString().substring(test.getPath().lastIndexOf("/") + 1));
    System.out.println("java.lang."
            + test.getPath().toString().substring(test.getPath().lastIndexOf("/") + 1).substring(0, 1)
                    .toUpperCase()
            + test.getPath().toString().substring(test.getPath().lastIndexOf("/") + 1).substring(1));

    String typ = "java.lang.Boolean";
    String val = "true";

    try {
        Object typedLiteral = Class.forName(typ, true, ClassLoader.getSystemClassLoader())
                .getConstructor(String.class).newInstance(val);

        System.out.println("Type: " + typedLiteral.getClass().getName() + " Value: " + typedLiteral);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        System.out.println("Query...");
        com.hp.hpl.jena.query.ResultSet results = queryExecution.execSelect();
        System.out.println("RESULT:");
        ResultSetFormatter.output(System.out, results, ResultSetFormat.syntaxJSON);
        //         
        //         
        //         ResultSetFormatter.outputAsJSON(baos, results);
        //         System.out.println(baos.toString());
        //         System.out.println("JsonTest: ");
        //         JSONObject result = new JSONObject(baos.toString("ISO-8859-1"));
        //         for (Iterator key = result.keys(); result.keys().hasNext(); ){
        //            System.out.println(key.next());
        //            
        //            for (Iterator key2 = ((JSONObject)result.getJSONObject("head")).keys(); key2.hasNext(); ){
        //               System.out.println(key2.next());
        //            }
        //         }

        //         Model results = queryExecution.execConstruct();

        //         results.write(System.out, "TURTLE");
        //         for ( ; results.hasNext() ; ){
        //            QuerySolution soln = results.nextSolution() ;
        //            RDFNode x = soln.get("sub") ;   
        //            System.out.println("result: "+soln.get("sub")+" hasTitle "+soln.get("obj"));
        //             Resource r = soln.getResource("VarR") ; 
        //             Literal l = soln.getLiteral("VarL") ; 
        //
        //         }

    } catch (Exception e) {
        // TODO: handle exception
    }

    //      StringBuilder updateString2 = new StringBuilder();
    //      updateString2.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>");
    //      updateString2.append("DELETE DATA { ");
    //      updateString2.append("<http://example/egbook3> dc:title  \"Title3\" ");
    //      updateString2.append("}");
    //
    //      UpdateAction.parseExecute(updateString2.toString(), newModel);
    //      
    //      iter = newModel.listStatements();
    //      System.out.println("After delete");
    //      while (iter.hasNext()) {
    //         System.out.println(iter.next().toString());
    //            
    //      }
    //      
    //      StringBuilder updateString3 = new StringBuilder();
    //      updateString3.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>");
    //      updateString3.append("DELETE DATA { ");
    //      updateString3.append("<http://example/egbook6> dc:title  \"Title6\" ");
    //      updateString3.append("}");
    //      updateString3.append("INSERT { ");
    //      updateString3.append("<http://example/egbook6> dc:title  \"New Title6\" ");
    //      updateString3.append("}");
    //   
    //      UpdateAction.parseExecute(updateString3.toString(), newModel);

    //      UpdateAction.parseExecute(   "prefix exp: <http://www.example.de>"+
    //                           "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>"+
    //                           "INSERT { graph <http://www.defaultgraph.de/graph1> {"+
    //                           "   <http://www.test.de#substructure1> <exp:has_relation3> <http://www.test.de#substructure2> ."+ 
    //                           "   <http://www.test.de#substructure1> <rdf:type> <http://www.test.de#substructuretype1> ."+ 
    //                           "   <http://www.test.de#substructure2> <rdf:type> <http://www.test.de#substructuretype2> ."+
    //                           "}}", newModel2);
    //      
    //      iter = newModel.listStatements();
    //      System.out.println("After update");
    //      while (iter.hasNext()) {
    //         System.out.println(iter.next().toString());
    //            
    //      }
}

From source file:com.atilika.kuromoji.benchmark.Benchmark.java

public static void main(String[] args) throws IOException {
    Options options = new Options();
    options.addOption("h", "help", false, "Display this help message and exit");
    options.addOption("t", "tokenizer", true, "Tokenizer class to use");
    options.addOption("u", "user-dictionary", true, "Optional user dictionary filename to use");
    options.addOption("c", "count", true, "Number of documents ot process (Default: 0, which means all");
    //        options.addOption("v", "validation-input", true, "Validation filename");
    options.addOption("o", "output", true,
            "Output filename.  If unset, segmentation is done, but the result is discarded");
    options.addOption("n", "n-best", true, "The number of tokenizations to get per input");
    options.addOption(null, "benchmark-output", true, "Benchmark metrics output filename filename");

    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine = null;/*  www . j  a  v  a  2 s . com*/
    try {
        commandLine = parser.parse(options, args);

        args = commandLine.getArgs();

        if (args.length != 1) {
            throw new ParseException("A single input filename is required");
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        usage(options);
    }

    String inputFilename = args[0];

    String className = commandLine.getOptionValue("t", "com.atilika.kuromoji.ipadic.Tokenizer");

    className += "$Builder";

    String userDictionaryFilename = commandLine.getOptionValue("u");

    TokenizerBase tokenizer = null;
    try {
        Class clazz = Class.forName(className);

        // Make builder
        Object builder = clazz.getDeclaredConstructor(null).newInstance();

        // Set user dictionary
        if (userDictionaryFilename != null) {
            builder.getClass().getMethod("userDictionary", String.class).invoke(builder,
                    userDictionaryFilename);
        }

        // Build tokenizer
        tokenizer = (TokenizerBase) builder.getClass().getMethod("build").invoke(builder);

    } catch (Exception e) {
        System.err.println("Could not create tokenizer. Got " + e);
        e.printStackTrace();
        System.exit(1);
    }

    File outputFile = null;
    String outputFilename = commandLine.getOptionValue("o");

    if (outputFilename != null) {
        outputFile = new File(outputFilename);
    }

    File statisticsFile = null;
    String statisticsFilename = commandLine.getOptionValue("benchmark-output");

    if (statisticsFilename != null) {
        statisticsFile = new File(statisticsFilename);
    }

    long count = Long.parseLong(commandLine.getOptionValue("c", "0"));

    int nbest = Integer.parseInt(commandLine.getOptionValue("n", "1"));

    Benchmark benchmark = new Builder().tokenizer(tokenizer).inputFile(new File(inputFilename))
            .outputFile(outputFile).outputStatisticsFile(statisticsFile).setOutputStatistiscs(true).count(count)
            .nbest(nbest).build();

    benchmark.benchmark();
}

From source file:org.red5.client.net.remoting.DSRemotingClient.java

@SuppressWarnings("rawtypes")
public static void main(String[] args) {
    //blazeds my-polling-amf http://localhost:8400/meta/messagebroker/amfpolling
    DSRemotingClient client = new DSRemotingClient("http://localhost:8400/meta/messagebroker/amfpolling");
    try {/*from   ww w  .  j a va  2  s  .  c  om*/
        client.afterPropertiesSet();
        //send ping
        CommandMessage msg = new CommandMessage();
        msg.setCorrelationId("");
        msg.setDestination("");
        //create / set headers
        ObjectMap<String, Object> headerMap = new ObjectMap<String, Object>();
        headerMap.put(Message.FLEX_CLIENT_ID_HEADER, "nil");
        headerMap.put(Message.MESSAGING_VERSION, 1);
        msg.setHeaders(headerMap);
        msg.setOperation(Constants.CLIENT_PING_OPERATION);
        msg.setBody(new Object[] {});

        Object response = client.invokeMethod("null", new Object[] { msg });
        log.debug("Response: {}\n{}", response.getClass().getName(), response);
        if (response instanceof AcknowledgeMessage || response instanceof AcknowledgeMessageExt) {
            log.info("Got first ACK");
            AcknowledgeMessage ack = (AcknowledgeMessage) response;
            Object id = ack.getHeader(Message.FLEX_CLIENT_ID_HEADER);
            if (id != null) {
                log.info("Got DSId: {}", id);
                client.setDataSourceId((String) id);
            }
        }
        //wait a second for a dsid
        do {
            Thread.sleep(1000);
            log.info("Done with sleeping");
        } while (client.getDataSourceId().equals("nil"));
        //send subscribe
        msg = new CommandMessage();
        msg.setCorrelationId("");
        msg.setDestination("Red5Chat");
        headerMap = new ObjectMap<String, Object>();
        headerMap.put(Message.FLEX_CLIENT_ID_HEADER, client.getDataSourceId());
        headerMap.put(Message.ENDPOINT_HEADER, "my-polling-amf");
        msg.setHeaders(headerMap);
        msg.setOperation(Constants.SUBSCRIBE_OPERATION);
        msg.setBody(new Object[] {});

        response = client.invokeMethod("null", new Object[] { msg });

        if (response instanceof AcknowledgeMessage || response instanceof AcknowledgeMessageExt) {
            log.info("Got second ACK {}", ((AcknowledgeMessage) response));
        }

        //poll every 5 seconds for 60
        int loop = 12;
        do {
            Thread.sleep(5000);
            log.info("Done with sleeping");
            //send poll 
            //0 messages - returns DSK
            //n messages - CommandMessage with internal DSA
            msg = new CommandMessage();
            msg.setCorrelationId("");
            msg.setDestination("Red5Chat");
            headerMap = new ObjectMap<String, Object>();
            headerMap.put(Message.FLEX_CLIENT_ID_HEADER, client.getDataSourceId());
            msg.setHeaders(headerMap);
            msg.setOperation(Constants.POLL_OPERATION);
            msg.setBody(new Object[] {});

            response = client.invokeMethod("null", new Object[] { msg });
            if (response instanceof AcknowledgeMessage) {
                AcknowledgeMessage ack = (AcknowledgeMessage) response;
                log.info("Got ACK response {}", ack);
            } else if (response instanceof CommandMessage) {
                CommandMessage com = (CommandMessage) response;
                log.info("Got COM response {}", com);
                ArrayList list = (ArrayList) com.getBody();
                log.info("Child message body: {}", ((AsyncMessageExt) list.get(0)).getBody());
            }
        } while (--loop > 0);

    } catch (Exception e) {
        log.warn("Exception {}", e);
    }
}

From source file:com.artistech.tuio.mouse.ZeroMqMouse.java

/**
 * Main entry point for ZeroMQ integration.
 *
 * @param args// w  ww .  j av  a2s  .  co m
 * @throws AWTException
 * @throws java.io.IOException
 */
public static void main(String[] args) throws AWTException, java.io.IOException {
    //read off the TUIO port from the command line
    String zeromq_port;

    Options options = new Options();
    options.addOption("z", "zeromq-port", true, "ZeroMQ Server:Port to subscribe to. (-z localhost:5565)");
    options.addOption("h", "help", false, "Show this message.");
    HelpFormatter formatter = new HelpFormatter();

    try {
        CommandLineParser parser = new org.apache.commons.cli.BasicParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            formatter.printHelp("tuio-mouse-driver", options);
            return;
        } else {
            if (cmd.hasOption("z") || cmd.hasOption("zeromq-port")) {
                zeromq_port = cmd.getOptionValue("z");
            } else {
                System.err.println("The zeromq-port value must be specified.");
                formatter.printHelp("tuio-mouse-driver", options);
                return;
            }
        }
    } catch (ParseException ex) {
        System.err.println("Error Processing Command Options:");
        formatter.printHelp("tuio-mouse-driver", options);
        return;
    }

    //load conversion services
    ServiceLoader<ProtoConverter> services = ServiceLoader.load(ProtoConverter.class);

    //create zeromq context
    ZMQ.Context context = ZMQ.context(1);

    // Connect our subscriber socket
    ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
    subscriber.setIdentity(ZeroMqMouse.class.getName().getBytes());

    //this could change I guess so we can get different data subscrptions.
    subscriber.subscribe("TuioCursor".getBytes());
    //        subscriber.subscribe("TuioTime".getBytes());
    subscriber.connect("tcp://" + zeromq_port);

    System.out.println("Subscribed to " + zeromq_port + " for ZeroMQ messages.");

    // Get updates, expect random Ctrl-C death
    String msg = "";
    MouseDriver md = new MouseDriver();
    while (!msg.equalsIgnoreCase("END")) {
        boolean success = false;
        byte[] recv = subscriber.recv();

        com.google.protobuf.GeneratedMessage message = null;
        TuioPoint pt = null;
        String type = recv.length > 0 ? new String(recv) : "";
        recv = subscriber.recv();
        switch (type) {
        case "TuioCursor.PROTOBUF":
            try {
                //it is a cursor?
                message = com.artistech.protobuf.TuioProtos.Cursor.parseFrom(recv);
                success = true;
            } catch (Exception ex) {
            }
            break;
        case "TuioTime.PROTOBUF":
            //                    try {
            //                        //it is a cursor?
            //                        message = com.artistech.protobuf.TuioProtos.Time.parseFrom(recv);
            //                        success = true;
            //                    } catch (Exception ex) {
            //                    }
            break;
        case "TuioObject.PROTOBUF":
            try {
                //it is a cursor?
                message = com.artistech.protobuf.TuioProtos.Object.parseFrom(recv);
                success = true;
            } catch (Exception ex) {
            }
            break;
        case "TuioBlob.PROTOBUF":
            try {
                //it is a cursor?
                message = com.artistech.protobuf.TuioProtos.Blob.parseFrom(recv);
                success = true;
            } catch (Exception ex) {
            }
            break;
        case "TuioCursor.JSON":
            try {
                //it is a cursor?
                pt = mapper.readValue(recv, TUIO.TuioCursor.class);
                success = true;
            } catch (Exception ex) {
            }
            break;
        case "TuioTime.JSON":
            //                    try {
            //                        //it is a cursor?
            //                        pt = mapper.readValue(recv, TUIO.TuioTime.class);
            //                        success = true;
            //                    } catch (Exception ex) {
            //                    }
            break;
        case "TuioObject.JSON":
            try {
                //it is a cursor?
                pt = mapper.readValue(recv, TUIO.TuioObject.class);
                success = true;
            } catch (Exception ex) {
            }
            break;
        case "TuioBlob.JSON":
            try {
                //it is a cursor?
                pt = mapper.readValue(recv, TUIO.TuioBlob.class);
                success = true;
            } catch (Exception ex) {
            }
            break;
        case "TuioTime.OBJECT":
            break;
        case "TuioCursor.OBJECT":
        case "TuioObject.OBJECT":
        case "TuioBlob.OBJECT":
            try {
                //Try reading the data as a serialized Java object:
                try (ByteArrayInputStream bis = new ByteArrayInputStream(recv)) {
                    //Try reading the data as a serialized Java object:
                    ObjectInput in = new ObjectInputStream(bis);
                    Object o = in.readObject();
                    //if it is of type Point (Cursor, Object, Blob), process:
                    if (TuioPoint.class.isAssignableFrom(o.getClass())) {
                        pt = (TuioPoint) o;
                        process(pt, md);
                    }

                    success = true;
                }
            } catch (java.io.IOException | ClassNotFoundException ex) {
            } finally {
            }
            break;
        default:
            success = false;
            break;
        }

        if (message != null && success) {
            //ok, so we have a message that is not null, so it was protobuf:
            Object o = null;

            //look for a converter that will suppor this objec type and convert:
            for (ProtoConverter converter : services) {
                if (converter.supportsConversion(message)) {
                    o = converter.convertFromProtobuf(message);
                    break;
                }
            }

            //if the type is of type Point (Cursor, Blob, Object), process:
            if (o != null && TuioPoint.class.isAssignableFrom(o.getClass())) {
                pt = (TuioPoint) o;
            }
        }

        if (pt != null) {
            process(pt, md);
        }
    }
}

From source file:edu.harvard.med.iccbl.dev.HibernateConsole.java

public static void main(String[] args) {
    BufferedReader br = null;//from   w ww.  ja  v a  2  s  . c  om
    try {
        CommandLineApplication app = new CommandLineApplication(args);
        app.processOptions(true, false);
        br = new BufferedReader(new InputStreamReader(System.in));

        EntityManagerFactory emf = (EntityManagerFactory) app.getSpringBean("entityManagerFactory");
        EntityManager em = emf.createEntityManager();

        do {
            System.out.println("Enter HQL query (blank to quit): ");
            String input = br.readLine();
            if (input.length() == 0) {
                System.out.println("Goodbye!");
                System.exit(0);
            }
            try {
                List list = ((Session) em.getDelegate()).createQuery(input).list(); // note: this uses the Hibernate Session object, to allow HQL (and JPQL)
                // List list = em.createQuery(input).getResultList();  // note: this JPA method supports JPQL

                System.out.println("Result:");
                for (Iterator iter = list.iterator(); iter.hasNext();) {
                    Object item = iter.next();
                    // format output from multi-item selects ("select a, b, c, ... from ...")
                    if (item instanceof Object[]) {
                        List<Object> fields = Arrays.asList((Object[]) item);
                        System.out.println(StringUtils.makeListString(fields, ", "));
                    }
                    // format output from single-item selected ("select a from ..." or "from ...")
                    else {
                        System.out.println("[" + item.getClass().getName() + "]: " + item);
                    }
                }
                System.out.println("(" + list.size() + " rows)\n");
            } catch (Exception e) {
                System.out.println("Hibernate Error: " + e.getMessage());
                log.error("Hibernate error", e);
            }
            System.out.println();
        } while (true);
    } catch (Exception e) {
        System.err.println("Fatal Error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(br);
    }
}