public Boolean saveGameStateSync(String id, byte[] gameState, long progressValue, ISaveGameStateResponseListener listener) { if (!isSessionActive() || !whisperSyncEnabled) return false; GameDataMap gameDataMap = AmazonGamesClient.getWhispersyncClient().getGameData(); SyncableString savedData = gameDataMap.getLatestString(id); SyncableNumber savedProgress = gameDataMap.getLatestNumber(id + "progress"); if (!savedProgress.isSet() || savedProgress.asLong() <= progressValue) { savedData.set(new String(Base64Coder.encode(gameState))); savedProgress.set(progressValue); if (listener != null) listener.onGameStateSaved(true, null); return true; } else { Gdx.app.error(GameCircleClient.GS_CLIENT_ID, "Progress of saved game state higher than current one. Did " + "not save."); if (listener != null) listener.onGameStateSaved(true, null); return false; } }
@Override public void onMessage(WebSocket conn, String message) { try { KryoConnection k = getBySocket(conn); if (k == null) return; if(message.equals("_ping_")){ conn.send(connections.size() + "|" + Vars.player.name); connections.remove(k); }else { if (debug) UCore.log("Got message: " + message); byte[] out = Base64Coder.decode(message); if (debug) UCore.log("Decoded: " + Arrays.toString(out)); ByteBuffer buffer = ByteBuffer.wrap(out); Object o = serializer.read(buffer); Net.handleServerReceived(o, k.id); } }catch (Exception e){ UCore.log("Error reading message!"); e.printStackTrace(); } }
public static void saveToSlot(int slot){ if(Vars.gwt){ ByteArrayOutputStream stream = new ByteArrayOutputStream(); write(stream); Settings.putString("save-"+slot+"-data", new String(Base64Coder.encode(stream.toByteArray()))); Settings.save(); }else{ FileHandle file = fileFor(slot); boolean exists = file.exists(); if(exists) file.moveTo(file.sibling(file.name() + "-backup." + file.extension())); try { write(fileFor(slot)); }catch (Exception e){ if(exists) file.sibling(file.name() + "-backup." + file.extension()).moveTo(file); throw new RuntimeException(e); } } }
public boolean hasOlderVersionSavingSystem() { String codedKey = Base64Coder.encodeString("currentLevel"); String stringUncodedValue = Base64Coder.decodeString(pref.getString(codedKey)); String codedKey2 = Base64Coder.encodeString("chapter1"); String stringUncodedValue2 = Base64Coder.decodeString(pref.getString(codedKey2)); if (stringUncodedValue.compareTo("") == 0) { return false; } else { if (stringUncodedValue2.compareTo("") == 0) { return true; } else { return false; } } }
private void loadLevelsStatus() { if (hasOlderVersionSavingSystem()) { loadOlderVersionChapter1(); } for (int i = 0; i < PlayerProgress.NUMBER_OF_CHAPTERS; i++) { String codedKey = Base64Coder.encodeString("chapter" + (i + 1)); String stringUncodedValue = Base64Coder.decodeString(pref.getString(codedKey)); if (stringUncodedValue.compareTo("") == 0) { saveLevelsStatus(); break; } else { String stringLevelsStatus[] = stringUncodedValue.split(" "); int levelsStatus[] = new int[stringLevelsStatus.length]; for (int j = 0; j < stringLevelsStatus.length; j++) { levelsStatus[j] = Integer.valueOf(stringLevelsStatus[j]); } playerProgress.setLevelsStatus(levelsStatus, i + 1); } } }
@SuppressWarnings("unchecked") private void retrieveHighScores() { FileHandle highScoresFile = Gdx.files.local(SCORES_DATA_FILE); if( highScoresFile.exists() ) { Json json = new Json(); try { String encScoresStr = highScoresFile.readString(); String scoresStr = Base64Coder.decodeString( encScoresStr ); highScores = json.fromJson(ArrayList.class, HighScore.class, scoresStr); return; } catch( Exception e ) { Gdx.app.error( HighScoreManager.class.getName(), "Unable to parse high scores data file", e ); } } highScores = new ArrayList<HighScore>(); String playerName = textResources.getDefaultPlayerName(); for(int i=0;i<HIGH_SCORES_COUNT;i++){ highScores.add(new HighScore(playerName, 50 - 10*i, false)); } }
public static void save(TilePrefab prefab, String outputFilename) { if (prefab == null) throw new IllegalArgumentException(); JsonTilePrefab jsonPrefab = new JsonTilePrefab(); jsonPrefab.width = prefab.getWidth(); jsonPrefab.height = prefab.getHeight(); jsonPrefab.depth = prefab.getDepth(); byte[] dataBytes = new byte[prefab.getData().length * TileDataSerializer.TILE_SIZE_BYTES]; ByteBuffer buffer = ByteBuffer.wrap(dataBytes); TileDataSerializer.serialize(prefab, buffer); jsonPrefab.data = new String(Base64Coder.encode(dataBytes)); Json json = new Json(); String output = json.prettyPrint(jsonPrefab); FileHandle outputFile = Gdx.files.local(outputFilename); outputFile.writeString(output, false); }
protected void persist(Profile profile) { // create the handle for profile data file FileHandle profileDataFile = Gdx.files.local(PROFILE_DATA_FILE); Gdx.app.log(GensokyoGame.LOG, "Persisting profile in: " + profileDataFile.path()); Json json = new Json(); // convert profile to text String profileAsText = json.toJson(profile); // encode the text if (!GensokyoGame.DEV) { profileAsText = Base64Coder.encodeString(profileAsText); } // write the profile data file profileDataFile.writeString(profileAsText, false); }
protected boolean loadGameStateSync(String fileId, ILoadGameStateResponseListener listener) { if (!isSessionActive() || !whisperSyncEnabled) { listener.gsGameStateLoaded(null); return false; } // wait some time to get data loaded from cloud int maxWaitTime = 5000; if (!loadedFromCloud) Gdx.app.log(GameCircleClient.GS_CLIENT_ID, "Waiting for cloud data to get synced..."); while (!loadedFromCloud && maxWaitTime > 0) { SystemClock.sleep(100); maxWaitTime -= 100; } GameDataMap gameDataMap = AmazonGamesClient.getWhispersyncClient().getGameData(); SyncableString savedData = gameDataMap.getLatestString(fileId); if (!savedData.isSet()) { Gdx.app.log(GameCircleClient.GS_CLIENT_ID, "No data in whispersync for " + fileId); listener.gsGameStateLoaded(null); return false; } else { Gdx.app.log(GameCircleClient.GS_CLIENT_ID, "Loaded " + fileId + "from whispersync successfully."); listener.gsGameStateLoaded(Base64Coder.decode(savedData.getValue())); return true; } }
@Override public void send(Object object, SendMode mode) { if(!(object instanceof Packet)) throw new RuntimeException("All sent objects must be packets!"); Packet p = (Packet)object; buffer.position(0); buffer.put(Registrator.getID(object.getClass())); p.write(buffer); int pos = buffer.position(); buffer.position(0); byte[] out = new byte[pos]; buffer.get(out); String string = new String(Base64Coder.encode(out)); if(debug) UCore.log("Sending string: " + string); socket.send(string); }
@Override public void send(Object object, SendMode mode){ if(socket != null){ try { synchronized (buffer) { buffer.position(0); if(debug) UCore.log("Sending object with ID " + Registrator.getID(object.getClass())); serializer.write(buffer, object); int pos = buffer.position(); buffer.position(0); byte[] out = new byte[pos]; buffer.get(out); String string = new String(Base64Coder.encode(out)); if(debug) UCore.log("Sending string: " + string); socket.send(string); } }catch (Exception e){ e.printStackTrace(); connections.remove(this); } }else if (connection != null) { if (mode == SendMode.tcp) { connection.sendTCP(object); } else { connection.sendUDP(object); } } }
@Override public void send(Object object, SendMode mode) { if(!(object instanceof Packet)) throw new RuntimeException("All sent objects must be packets!"); Packet p = (Packet)object; buffer.position(0); buffer.put(Registrator.getID(object.getClass())); p.write(buffer); int pos = buffer.position(); buffer.position(0); byte[] out = new byte[pos]; buffer.get(out); String string = new String(Base64Coder.encode(out)); socket.send(string); }
public static void loadFromSlot(int slot){ if(Vars.gwt){ String string = Settings.getString("save-"+slot+"-data"); ByteArrayInputStream stream = new ByteArrayInputStream(Base64Coder.decode(string)); load(stream); }else{ load(fileFor(slot)); } }
public static DataInputStream readSlotMeta(int slot){ if(Vars.gwt){ String string = Settings.getString("save-"+slot+"-data"); byte[] bytes = Base64Coder.decode(string); return new DataInputStream(new ByteArrayInputStream(bytes)); }else{ return new DataInputStream(fileFor(slot).read()); } }
/** * Creates texture region from byte[]. * <p> * GWT platform requires additional step (as far as i know) to deal with Pixmap. It is need to load Image element * and wait until it is loaded. * * @param bytes Image byte[] representation, not null * @param consumer Consumer where you should deal with region, not null */ public static void createTextureFromBytes(byte[] bytes, final Consumer<TextureRegion> consumer) { String base64 = "data:image/png;base64," + new String(Base64Coder.encode(bytes)); final Image image = new Image(); image.setVisible(false); image.addLoadHandler(new LoadHandler() { @Override public void onLoad(LoadEvent event) { ImageElement imageElement = image.getElement().cast(); Pixmap pixmap = new Pixmap(imageElement); Gdx.app.log("ImageHelper", "pixmap: " + pixmap.getWidth() + "/" + pixmap.getHeight()); final int orgWidth = pixmap.getWidth(); final int orgHeight = pixmap.getHeight(); int width = MathUtils.nextPowerOfTwo(orgWidth); int height = MathUtils.nextPowerOfTwo(orgHeight); final Pixmap potPixmap = new Pixmap(width, height, pixmap.getFormat()); potPixmap.drawPixmap(pixmap, 0, 0, 0, 0, pixmap.getWidth(), pixmap.getHeight()); pixmap.dispose(); TextureRegion region = new TextureRegion(new Texture(potPixmap), 0, 0, orgWidth, orgHeight); potPixmap.dispose(); RootPanel.get().remove(image); consumer.accept(region); } }); image.setUrl(base64); RootPanel.get().add(image); }
/** * {@inheritDoc} */ @Override public void upload(final byte[] data, final String path, final UploadCallback callback) { ScriptRunner.firebaseScript(new ScriptRunner.ScriptStorageAction(bucketUrl()) { @Override public void run() { StorageJS.upload(scriptBucketUrl, path, new String(Base64Coder.encode(data)), callback); } }); }
@Override public void persist(P profile) { FileHandle profileDataFile = Gdx.files.local(preferencesManager.PROFILE_DATA_FILE); Json json = new Json(); String profileAsText = json.toJson(profile); profileAsText = Base64Coder.encodeString(profileAsText); profileDataFile.writeString(profileAsText, false); }
public static String encrypt(String input, String key){ byte[] crypted = null; try{ SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, skey); crypted = cipher.doFinal(input.getBytes()); }catch(Exception e){ System.out.println(e.toString()); } return new String(Base64Coder.encode(crypted)); }
public static String decrypt(String input, String key){ System.out.println(input); byte[] output = null; try{ SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skey); output = cipher.doFinal(Base64Coder.decode(input.replace("\\", ""))); } catch(Exception e){ System.out.println(e.toString()); } return new String(output); }
@Override public String serializeAsString(final Object object) { final String serialized = serializer.serializeAsString(object); try { return Base64Coder.encodeString(serialized, useUrlSafeEncoding); } catch (final Exception exception) { throw new SerializationException("Unable to encode data into BASE64: " + serialized, exception); } }
@Override public Object deserialize(final String data) { String decoded; try { decoded = Base64Coder.decodeString(data, useUrlSafeEncoding); } catch (final Exception exception) { throw new SerializationException("Unable to decode data from BASE64: " + data, exception); } return serializer.deserialize(decoded); }
private void loadOlderVersionChapter1() { int currentLevel; // loadCurrentLevel String codedKey = Base64Coder.encodeString("currentLevel"); String stringUncodedValue = Base64Coder.decodeString(pref.getString(codedKey)); currentLevel = Integer.valueOf(stringUncodedValue); int chapter1LevelsStatus[] = new int[PlayerProgress.NUMBER_OF_LEVELS]; // loadSkippedLevels String codedKey2 = Base64Coder.encodeString("skippedLevels"); String stringUncodedValue2 = Base64Coder.decodeString(pref.getString(codedKey2)); boolean noSkippedLevels = stringUncodedValue2.compareTo("") == 0; String stringSkippedLevels[] = stringUncodedValue2.split(" "); for (int i = 0; i < chapter1LevelsStatus.length; i++) { boolean found = false; if (!noSkippedLevels) { for (int j = 0; j < stringSkippedLevels.length; j++) { if ((i + 1) == Integer.valueOf(stringSkippedLevels[j])) { chapter1LevelsStatus[i] = PlayerProgress.LevelType.SKIPPED_LEVEL.ordinal(); found = true; } } } if (!found) { if (i + 1 <= currentLevel) { chapter1LevelsStatus[i] = PlayerProgress.LevelType.OPENED_LEVEL.ordinal(); } else { chapter1LevelsStatus[i] = PlayerProgress.LevelType.LOCKED_LEVEL.ordinal(); } } } playerProgress.setLevelsStatus(chapter1LevelsStatus, 1); savePlayerProgress(); }
private void saveLevelsStatus() { for (int i = 0; i < PlayerProgress.NUMBER_OF_CHAPTERS; i++) { StringBuilder stringBuilder = new StringBuilder(); for (Integer levelStatus : playerProgress.getLevelsStatus(i + 1)) { stringBuilder.append(String.valueOf(levelStatus)).append(" "); } if (stringBuilder.length() != 0) { stringBuilder.deleteCharAt(stringBuilder.length() - 1); } pref.putString(Base64Coder.encodeString("chapter" + (i + 1)), Base64Coder.encodeString(stringBuilder.toString())); } pref.flush(); }
private void persist() { FileHandle highScoresFile = Gdx.files.local(SCORES_DATA_FILE); Json json = new Json(); String scoresStr = json.toJson(highScores); String encScoresStr = Base64Coder.encodeString(scoresStr); highScoresFile.writeString(encScoresStr, false); }
/** * Loads an Object of type T from a previously saved file * @param type type of the Object to load * @param localPath local path to the file * @param encoded whether the file is encoded * @return the loaded Object of type T */ public <T> T load(Class<T> type, String localPath, boolean encoded) { FileHandle file = Gdx.files.internal(localPath); if (encoded) { return json.fromJson(type, Base64Coder.decodeString(file.readString())); } return json.fromJson(type, file.readString()); }
/** * Saves a key or controller map to a json file with optional Base64 encoding. * @param path Path to output file. * @param controller Whether to save the controller map. * @param encoded Whether to encode the file. */ public void saveMap(String path, boolean controller, boolean encoded) { FileHandle file = new FileHandle(path); String output = json.prettyPrint((controller)? controllerMap : keyMap); if (encoded) output = Base64Coder.encodeString(output); file.writeString(output, false); System.out.println("Map saved to " + path); }
/** * Loads a key or controller map from a previously saved file. * @param path Path to map file. * @param controller Whether to load a controller map. * @param encoded Whether the file is encoded. */ @SuppressWarnings("unchecked") public void loadMap(String path, boolean controller, boolean encoded) { FileHandle file = new FileHandle(path); Map<String, Float> map = json.fromJson(HashMap.class, (encoded)? Base64Coder.decodeString(file.readString()) : file.readString()); ((controller) ? controllerMap : keyMap).clear(); ((controller) ? controllerMap : keyMap).putAll(map); }
private void processLayerDataXML(final Element layerNode, final int width, final int height) throws IOException { final String data = layerNode.getChildNodes().item(1).getTextContent().trim(); final byte[] decodedBytes = Base64Coder.decode(data); final GZIPInputStream stream = new GZIPInputStream(new ByteArrayInputStream(decodedBytes)); final int[] _tileData = new int[width * height]; int pos = 0; while (pos < (width * height)) { int tileNum = stream.read(); tileNum |= (stream.read() << 8); tileNum |= (stream.read() << 16); tileNum |= (stream.read() << 24); _tileData[pos++] = tileNum - 1; } _stageFactory.generate().setTileData(_tileData); }
protected void persist(Profile profile) { FileHandle profileDataFile = Gdx.files.local(Constants.PROFILE_DATA_FILE); Gdx.app.log(Constants.LOG, "Persisting profile in: " + profileDataFile.path()); Json json = new Json(); String profileAsText = json.toJson(profile); if (!DreamsGame.DEBUG) { profileAsText = Base64Coder.encodeString(profileAsText); } profileDataFile.writeString(profileAsText, false); }
@Override public void saveGameState(String fileId, byte[] gameState, long progressValue, final ISaveGameStateResponseListener listener) { if (!isSessionActive()) { if (listener != null) listener.onGameStateSaved(false, "NOT_CONNECTED"); return; } //TODO progressValue is saved for future use, but should be checked before overwriting existing values Net.HttpRequest http = buildStoreDataRequest(fileId, false, Long.toString(progressValue) + "\n" + new String(Base64Coder.encode(gameState))); Gdx.net.sendHttpRequest(http, new Net.HttpResponseListener() { @Override public void handleHttpResponse(Net.HttpResponse httpResponse) { String json = httpResponse.getResultAsString(); boolean success = parseSuccessFromResponse(json); if (!success) Gdx.app.error(GAMESERVICE_ID, "Error saving gamestate: " + json); if (listener != null) listener.onGameStateSaved(success, null); } @Override public void failed(Throwable t) { Gdx.app.error(GAMESERVICE_ID, "Error saving gamestate", t); if (listener != null) listener.onGameStateSaved(false, null); } @Override public void cancelled() { Gdx.app.error(GAMESERVICE_ID, "Error saving gamestate: Cancelled"); if (listener != null) listener.onGameStateSaved(false, null); } }); }
@Override public void loadGameState(String fileId, final ILoadGameStateResponseListener listener) { if (!isSessionActive()) { listener.gsGameStateLoaded(null); return; } Net.HttpRequest http = buildLoadDataRequest(fileId, false); Gdx.net.sendHttpRequest(http, new Net.HttpResponseListener() { @Override public void handleHttpResponse(Net.HttpResponse httpResponse) { String response = httpResponse.getResultAsString(); if (response == null || !response.startsWith("SUCCESS")) { // just log, no error because loading a nonexistant gamestate fails but is no error Gdx.app.log(GAMESERVICE_ID, "Gamestate load failed: " + response); listener.gsGameStateLoaded(null); } else { // indexOf is twice to cut first two lines. First one is success message, // second one is progressValue byte[] gs = Base64Coder.decode(response.substring( response.indexOf('\n', response.indexOf('\n') + 1) + 1)); listener.gsGameStateLoaded(gs); } } @Override public void failed(Throwable t) { Gdx.app.error(GAMESERVICE_ID, "Gamestate load failed", t); listener.gsGameStateLoaded(null); } @Override public void cancelled() { Gdx.app.error(GAMESERVICE_ID, "Gamestate load cancelled"); listener.gsGameStateLoaded(null); } }); }
@Override public void connect(String ip, int port) throws IOException { try { URI i = new URI("ws://" + ip + ":" + Vars.webPort); UCore.log("Connecting: " + i); socket = new WebSocketClient(i, new Draft_6455(), null, 5000) { Thread thread; @Override public void connect() { if(thread != null ) throw new IllegalStateException( "WebSocketClient objects are not reuseable" ); thread = new Thread(this); thread.setDaemon(true); thread.start(); } @Override public void onOpen(ServerHandshake handshakedata) { UCore.log("Connected!"); Connect connect = new Connect(); Net.handleClientReceived(connect); } @Override public void onMessage(String message) { if(debug) UCore.log("Got message: " + message); try { byte[] bytes = Base64Coder.decode(message); ByteBuffer buffer = ByteBuffer.wrap(bytes); byte id = buffer.get(); if (id == -2) { //this is a framework message... do nothing yet? } else { Class<?> type = Registrator.getByID(id); if(debug) UCore.log("Got class ID: " + type); Packet packet = (Packet) ClassReflection.newInstance(type); packet.read(buffer); Net.handleClientReceived(packet); } } catch (Exception e) { e.printStackTrace(); //throw new RuntimeException(e); } } @Override public void onClose(int code, String reason, boolean remote) { if(debug) UCore.log("Closed."); Disconnect disconnect = new Disconnect(); Net.handleClientReceived(disconnect); } @Override public void onError(Exception ex) { onClose(0, null, true); ex.printStackTrace(); } }; socket.connect(); }catch (URISyntaxException e){ throw new IOException(e); } }
public static void save() { Json json = new Json(); saveFile.writeString(Base64Coder.encodeString(json.prettyPrint(currentDescriptor)), false); }
public static void load() { Json json = new Json(); currentDescriptor = json.fromJson(SaveFileDescriptor.class, Base64Coder.decodeString(saveFile.readString())); }
/** * Base64Coder解密获取单个数据 */ public String getDataFromDecode(String key) { String result = Base64Coder.decodeString(mPreferences.getString(key)); return result; }
/** * Base64Coder加密保存单个数据 */ public void saveDataToEncode(String key, String content) { String result = Base64Coder.encodeString(content); mPreferences.putString(key, result); mPreferences.flush(); }
@Override @SuppressWarnings("unchecked") protected Array<ControlsData> convert(final String rawPreference) { return json.fromJson(Array.class, ControlsData.class, Base64Coder.decodeString(rawPreference)); }
@Override protected String serialize(final Array<ControlsData> preference) { return Base64Coder.encodeString(json.toJson(preference, Array.class, ControlsData.class)); }
@Override public String encrypt(String value) { return Base64Coder.encodeString(value); }
@Override public String decrypt(String value) { return Base64Coder.decodeString(value); }