Skip to content

Commit

Permalink
Fixed encoding of special characters on Windows
Browse files Browse the repository at this point in the history
  • Loading branch information
kkevinm committed Jan 12, 2020
1 parent 48af42f commit ed49f20
Show file tree
Hide file tree
Showing 4 changed files with 139 additions and 121 deletions.
16 changes: 14 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.github.kevinmussi</groupId>
<artifactId>itunes-discord-rp</artifactId>
<version>1.2</version>
<version>1.3</version>
<packaging>jar</packaging>
<name>iTunes Discord RP</name>
<properties>
Expand Down Expand Up @@ -85,6 +85,18 @@
<groupId>sh.tak.appbundler</groupId>
<artifactId>appbundle-maven-plugin</artifactId>
<version>1.2.0</version>
<dependencies>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-archiver</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
<executions>
<execution>
<phase>package</phase>
Expand Down Expand Up @@ -118,7 +130,7 @@
</executions>
<configuration>
<headerType>gui</headerType>
<outfile>${project.build.directory}/${exec.name}.exe</outfile>
<outfile>${project.build.directory}/${exec.name}-${project.version}.exe</outfile>
<jar>${project.build.directory}/${exec.name}-${project.version}.jar</jar>
<dontWrapJar>false</dontWrapJar>
<errTitle>Error in launch4j plugin</errTitle>
Expand Down
20 changes: 11 additions & 9 deletions src/main/java/com/github/kevinmussi/itunesrp/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,17 @@ public static void main(String[] args) {
}

// Change the encoding to use emojis on Windows
System.setProperty("file.encoding", "UTF-8");
try {
java.lang.reflect.Field charset = null;
charset = java.nio.charset.Charset.class.getDeclaredField("defaultCharset");
charset.setAccessible(true);
charset.set(null, null);
} catch (NoSuchFieldException|IllegalAccessException e) {
LOGGER.log(Level.SEVERE, "An error occurred: ", e);
return;
if(OS == OperativeSystem.WINDOWS) {
System.setProperty("file.encoding", "UTF-8");
try {
java.lang.reflect.Field charset = null;
charset = java.nio.charset.Charset.class.getDeclaredField("defaultCharset");
charset.setAccessible(true);
charset.set(null, null);
} catch (NoSuchFieldException|IllegalAccessException e) {
LOGGER.log(Level.SEVERE, "An error occurred: ", e);
return;
}
}

// Create the ScriptHelper
Expand Down
222 changes: 113 additions & 109 deletions src/main/java/com/github/kevinmussi/itunesrp/core/ScriptHelper.java
Original file line number Diff line number Diff line change
@@ -1,109 +1,113 @@
package com.github.kevinmussi.itunesrp.core;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.github.kevinmussi.itunesrp.commands.ScriptCommand;
import com.github.kevinmussi.itunesrp.data.OperativeSystem;
import com.github.kevinmussi.itunesrp.observer.Commanded;
import com.github.kevinmussi.itunesrp.observer.Observable;

public class ScriptHelper
extends Observable<String> implements Commanded<ScriptCommand> {

public static final String TRACK_RECORD_SEPARATOR = ";;";

private final Logger logger = Logger.getLogger(getClass().getName() + "Logger");

private final ProcessBuilder builder;
private volatile Process process;

public ScriptHelper(OperativeSystem os) throws IOException {
File file = createTempFile(os);
this.builder = new ProcessBuilder(os.getCommandName(), file.getAbsolutePath());
this.process = null;
}

/**
* This method creates a temporary file in the default temporary-file
* directory containing the contents of the script to execute.
* This is done because the resources files in the packaged jar file
* can be loaded only as {@code InputStream} objects, so we need to
* first copy the contents of the stream to a temporary file, and then
* launch the script reading it from that file.
*
* @param os
* @return the temporary file abstract reference.
* @throws IOException If the creation of the temporary file fails.
*/
private File createTempFile(OperativeSystem os) throws IOException {
InputStream inputStream = getClass()
.getResourceAsStream(os.getScriptPath());
File file = File.createTempFile("script", os.getScriptExtension());
try(OutputStream outputStream = new FileOutputStream(file)) {
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
outputStream.write(buffer);
}
inputStream.close();
file.deleteOnExit();
return file;
}

@Override
public boolean onCommand(ScriptCommand command) {
if(command != null) {
if(command == ScriptCommand.EXECUTE) {
if(process == null || !process.isAlive()) {
new Thread(this::executeScript).start();
return true;
}
return false;
} else {
stopScript();
return true;
}
}
return false;
}

public void executeScript() {
if(process != null && process.isAlive()) {
return;
}
try {
process = builder.start();
logger.log(Level.INFO, "The script started execution.");
// The script logs its messages to stderr
Scanner scanner = new Scanner(process.getErrorStream());
scanner.useDelimiter("\n");
while(process != null && process.isAlive()) {
if(scanner.hasNext()) {
sendUpdate(scanner.next());
}
Thread.sleep(1000);
}
scanner.close();
} catch (IOException e) {
logger.log(Level.SEVERE, "The script did not execute correctly", e);
} catch (InterruptedException e) {
logger.log(Level.WARNING, "An error occurred: ", e);
Thread.currentThread().interrupt();
}
}

public void stopScript() {
if(process != null && process.isAlive()) {
process.destroy();
logger.log(Level.INFO, "The script stopped execution.");
}
process = null;
}

}
package com.github.kevinmussi.itunesrp.core;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.github.kevinmussi.itunesrp.commands.ScriptCommand;
import com.github.kevinmussi.itunesrp.data.OperativeSystem;
import com.github.kevinmussi.itunesrp.observer.Commanded;
import com.github.kevinmussi.itunesrp.observer.Observable;

public class ScriptHelper extends Observable<String> implements Commanded<ScriptCommand> {

public static final String TRACK_RECORD_SEPARATOR = ";;";

private final Logger logger = Logger.getLogger(getClass().getName() + "Logger");

private final ProcessBuilder builder;
private volatile Process process;

public ScriptHelper(OperativeSystem os) throws IOException {
File file = createTempFile(os);
this.builder = new ProcessBuilder(os.getCommandName(), file.getAbsolutePath());
this.process = null;
}

/**
* This method creates a temporary file in the default temporary-file directory
* containing the contents of the script to execute. This is done because the
* resources files in the packaged jar file can be loaded only as
* {@code InputStream} objects, so we need to first copy the contents of the
* stream to a temporary file, and then launch the script reading it from that
* file.
*
* @param os
* @return the temporary file abstract reference.
* @throws IOException If the creation of the temporary file fails.
*/
private File createTempFile(OperativeSystem os) throws IOException {
InputStream inputStream = getClass().getResourceAsStream(os.getScriptPath());
File file = File.createTempFile("script", os.getScriptExtension());
try (OutputStream outputStream = new FileOutputStream(file)) {
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
outputStream.write(buffer);
}
inputStream.close();
file.deleteOnExit();
return file;
}

@Override
public boolean onCommand(ScriptCommand command) {
if (command != null) {
if (command == ScriptCommand.EXECUTE) {
if (process == null || !process.isAlive()) {
new Thread(this::executeScript).start();
return true;
}
return false;
} else {
stopScript();
return true;
}
}
return false;
}

public void executeScript() {
if (process != null && process.isAlive()) {
return;
}
try {
process = builder.start();
logger.log(Level.INFO, "The script started execution.");

// The script logs its messages to stderr
Scanner scanner = new Scanner(process.getErrorStream());
scanner.useDelimiter("\n");

while (process != null && process.isAlive()) {
if (scanner.hasNext()) {
String next = scanner.next();
String decoded = URLDecoder.decode(next, StandardCharsets.UTF_8.toString());
sendUpdate(decoded);
}
Thread.sleep(1000);
}
scanner.close();
} catch (IOException e) {
logger.log(Level.SEVERE, "The script did not execute correctly", e);
} catch (InterruptedException e) {
logger.log(Level.WARNING, "An error occurred: ", e);
Thread.currentThread().interrupt();
}
}

public void stopScript() {
if (process != null && process.isAlive()) {
process.destroy();
logger.log(Level.INFO, "The script stopped execution.");
}
process = null;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ function MainLoop() {
}

var output = currentTrack.Name + ";;" + currentTrack.Artist + ";;" + currentTrack.Album + ";;" + state + ";;" + iTunesApp.PlayerPosition + ";;" + currentTrack.Duration + ";;" + currentTrack.TrackNumber + ";;" + currentTrack.TrackCount;
stderr.WriteLine(output);
stderr.WriteLine(encodeURIComponent(output));
}

WScript.sleep(1000);
Expand Down

0 comments on commit ed49f20

Please sign in to comment.