コード例 #1
0
  /**
   * Loads the specified file with one of the loaders registered with this ModelLoaderRegistry. Uses
   * the extension to determine which loader to use. The comparison of extensions is done case
   * insensitive.
   *
   * @param file the file to be loaded
   * @param hints the {@link ModelLoaderHints} to use
   * @return the {@link Model}
   * @throws GdxRuntimeException in case the model could not be loaded.
   */
  public static Model load(FileHandle file, ModelLoaderHints hints) {
    String name = file.name();
    int dotIndex = name.lastIndexOf('.');
    if (dotIndex == -1)
      throw new GdxRuntimeException(
          "file '"
              + file.name()
              + "' does not have an extension that can be matched to a ModelLoader");
    String extension = name.substring(dotIndex + 1).toLowerCase();

    Array<ModelLoader> loaders = ModelLoaderRegistry.loaders.get(extension);
    if (loaders == null)
      throw new GdxRuntimeException("no loaders for extension '" + extension + "'");

    Model model = null;
    StringBuilder errors = new StringBuilder();
    for (int i = 0; i < loaders.size; i++) {
      ModelLoader loader = loaders.get(i);
      try {
        model = loader.load(file, hints);
      } catch (GdxRuntimeException e) {
        errors.append(
            "Couldn't load '"
                + file.name()
                + "' with loader of type "
                + loader.getClass().getSimpleName()
                + ": "
                + e.getMessage()
                + "\n");
      }
    }

    if (model == null) throw new GdxRuntimeException(errors.toString());
    else return model;
  }
コード例 #2
0
  // here we create macros listing
  private String makeMacros(
      GridTransferContainer container, String script, String type, String backend) {
    String text = "";
    if (type.equalsIgnoreCase("input")) {
      text += JobGenerator.SOURCE_SCRIPT + "\n";

      Vector<String> nameInputs = loader.findFlagValues(script, ModelLoader.FLAG_INPUTS);
      Hashtable<String, String> inputs = container.getInputs();

      for (String s : nameInputs) {
        String macroline = makeMacroLine(s, inputs, type, backend);
        text += macroline;
      }

      Vector<String> nameExes = loader.findFlagValues(script, ModelLoader.FLAG_EXES);
      Hashtable<String, String> exes = container.getExes();

      for (String s : nameExes) {
        String macroline = makeMacroLine(s, exes, JobGenerator.EXE, backend);
        text += macroline;
      }

    } else if (type.equalsIgnoreCase("output")) {
      text += "\n";

      Vector<String> nameOutputs = loader.findFlagValues(script, ModelLoader.FLAG_OUTPUTS);
      Hashtable<String, String> outputs = container.getOutputs();
      for (String s : nameOutputs) {
        String macroline = makeMacroLine(s, outputs, type, backend);
        text += macroline;
      }
    }
    return text;
  }
コード例 #3
0
  /** change own namespace. */
  @Test
  public void namespace() {
    ModelLoader loader = generate();
    loader.setNamespace("other");
    ModelWrapper object = loader.newModel("Simple");

    object.set("value", 100);
    assertThat(object.get("value"), eq(100));
  }
コード例 #4
0
  /**
   * input/output simple records.
   *
   * @throws Exception if test was failed
   */
  @SuppressWarnings("unchecked")
  @Test
  public void simple_record() throws Exception {
    ModelLoader loader = generate();

    Class<?> type = loader.modelType("Simple");
    assertThat(type.isAnnotationPresent(ModelInputLocation.class), is(true));
    assertThat(type.isAnnotationPresent(ModelOutputLocation.class), is(true));

    ModelWrapper object = loader.newModel("Simple");
    DataOutputBuffer output = new DataOutputBuffer();
    ModelOutput<Object> modelOut =
        (ModelOutput<Object>)
            type.getAnnotation(ModelOutputLocation.class)
                .value()
                .getDeclaredConstructor(RecordEmitter.class)
                .newInstance(new TsvEmitter(new OutputStreamWriter(output, "UTF-8")));

    object.set("sid", 1L);
    object.set("value", new Text("hello"));
    modelOut.write(object.unwrap());

    object.set("sid", 2L);
    object.set("value", new Text("world"));
    modelOut.write(object.unwrap());

    object.set("sid", 3L);
    object.set("value", null);
    modelOut.write(object.unwrap());
    modelOut.close();

    DataInputBuffer input = new DataInputBuffer();
    input.reset(output.getData(), output.getLength());
    ModelInput<Object> modelIn =
        (ModelInput<Object>)
            type.getAnnotation(ModelInputLocation.class)
                .value()
                .getDeclaredConstructor(RecordParser.class)
                .newInstance(new TsvParser(new InputStreamReader(input, "UTF-8")));
    ModelWrapper copy = loader.newModel("Simple");

    modelIn.readTo(copy.unwrap());
    assertThat(copy.get("sid"), is((Object) 1L));
    assertThat(copy.get("value"), is((Object) new Text("hello")));

    modelIn.readTo(copy.unwrap());
    assertThat(copy.get("sid"), is((Object) 2L));
    assertThat(copy.get("value"), is((Object) new Text("world")));

    modelIn.readTo(copy.unwrap());
    assertThat(copy.get("sid"), is((Object) 3L));
    assertThat(copy.getOption("value").isNull(), is(true));

    assertThat(input.read(), is(-1));
    modelIn.close();
  }
コード例 #5
0
  /**
   * all primitive types.
   *
   * @throws Exception if test was failed
   */
  @SuppressWarnings("unchecked")
  @Test
  public void primitives() throws Exception {
    ModelLoader loader = generate();

    Class<?> type = loader.modelType("Primitives");
    assertThat(type.isAnnotationPresent(ModelInputLocation.class), is(true));
    assertThat(type.isAnnotationPresent(ModelOutputLocation.class), is(true));

    ModelWrapper object = loader.newModel("Primitives");

    object.set("type_boolean", true);
    object.set("type_byte", (byte) 64);
    object.set("type_short", (short) 256);
    object.set("type_int", 100);
    object.set("type_long", 200L);
    object.set("type_float", 300.f);
    object.set("type_double", 400.d);
    object.set("type_decimal", new BigDecimal("1234.567"));
    object.set("type_text", new Text("Hello, world!"));
    object.set("type_date", new Date(2011, 3, 31));
    object.set("type_datetime", new DateTime(2011, 3, 31, 23, 30, 1));

    DataOutputBuffer output = new DataOutputBuffer();
    ModelOutput<Object> modelOut =
        (ModelOutput<Object>)
            type.getAnnotation(ModelOutputLocation.class)
                .value()
                .getDeclaredConstructor(RecordEmitter.class)
                .newInstance(new TsvEmitter(new OutputStreamWriter(output, "UTF-8")));
    modelOut.write(object.unwrap());
    modelOut.write(object.unwrap());
    modelOut.write(object.unwrap());
    modelOut.close();

    DataInputBuffer input = new DataInputBuffer();
    input.reset(output.getData(), output.getLength());
    ModelInput<Object> modelIn =
        (ModelInput<Object>)
            type.getAnnotation(ModelInputLocation.class)
                .value()
                .getDeclaredConstructor(RecordParser.class)
                .newInstance(new TsvParser(new InputStreamReader(input, "UTF-8")));
    ModelWrapper copy = loader.newModel("Primitives");
    modelIn.readTo(copy.unwrap());
    assertThat(object.unwrap(), equalTo(copy.unwrap()));
    assertThat(input.read(), is(-1));
    modelIn.close();
  }
コード例 #6
0
  /** generate a simple model class. */
  @Test
  public void simple() {
    ModelLoader loader = generate();
    ModelWrapper object = loader.newModel("Simple");
    object.set("value", 100);
    assertThat(object.get("value"), eq(100));
    assertThat(object.getOption("value"), eq(new IntOption(100)));
    object.setOption("value", new IntOption(200));
    assertThat(object.get("value"), eq(200));

    ModelWrapper copy = loader.newModel("Simple");
    copy.copyFrom(object);

    object.reset();
    assertThat(object.getOption("value").isNull(), eq(true));
    assertThat(copy.get("value"), eq(200));
  }
コード例 #7
0
 @SuppressWarnings("unchecked")
 private Class<? extends DirectFileOutputDescription> generate(final Description description) {
   emitDrivers.add(
       new JavaDataModelDriver() {
         @Override
         public void generateResources(EmitContext context, ModelDeclaration model)
             throws IOException {
           EmitContext next =
               new EmitContext(
                   context.getSemantics(),
                   context.getConfiguration(),
                   model,
                   "testing",
                   "MockFileOutputDescription");
           DirectFileOutputDescriptionGenerator.generate(next, description);
         }
       });
   ModelLoader loader = generateJavaFromLines("model = { prop : INT; };");
   return (Class<? extends DirectFileOutputDescription>)
       loader.load("testing", "MockFileOutputDescription");
 }
コード例 #8
0
ファイル: UriLoader.java プロジェクト: 0359xiaodong/iosched
  @Override
  public final DataFetcher<T> getResourceFetcher(Uri model, int width, int height) {
    final String scheme = model.getScheme();

    DataFetcher<T> result = null;
    if (isLocalUri(scheme)) {
      result = getLocalUriFetcher(context, model);
    } else if (urlLoader != null && ("http".equals(scheme) || "https".equals(scheme))) {
      result = urlLoader.getResourceFetcher(new GlideUrl(model.toString()), width, height);
    }

    return result;
  }
コード例 #9
0
  /** all primitive types. */
  @Test
  public void primitives() {
    ModelLoader loader = generate();
    ModelWrapper object = loader.newModel("Primitives");

    object.set("type_boolean", true);
    assertThat(object.is("type_boolean"), eq(true));

    object.set("type_byte", (byte) 64);
    assertThat(object.get("type_byte"), eq((byte) 64));

    object.set("type_short", (short) 256);
    assertThat(object.get("type_short"), eq((short) 256));

    object.set("type_int", 100);
    assertThat(object.get("type_int"), eq(100));

    object.set("type_long", 200L);
    assertThat(object.get("type_long"), eq(200L));

    object.set("type_float", 300.f);
    assertThat(object.get("type_float"), eq(300.f));

    object.set("type_double", 400.d);
    assertThat(object.get("type_double"), eq(400.d));

    object.set("type_decimal", new BigDecimal("1234.567"));
    assertThat(object.get("type_decimal"), eq(new BigDecimal("1234.567")));

    object.set("type_text", new Text("Hello, world!"));
    assertThat(object.get("type_text"), eq(new Text("Hello, world!")));

    object.set("type_date", new Date(2011, 3, 31));
    assertThat(object.get("type_date"), eq(new Date(2011, 3, 31)));

    object.set("type_datetime", new DateTime(2011, 3, 31, 23, 30, 1));
    assertThat(object.get("type_datetime"), eq(new DateTime(2011, 3, 31, 23, 30, 1)));
  }
コード例 #10
0
ファイル: UrlUriLoader.java プロジェクト: iwillow/GlideSample
 @Override
 public LoadData<Data> buildLoadData(Uri uri, int width, int height, Options options) {
   GlideUrl glideUrl = new GlideUrl(uri.toString());
   return urlLoader.buildLoadData(glideUrl, width, height, options);
 }
コード例 #11
0
ファイル: ResourceLoader.java プロジェクト: Gyappy/glide
  @Override
  public LoadData<Data> buildLoadData(Integer model, int width, int height, Options options) {

    Uri uri = getResourceUri(model);
    return uri == null ? null : uriLoader.buildLoadData(uri, width, height, options);
  }
コード例 #12
0
 public DataFetcher getResourceFetcher(File file, int i, int j) {
   return uriLoader.getResourceFetcher(Uri.fromFile(file), i, j);
 }
コード例 #13
0
    /**
     * Performs schema compilation and prints the status/error into the
     * specified PrintStream.
     *
     * <p>
     * This method could be used to trigger XJC from other tools,
     * such as Ant or IDE.
     *
     * @param    args
     *        specified command line parameters. If there is an error
     *        in the parameters, {@link BadCommandLineException} will
     *        be thrown.
     * @param    listener
     *      Receives messages from XJC reporting progress/errors.
     *
     * @return
     *      If the compiler runs successfully, this method returns 0.
     *      All non-zero values indicate an error. The error message
     *      will be sent to the specified PrintStream.
     */
    public static int run(String[] args, @NotNull final XJCListener listener) throws BadCommandLineException {

        // recognize those special options before we start parsing options.
        for (String arg : args) {
            if (arg.equals("-version")) {
                listener.message(Messages.format(Messages.VERSION));
                return -1;
            }
        }

        final OptionsEx opt = new OptionsEx();
        opt.setSchemaLanguage(Language.XMLSCHEMA);  // disable auto-guessing
        try {
            opt.parseArguments(args);
        } catch (WeAreDone _) {
            return -1;
        } catch(BadCommandLineException e) {
            e.initOptions(opt);
            throw e;
        }

        // display a warning if the user specified the default package
        // this should work, but is generally a bad idea
        if(opt.defaultPackage != null && opt.defaultPackage.length()==0) {
            listener.message(Messages.format(Messages.WARNING_MSG, Messages.format(Messages.DEFAULT_PACKAGE_WARNING)));
        }


        // set up the context class loader so that the user-specified classes
        // can be loaded from there
        final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(
            opt.getUserClassLoader(contextClassLoader));

        // parse a grammar file
        //-----------------------------------------
        try {
            if( !opt.quiet ) {
                listener.message(Messages.format(Messages.PARSING_SCHEMA));
            }

            final boolean[] hadWarning = new boolean[1];

            ErrorReceiver receiver = new ErrorReceiverFilter(listener) {
                public void info(SAXParseException exception) {
                    if(opt.verbose)
                        super.info(exception);
                }
                public void warning(SAXParseException exception) {
                    hadWarning[0] = true;
                    if(!opt.quiet)
                        super.warning(exception);
                }
                @Override
                public void pollAbort() throws AbortException {
                    if(listener.isCanceled())
                        throw new AbortException();
                }
            };

            if( opt.mode==Mode.FOREST ) {
                // dump DOM forest and quit
                ModelLoader loader  = new ModelLoader( opt, new JCodeModel(), receiver );
                try {
                    DOMForest forest = loader.buildDOMForest(new XMLSchemaInternalizationLogic());
                    forest.dump(System.out);
                    return 0;
                } catch (SAXException e) {
                    // the error should have already been reported
                } catch (IOException e) {
                    receiver.error(e);
                }

                return -1;
            }

            if( opt.mode==Mode.GBIND ) {
                try {
                    XSSchemaSet xss = new ModelLoader(opt, new JCodeModel(), receiver).loadXMLSchema();
                    Iterator<XSComplexType> it = xss.iterateComplexTypes();
                    while (it.hasNext()) {
                        XSComplexType ct =  it.next();
                        XSParticle p = ct.getContentType().asParticle();
                        if(p==null)     continue;

                        Expression tree = ExpressionBuilder.createTree(p);
                        System.out.println("Graph for "+ct.getName());
                        System.out.println(tree.toString());
                        Graph g = new Graph(tree);
                        System.out.println(g.toString());
                        System.out.println();
                    }
                    return 0;
                } catch (SAXException e) {
                    // the error should have already been reported
                }
                return -1;
            }
            
            Model model = ModelLoader.load( opt, new JCodeModel(), receiver );

            if (model == null) {
                listener.message(Messages.format(Messages.PARSE_FAILED));
                return -1;
            }

            if( !opt.quiet ) {
                listener.message(Messages.format(Messages.COMPILING_SCHEMA));
            }

            switch (opt.mode) {
            case SIGNATURE :
                try {
                    SignatureWriter.write(
                        BeanGenerator.generate(model,receiver),
                        new OutputStreamWriter(System.out));
                    return 0;
                } catch (IOException e) {
                    receiver.error(e);
                    return -1;
                }

            case CODE :
            case DRYRUN :
            case ZIP :
                {
                    // generate actual code
                    receiver.debug("generating code");
                    {// don't want to hold outline in memory for too long.
                        Outline outline = model.generateCode(opt,receiver);
                        if(outline==null) {
                            listener.message(
                                Messages.format(Messages.FAILED_TO_GENERATE_CODE));
                            return -1;
                        }

                        listener.compiled(outline);
                    }

                    if( opt.mode == Mode.DRYRUN )
                        break;  // enough

                    // then print them out
                    try {
                        CodeWriter cw;
                        if( opt.mode==Mode.ZIP ) {
                            OutputStream os;
                            if(opt.targetDir.getPath().equals("."))
                                os = System.out;
                            else
                                os = new FileOutputStream(opt.targetDir);

                            cw = opt.createCodeWriter(new ZipCodeWriter(os));
                        } else
                            cw = opt.createCodeWriter();

                        if( !opt.quiet ) {
                            cw = new ProgressCodeWriter(cw,listener, model.codeModel.countArtifacts());
                        }
                        model.codeModel.build(cw);
                    } catch (IOException e) {
                        receiver.error(e);
                        return -1;
                    }

                    break;
                }
            default :
                assert false;
            }

            if(opt.debugMode) {
                try {
                    new FileOutputStream(new File(opt.targetDir,hadWarning[0]?"hadWarning":"noWarning")).close();
                } catch (IOException e) {
                    receiver.error(e);
                    return -1;
                }
            }

            return 0;
        } catch( StackOverflowError e ) {
            if(opt.verbose)
                // in the debug mode, propagate the error so that
                // the full stack trace will be dumped to the screen.
                throw e;
            else {
                // otherwise just print a suggested workaround and
                // quit without filling the user's screen
                listener.message(Messages.format(Messages.STACK_OVERFLOW));
                return -1;
            }
        }
    }