/** Parses the given reader. * @param reader the reader * @throws SerializationException if the reader cannot be successfully parsed. */ public void parse (Reader reader) { try { char[] data = new char[1024]; int offset = 0; while (true) { int length = reader.read(data, offset, data.length - offset); if (length == -1) break; if (length == 0) { char[] newData = new char[data.length * 2]; System.arraycopy(data, 0, newData, 0, data.length); data = newData; } else offset += length; } parse(data, 0, offset); } catch (IOException ex) { throw new SerializationException(ex); } finally { StreamUtils.closeQuietly(reader); } }
private String getOwnerCharacterName() { if (ownerCharacterName == null && s_ownerCharacterId != null) { try { GameObject go = GameState.getGameObjectById(s_ownerCharacterId); if (go instanceof GameCharacter) { ownerCharacterName = ((GameCharacter) go).getName(); } else { XmlReader xmlReader = new XmlReader(); Element root = xmlReader.parse(Gdx.files .internal(Configuration.getFolderCharacters() + s_ownerCharacterId + ".xml")); ownerCharacterName = root.getChildByName( XMLUtil.XML_PROPERTIES).get( XMLUtil.XML_ATTRIBUTE_NAME); } } catch (SerializationException e) { throw new GdxRuntimeException("Could not determine the owner with type "+s_ownerCharacterId, e); } if (ownerCharacterName == null) { throw new GdxRuntimeException("Could not determine the owner with type "+s_ownerCharacterId); } } return Strings.getString(ownerCharacterName); }
/** * Parses the supplied InputStream without closing it at the end using the * supplied XmlReader. * * @param inStream * @return */ public static Element parseNonCLosing(XmlReader parser, InputStream inStream) { try { InputStreamReader inReader = new InputStreamReader(inStream, "UTF-8"); char[] data = new char[1024]; int offset = 0; while (true) { int length = inReader.read(data, offset, data.length - offset); if (length == -1) break; if (length == 0) { char[] newData = new char[data.length * 2]; System.arraycopy(data, 0, newData, 0, data.length); data = newData; } else offset += length; } return parser.parse(data, 0, offset); } catch (IOException ex) { throw new SerializationException(ex); } }
@Override public void handleHttpResponse(Net.HttpResponse httpResponse) { try { handleResponse(httpResponse.getResultAsString()); if (statsReporterResponseListener != null) { statsReporterResponseListener.succeed(responseVO); } } catch (Error error) { Gdx.app.error(TAG, error.getMessage()); if (statsReporterResponseListener != null) { statsReporterResponseListener.failed(error); } } catch (SerializationException e) { e.printStackTrace(); if (statsReporterResponseListener != null) { statsReporterResponseListener.failed(e); } } }
private Skin loadSkin(GdxFileSystem fileSystem) { String skinPath = "skin/uiskin.json"; FileHandle skinFile = null; if (fileSystem.getFileExists(FilePath.of(skinPath))) { skinFile = fileSystem.resolve(skinPath); } else { // Fallback: use the internal skin stored in the classpath skinFile = Gdx.files.classpath("builtin/" + skinPath); } // Load skin if (skinFile != null) { try { return new Skin(skinFile); } catch (SerializationException se) { LOG.error("Error loading Scene2d skin", se); } } return new Skin(); }
public void loadChapter(String selChapter) throws IOException { undoStack.clear(); setSelectedScene(null); try { chapter.load(selChapter); firePropertyChange(NOTIFY_CHAPTER_LOADED); Ctx.project.getEditorConfig().setProperty("project.selectedChapter", selChapter); } catch (SerializationException ex) { // check for not compiled custom actions if (ex.getCause() != null && ex.getCause() instanceof ClassNotFoundException) { EditorLogger.msg("Custom action class not found. Trying to compile..."); if (RunProccess.runGradle(Ctx.project.getProjectDir(), "desktop:compileJava")) { ((FolderClassLoader)ActionFactory.getActionClassLoader()).reload(); chapter.load(selChapter); } else { throw new IOException("Failed to run Gradle."); } } else { throw ex; } } i18n.load(selChapter); }
/** * Use this to load in an individual .json scene. Any previously loaded scene * data will be lost (including Box2D objects!) * * @param _file * File to read. * @return The scene represented by the RUBE JSON file. */ public RubeScene loadScene(FileHandle _file) { if (mRubeWorldSerializer != null) { mRubeWorldSerializer.resetScene(); } if (mWorld != null) { mRubeWorldSerializer.usePreexistingWorld(mWorld); } RubeScene scene = null; try { scene = json.fromJson(RubeScene.class, _file); } catch (SerializationException ex) { throw new SerializationException("Error reading file: " + _file, ex); } return scene; }
/** * This method accumulates objects defined in a scene, allowing several separate * RUBE .json files to be combined. Objects are added to the scene's data, as * well as within the Box2D world that is ultimately returned. * * @param _file * The JSON file to parse * @return The cumulative scene */ public RubeScene addScene(FileHandle _file) { RubeScene scene = null; if ((mRubeWorldSerializer != null) && (mWorld != null)) { mRubeWorldSerializer.usePreexistingWorld(mWorld); } try { scene = json.fromJson(RubeScene.class, _file); } catch (SerializationException ex) { throw new SerializationException("Error reading file: " + _file, ex); } return scene; }
private void readNamedObjects(Json paramJson, Class paramClass, ObjectMap<String, ObjectMap> paramObjectMap) { if (paramClass == Skin.TintedDrawable.class); for (Object localObject1 = Drawable.class; ; localObject1 = paramClass) { Iterator localIterator = paramObjectMap.entries().iterator(); while (true) { if (!localIterator.hasNext()) return; ObjectMap.Entry localEntry = (ObjectMap.Entry)localIterator.next(); String str = (String)localEntry.key; Object localObject2 = paramJson.readValue(paramClass, localEntry.value); if (localObject2 != null) try { this.this$0.add(str, localObject2, (Class)localObject1); } catch (Exception localException) { throw new SerializationException("Error reading " + paramClass.getSimpleName() + ": " + (String)localEntry.key, localException); } } } }
public Skin read(Json paramJson, Object paramObject, Class paramClass) { Iterator localIterator = ((ObjectMap)paramObject).entries().iterator(); while (localIterator.hasNext()) { ObjectMap.Entry localEntry = (ObjectMap.Entry)localIterator.next(); String str = (String)localEntry.key; ObjectMap localObjectMap = (ObjectMap)localEntry.value; try { readNamedObjects(paramJson, Class.forName(str), localObjectMap); } catch (ClassNotFoundException localClassNotFoundException) { throw new SerializationException(localClassNotFoundException); } } return this.val$skin; }
/** Parses the given input stream. * @param input the input stream * @throws SerializationException if the input stream cannot be successfully parsed. */ public void parse (InputStream input) { try { parse(new InputStreamReader(input, "UTF-8")); } catch (IOException ex) { throw new SerializationException(ex); } finally { StreamUtils.closeQuietly(input); } }
/** Parses the given file. * @param file the file * @throws SerializationException if the file cannot be successfully parsed. */ public void parse (FileHandle file) { try { parse(file.reader("UTF-8")); } catch (Exception ex) { throw new SerializationException("Error parsing file: " + file, ex); } }
@Override public final void write(Json json) { for (Entry<String, StoragePrimitive> entry : properties.entrySet()) { try { json.getWriter().json(entry.getKey(), entry.getValue().toJson()); } catch (IOException e) { throw new SerializationException(e); } } }
private void loadEntities(){ logger.debug("Loading Entities"); Json json = new Json(); for (String s : manifest.entities){ try { EntityConfig config = json.fromJson(EntityConfig.class, Gdx.files.internal(s)); entityConfigs.put(config.name,config); } catch (SerializationException ex){ logger.error("Failed to load entity file: " + s); logger.error(ex.getMessage()); } } }
private void loadWeapons(){ logger.debug("Loading Weapons"); Json json = new Json();; for (String s : manifest.weapons){ try { WeaponConfig config = json.fromJson(WeaponConfig.class, Gdx.files.internal(s)); weaponConfigs.put(config.name,config); } catch (SerializationException ex){ logger.error("Failed to load weapons file: " + s); logger.error(ex.getMessage()); } } }
/** Adds all resources in the specified skin JSON file. */ public void load (FileHandle skinFile) { try { getJsonLoader(skinFile).fromJson(Skin.class, skinFile); } catch (SerializationException ex) { throw new SerializationException("Error reading file: " + skinFile, ex); } }
@Override public void init () { FileHandle storage = fileAccess.getMetadataFolder(); FileHandle storageFile = storage.child("donateReminder.json"); Json json = new Json(); json.setIgnoreUnknownFields(true); json.addClassTag("EditorRunCounter", EditorRunCounter.class); EditorRunCounter runCounter; try { if (storageFile.exists()) { runCounter = json.fromJson(EditorRunCounter.class, storageFile); } else runCounter = new EditorRunCounter(); } catch (SerializationException ignored) { runCounter = new EditorRunCounter(); } runCounter.counter++; if (runCounter.counter % 50 == 0) { VisTable table = new VisTable(true); table.add("If you like VisEditor please consider").spaceRight(3); table.add(new LinkLabel("donating.", DONATE_URL)); LinkLabel hide = new LinkLabel("Hide"); table.add(hide); menuBar.setUpdateInfoTableContent(table); hide.setListener(labelUrl -> menuBar.setUpdateInfoTableContent(null)); } json.toJson(runCounter, storageFile); }
@Override public void init () { FileHandle storage = fileAccess.getMetadataFolder(); storageFile = storage.child("recentProjects.json"); json = new Json(); json.setIgnoreUnknownFields(true); json.addClassTag("RecentProjectEntry", RecentProjectEntry.class); try { if (storageFile.exists()) { recentProjects = json.fromJson(new Array<RecentProjectEntry>().getClass(), storageFile); Iterator<RecentProjectEntry> it = recentProjects.iterator(); while (it.hasNext()) { RecentProjectEntry entry = it.next(); if (Gdx.files.absolute(entry.projectPath).exists() == false) it.remove(); } } else recentProjects = new Array<>(); } catch (SerializationException ignored) { //no big deal if cache can't be loaded recentProjects = new Array<>(); } }
private Settings readSettings () { if (settingsFile.exists()) { try { return json.fromJson(Settings.class, settingsFile); } catch (SerializationException e) { settingsFile.delete(); return new Settings(); } } else return new Settings(); }
/** Adds all resources in the specified skin JSON file. */ public void load(FileHandle skinFile) { try { getJsonLoader(skinFile).fromJson(Skin.class, skinFile); } catch (SerializationException ex) { throw new SerializationException("Error reading file: " + skinFile, ex); } }
@Override public void readFields(Object object, JsonValue jsonMap) { try { super.readFields(object, jsonMap); } catch (SerializationException e) { Gdx.app.error("Assets", "Error reading fields " + jsonMap + " to " + object, e); } }
public boolean run() { exported = false; Map<String, Object> entities = new HashMap<String, Object>(); FileHandle projectFileHandle = new FileHandle(projectPath); // Try to load all game entities GameAssets gameAssets = new GameAssets(new ExporterFiles(), new ExporterImageUtils()) { protected FileHandle[] resolveBindings() { return new FileHandle[] { resolve("bindings.json"), resolve("editor-bindings.json") }; } }; try { loadAllEntities(gameAssets, projectFileHandle, entities); } catch (SerializationException serializationException) { System.err .println("[ERROR] A serialization exception occurred while exporting " + projectPath + ". The project could not be exported."); return false; } // Export Exporter exporter = new Exporter(gameAssets); doExport(projectPath, destinationPath, entities, gameAssets, exporter, new DefaultCallback()); return exported; }
@Override protected void doPrepare(String URL) { response = null; repoElems = null; String httpResponse = null; try { httpResponse = controller.getPlatform().sendHttpGetRequest(URL, String.class); } catch (IOException e) { Gdx.app.error(SEARCH_REPO_TAG, "Failed to perform the HTTP request. ", e); error(e); return; } if (httpResponse == null || httpResponse.trim().isEmpty()) { IOException ioe = new IOException( "Invalid http response (null or empty)"); Gdx.app.error(SEARCH_REPO_TAG, "", ioe); error(ioe); return; } try { response = getRepoElementsFromResult(httpResponse); result(response); repoElems = response.getResults(); } catch (SerializationException se) { Gdx.app.log(SEARCH_REPO_TAG, "Error parsing JSON result.", se); repoElems = null; response = null; error(se); } }
public void load(FileHandle paramFileHandle) { try { getJsonLoader(paramFileHandle).fromJson(Skin.class, paramFileHandle); return; } catch (SerializationException localSerializationException) { throw new SerializationException("Error reading file: " + paramFileHandle, localSerializationException); } }
public BitmapFont read(Json paramJson, Object paramObject, Class paramClass) { String str1 = (String)paramJson.readValue("file", String.class, paramObject); FileHandle localFileHandle1 = this.val$skinFile.parent().child(str1); if (!localFileHandle1.exists()) localFileHandle1 = Gdx.files.internal(str1); if (!localFileHandle1.exists()) throw new SerializationException("Font file not found: " + localFileHandle1); String str2 = localFileHandle1.nameWithoutExtension(); try { TextureRegion localTextureRegion = (TextureRegion)this.val$skin.optional(str2, TextureRegion.class); if (localTextureRegion != null) return new BitmapFont(localFileHandle1, localTextureRegion, false); FileHandle localFileHandle2 = localFileHandle1.parent().child(str2 + ".png"); if (localFileHandle2.exists()) { BitmapFont localBitmapFont1 = new BitmapFont(localFileHandle1, localFileHandle2, false); return localBitmapFont1; } } catch (RuntimeException localRuntimeException) { throw new SerializationException("Error loading bitmap font: " + localFileHandle1, localRuntimeException); } BitmapFont localBitmapFont2 = new BitmapFont(localFileHandle1, false); return localBitmapFont2; }
private static String unescape (String value) { int length = value.length(); StringBuilder buffer = new StringBuilder(length + 16); for (int i = 0; i < length;) { char c = value.charAt(i++); if (c != '\\') { buffer.append(c); continue; } if (i == length) break; c = value.charAt(i++); if (c == 'u') { buffer.append(Character.toChars(Integer.parseInt(value.substring(i, i + 4), 16))); i += 4; continue; } switch (c) { case '"': case '\\': case '/': break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; default: throw new SerializationException("Illegal escaped character: \\" + c); } buffer.append(c); } return buffer.toString(); }
protected Json getJsonLoader (final FileHandle skinFile) { Json loader = super.getJsonLoader(skinFile); final Serializer<BitmapFont> originialSerializer = loader.getSerializer(BitmapFont.class); loader.setSerializer(BitmapFont.class, new ReadOnlySerializer<BitmapFont>() { @SuppressWarnings("rawtypes") public BitmapFont read (Json json, JsonValue jsonData, Class type) { String path = json.readValue("file", String.class, jsonData); FileHandle fontFile = skinFile.parent().child(path); if (!fontFile.exists()) { fontFile = Gdx.files.internal(path); } if (!fontFile.exists()) { throw new SerializationException("Font file not found: " + fontFile); } boolean isTrueType = "ttf".equals(fontFile.extension()); if (isTrueType) { Boolean markupEnabled = json.readValue("markupEnabled", Boolean.class, false, jsonData); FreeTypeFontParameter parameter = new FreeTypeFontParameter(); parameter.size = json.readValue("size", int.class, -1, jsonData); parameter.borderWidth = json.readValue("borderWidth", int.class, 0, jsonData); parameter.color= json.readValue("color", Color.class, Color.WHITE, jsonData); parameter.borderColor= json.readValue("borderColor", Color.class, Color.BLACK, jsonData); parameter.borderStraight = json.readValue("borderStraight", boolean.class, false, jsonData); parameter.shadowOffsetX = json.readValue("shadowOffsetX", int.class, 0, jsonData); parameter.shadowOffsetY = json.readValue("shadowOffsetY", int.class, 0, jsonData); parameter.shadowColor = json.readValue("shadowColor", Color.class, new Color(0, 0, 0, 0.75f), jsonData); parameter.flip = json.readValue("flip", Boolean.class, false, jsonData); parameter.packer = getPacker(); FreeTypeFontGenerator generator = new FreeTypeFontGenerator(fontFile); BitmapFont font = generator.generateFont(parameter); generator.dispose(); font.getData().markupEnabled = markupEnabled; return font; } else { return originialSerializer.read(json, jsonData, type); } } }); return loader; }
@Test(expected = SerializationException.class) public void setJsonStringThrows() { fixture.setJsonString("INVALID_JSON_STRING{}"); }
@Test(expected = SerializationException.class) public void jsonStringConstructorThrows() { new JsonResult("INVALID_JSON_STRING{}"); }
protected void handleResponse (String resultAsString) throws SerializationException{ Json json = new Json(); responseVO = json.fromJson(responseType, resultAsString); }
public void loadProject(File projectToLoad) throws IOException { projectToLoad = checkProjectStructure(projectToLoad); if (projectToLoad != null) { // dispose the current project closeProject(); this.projectFile = projectToLoad; // Use FolderClassLoader for loading CUSTOM actions. // TODO Add 'core/bin' and '/core/out' folders??? FolderClassLoader folderClassLoader = null; if (new File(projectFile, "/assets").exists()) { folderClassLoader = new FolderClassLoader(projectFile.getAbsolutePath() + "/core/build/classes/java/main"); } else { folderClassLoader = new FolderClassLoader(projectFile.getAbsolutePath() + "/core/build/classes/main"); } ActionFactory.setActionClassLoader(folderClassLoader); EngineAssetManager.createEditInstance(getAssetPath()); try { World.getInstance().loadWorldDesc(); } catch (SerializationException ex) { // check for not compiled custom actions if (ex.getCause() != null && ex.getCause() instanceof ClassNotFoundException) { EditorLogger.msg("Custom action class not found. Trying to compile..."); if (RunProccess.runGradle(Ctx.project.getProjectDir(), "desktop:compileJava")) { folderClassLoader.reload(); World.getInstance().loadWorldDesc(); } else { this.projectFile = null; throw new IOException("Failed to run Gradle."); } } else { this.projectFile = null; throw ex; } } chapter = new Chapter(getAssetPath() + Project.MODEL_PATH); i18n = new I18NHandler(getAssetPath() + Project.MODEL_PATH); // No need to load the chapter. It's loaded by the chapter combo. // loadChapter(World.getInstance().getInitChapter()); editorConfig.setProperty(LAST_PROJECT_PROP, projectFile.getAbsolutePath()); projectConfig = new OrderedProperties(); projectConfig.load(new FileInputStream(getAssetPath() + "/" + Config.PROPERTIES_FILENAME)); modified = false; Display.setTitle("Adventure Editor v" + Versions.getVersion() + " - " + projectFile.getAbsolutePath()); firePropertyChange(NOTIFY_PROJECT_LOADED); } else { throw new IOException("Project not found."); } }
/** * Tries to find the {@link Component} class equivalent to the * {@link ModelComponent} provided as argument. * * ModelComponent to EngineComponent mappings are created dynamically. New * mappings are cached when {@link #toEngineComponent(ModelComponent)} is * invoked. If a mapping is not found, then a new {@link ModelComponent} is * created and it is passed to {@link #toEngineComponent(ModelComponent)} to * infer the engine's component class. * * @param alias * The alias of the class that is to be mapped to engine class. * It must be compulsorily either of type {@line ModelComponent} * or {@link Event}, as {@link Behavior}s are handled in a * special way (each event type is mapped to a different * component type). * @return The {@link Component} engine equivalent class, if found, * {@code null} otherwise. */ public Class<? extends Component> toEngineComponent(String alias) { Class modelClass; try { modelClass = gameAssets.getClass(alias); } catch (SerializationException e) { return null; } if (modelClass == null || (!ClassReflection.isAssignableFrom(Event.class, modelClass) && !ClassReflection .isAssignableFrom(ModelComponent.class, modelClass))) { return null; } else { return toEngineComponent(modelClass); } }
@Override public Object call() throws Exception { // Try to download update.json. If updateURL is not present, disable // the update system if (releaseInfo.getUpdateURL() != null) { HttpRequest request = new HttpRequest("GET"); request.setUrl(releaseInfo.getUpdateURL()); Gdx.app.debug(LOG_TAG, "Trying to retrieve update.json from url:" + releaseInfo.getUpdateURL()); Gdx.net.sendHttpRequest(request, new HttpResponseListener() { @Override public void handleHttpResponse(HttpResponse httpResponse) { if (httpResponse.getStatus().getStatusCode() == 200) { String data = httpResponse.getResultAsString(); Gdx.app.debug(LOG_TAG, "Update.json fetched and read: " + data); try { UpdateInfo updateInfo = controller .getApplicationAssets().fromJson( UpdateInfo.class, data); if (updateInfo != null) { checkUpdateNeeded(updateInfo); } } catch (SerializationException e) { Gdx.app.error( LOG_TAG, "An error occurred while reading update.json from " + releaseInfo.getUpdateURL() + ". The update system will be disabled.", e); setDone(); } } } @Override public void failed(Throwable t) { Gdx.app.debug( LOG_TAG, "Error fetching update.json. Updater will be disabled", t); setDone(); } @Override public void cancelled() { } }); } else { Gdx.app.debug(LOG_TAG, "The update.json url is null. The update system will be disabled."); setDone(); } return null; }
@Override protected boolean step() { entityFolder.mkdirs(); FileHandle entityContents = entityFolder .child(ModelStructure.CONTENTS_FOLDER); this.contentsFolder.copyTo(entityContents); if (controller.getLibraryManager().isMokap(element)) { if (!entityContents.child(ModelStructure.GAME_FILE).exists()) { error(new FileNotFoundException(ModelStructure.GAME_FILE + " not found at " + entityContents.path())); return true; } } else { FileHandle entityJson = entityContents .child(ModelStructure.ENTITY_FILE); if (!entityJson.exists()) { FileHandle[] list = entityContents.list(".json"); if (list.length > 0) { list[0].copyTo(entityJson); list[0].delete(); } else { error(new FileNotFoundException( "Entity json file not found at " + entityContents.path())); return true; } } } String json = null; try { json = gameAssets.toJson(element, RepoElement.class); } catch (SerializationException se) { error(se); return true; } entityFolder.child(ModelStructure.DESCRIPTOR_FILE).writeString(json, false); result(true); return true; }