com.badlogic.gdx.utils.Base64Coder Java Examples

The following examples show how to use com.badlogic.gdx.utils.Base64Coder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SeparatedDataFileResolver.java    From gdx-gltf with Apache License 2.0 6 votes vote down vote up
@Override
public Pixmap load(GLTFImage glImage) {
	if(glImage.uri == null){
		throw new GLTFIllegalException("GLTF image URI cannot be null");
	}else if(glImage.uri.startsWith("data:")){
		// data:application/octet-stream;base64,
		String [] headerBody = glImage.uri.split(",", 2);
		String header = headerBody[0];
		System.out.println(header);
		String body = headerBody[1];
		byte [] data = Base64Coder.decode(body);
		return PixmapBinaryLoaderHack.load(data, 0, data.length);
	}else{
		return new Pixmap(path.child(glImage.uri));
	}
}
 
Example #2
Source File: GameCircleClient.java    From gdx-gamesvcs with Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example #3
Source File: SeparatedDataFileResolver.java    From gdx-gltf with Apache License 2.0 6 votes vote down vote up
private ObjectMap<Integer, ByteBuffer> loadBuffers(FileHandle path) {
	
	if(glModel.buffers != null){
		for(int i=0 ; i<glModel.buffers.size ; i++){
			GLTFBuffer glBuffer = glModel.buffers.get(i);
			ByteBuffer buffer = ByteBuffer.allocate(glBuffer.byteLength);
			buffer.order(ByteOrder.LITTLE_ENDIAN);
			if(glBuffer.uri.startsWith("data:")){
				// data:application/octet-stream;base64,
				String [] headerBody = glBuffer.uri.split(",", 2);
				String header = headerBody[0];
				// System.out.println(header);
				String body = headerBody[1];
				byte [] data = Base64Coder.decode(body);
				buffer.put(data);
			}else{
				FileHandle file = path.child(glBuffer.uri);
				buffer.put(file.readBytes());
			}
			bufferMap.put(i, buffer);
		}
	}
	return bufferMap;
}
 
Example #4
Source File: HighScoreManager.java    From FruitCatcher with Apache License 2.0 6 votes vote down vote up
@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));
	}
}
 
Example #5
Source File: StorageTest.java    From gdx-fireapp with Apache License 2.0 6 votes vote down vote up
@Test
public void upload1() {
    // Given
    byte[] data = {0, 0, 0, 0, 1, 1, 1, 1, 0};
    String path = "/test";
    String encodedData = "base64_encoded_data";
    Mockito.when(Base64Coder.encode(Mockito.eq(data))).thenReturn(encodedData.toCharArray());
    Storage storage = new Storage();


    // When
    storage.upload(path, data).subscribe();

    // Then
    PowerMockito.verifyStatic(StorageJS.class, VerificationModeFactory.times(1));
    StorageJS.upload(Mockito.anyString(), Mockito.eq(path), Mockito.eq(encodedData), Mockito.any(FuturePromise.class));
}
 
Example #6
Source File: HighScoreManager.java    From FruitCatcher with Apache License 2.0 5 votes vote down vote up
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);		
}
 
Example #7
Source File: ProfileManagerGDX.java    From Entitas-Java with MIT License 5 votes vote down vote up
@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);
}
 
Example #8
Source File: StorageTest.java    From gdx-fireapp with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    super.setup();
    PowerMockito.mockStatic(StorageJS.class);
    PowerMockito.mockStatic(Base64Coder.class);
    PowerMockito.mockStatic(ScriptRunner.class);
    PowerMockito.when(ScriptRunner.class, "firebaseScript", Mockito.any(Runnable.class)).then(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) {
            ((Runnable) invocation.getArgument(0)).run();
            return null;
        }
    });
}
 
Example #9
Source File: ImageHelper.java    From gdx-fireapp with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
            GdxFIRLogger.log("Image loaded");
            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);
}
 
Example #10
Source File: Storage.java    From gdx-fireapp with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Promise<FileMetadata> upload(final String path, final byte[] data) {
    return FuturePromise.when(new Consumer<FuturePromise<FileMetadata>>() {
        @Override
        public void accept(final FuturePromise<FileMetadata> promise) {
            ScriptRunner.firebaseScript(new ScriptRunner.ScriptStorageAction(bucketUrl()) {
                @Override
                public void run() {
                    StorageJS.upload(scriptBucketUrl, path, new String(Base64Coder.encode(data)), promise);
                }
            });
        }
    });
}
 
Example #11
Source File: Save.java    From Unlucky with MIT License 5 votes vote down vote up
/**
 * Reads the player data from the save json file and then
 * loads the data into the game through the player
 */
public void load(ResourceManager rm) {
    if (!file.exists()) save();
    psave = json.fromJson(PlayerAccessor.class, Base64Coder.decodeString(file.readString()));

    // load atomic fields
    player.setHp(psave.hp);
    player.setMaxHp(psave.maxHp);
    player.setLevel(psave.level);
    player.setExp(psave.exp);
    player.setMaxExp(psave.maxExp);
    player.setGold(psave.gold);
    player.setMinDamage(psave.minDamage);
    player.setMaxDamage(psave.maxDamage);
    player.setAccuracy(psave.accuracy);
    player.smoveCd = psave.smoveCd;
    player.maxWorld = psave.maxWorld;
    player.maxLevel = psave.maxLevel;

    // load inventory and equips
    loadInventory(rm);
    loadEquips(rm);

    // load smoveset
    for (int i = 0; i < SpecialMoveset.MAX_MOVES; i++) {
        if (psave.smoveset[i] != -1) {
            player.smoveset.addSMove(psave.smoveset[i]);
        }
    }

    // load statistics
    player.stats = psave.stats;

    // load and apply settings
    player.settings = psave.settings;
    if (player.settings.muteMusic) rm.setMusicVolume(0f);
    else rm.setMusicVolume(player.settings.musicVolume);
}
 
Example #12
Source File: Save.java    From Unlucky with MIT License 5 votes vote down vote up
/**
 * Loads the player data into the PlayerAccessor then
 * writes the player save data to the json file
 */
public void save() {
    // load player data
    psave.load(player);
    // write data to save json
    file.writeString(Base64Coder.encodeString(json.prettyPrint(psave)), false);
}
 
Example #13
Source File: GameCircleClient.java    From gdx-gamesvcs with Apache License 2.0 5 votes vote down vote up
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;
    }
}
 
Example #14
Source File: Base64StringEncryptor.java    From gdx-texture-packer-gui with Apache License 2.0 4 votes vote down vote up
@Override
public String encrypt(String value) {
    return Base64Coder.encodeString(value);
}
 
Example #15
Source File: Base64StringEncryptor.java    From gdx-texture-packer-gui with Apache License 2.0 4 votes vote down vote up
@Override
public String decrypt(String value) {
    return Base64Coder.decodeString(value);
}
 
Example #16
Source File: GameJoltClient.java    From gdx-gamesvcs with Apache License 2.0 4 votes vote down vote up
@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);
        }
    });
}
 
Example #17
Source File: GameJoltClient.java    From gdx-gamesvcs with Apache License 2.0 4 votes vote down vote up
@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);
        }
    });
}