I'm busy creating a modification/plugin to an existing application, my modification includes a Rhino JavaScript scripting engine, the only problem I have is that the ScriptEngine and ScriptEngineManager aren't serializable, this wouldn't be a problem if I could save all the data. How could I do this?
var vertices = RenderUtils.createSquareVertices(64);
var indices = RenderUtils.createSquareIndices();
var mesh = RenderUtils.newStaticMesh(vertices, indices, true);
var textureThingy = RenderUtils.newTexture("NULL.png", Sys.getAssetDir());
var materialThingy = RenderUtils.newMaterial(textureThingy, Math.newVector3f(1, 1, 1), 1, 1);
var renderMesh = RenderUtils.newMeshRenderer(mesh, materialThingy);
var rotationAngle = 0.0;
function update() {
if(Mouse.isButtonDown(0)) rotationAngle=rotationAngle + 1.0;
if(Mouse.isButtonDown(1)) rotationAngle=rotationAngle - 1.0;
}
function render() {
renderMesh.getTransform().getPos().setVector(Sys.getWidth()/2, Sys.getHeight()/2, 0);
renderMesh.getTransform().setRotation(Math.newVector3f(0, 0, 1), rotationAngle);
renderMesh.render();
}
The java side:
public void start() {
try {
this.Script.eval(this.ApplicationCode);
} catch(ScriptException e) {
e.printStackTrace();
}
}
public void update() {
if(this.hasUpdateFunc) {
try {
if(this.Script != null) ((Invocable)this.Script).invokeFunction("update");
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
public void render() {
if(this.hasRenderFunc) {
try {
if(this.Script != null) ((Invocable)this.Script).invokeFunction("render");
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
Related
// column: bigint
if (getTypes(column, struct).equalsIgnoreCase("bigint")) {
if (!lineArray[column].isEmpty()) {
try {
((LongColumnVector) batch.cols[column]).vector[row] = Long.parseLong(lineArray[column]);
} catch (NumberFormatException e) {
HiveDecimal hiveDecimal = HiveDecimal.create(lineArray[column]);
batch.cols[column]=new DecimalColumnVector(lineArray[column].length(), 0);
((DecimalColumnVector) batch.cols[column]).vector[row] = (new HiveDecimalWritable(hiveDecimal));
} catch (Exception e) {
e.printStackTrace();
}
} else {
((LongColumnVector) batch.cols[column]).noNulls = false;
((LongColumnVector) batch.cols[column]).isNull[row] = true;
((LongColumnVector) batch.cols[column]).vector[row] = LongColumnVector.NULL_VALUE;
// ((CustomLongColumnVector) batch.cols[column]).fillWithNulls();
}
}
I am trying to execute the above code snippet . lineArray is a String Array. But it is failing with java.lang.ClassCastException: org.apache.hadoop.hive.ql.exec.vector.DecimalColumnVector cannot be cast to org.apache.hadoop.hive.ql.exec.vector.LongColumnVector. Please help.
The problem I am having is acquiring all reachable clients on a network.The below method returns some clients when called. In most cases other android clients.However for the PC it fails when firewall is on.Is there a more effective way to get all clients in Java/android purely or will I need to use android NDK?Any help from experts in this domain will be appreciated.Thanks in advance.
/***
* ping_JavaStyle(final int j)
* uses multi threads to enhance performance
* while pinging from 0>j<=255
* #param j
*/
private void ping_JavaStyle(final int j)
{
new Thread(new Runnable() { // new thread for parallel execution
public void run() {
try {
String testIp = prefix + String.valueOf(j);
InetAddress address = InetAddress.getByName(testIp);
String output = address.toString().substring(1);
if (address.isReachable(3000)) {
System.out.println(output + " is on the network");
ipList.add(testIp);
} else {
if (retest(testIp, 139)) {
ipList.add(testIp);
} else {
System.out.println("Not Reachable: " + output);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
After Researching some more, got this working.With help of this repo:https://github.com/stealthcopter/AndroidNetworkTools
Below code solves the problem:
** RunnableTask.Java
* Created by Kirk on 10/29/2017.
*/
public class RunnableTask implements Callable<Boolean> {
private String testIp = "";
private Boolean is_Reachable = false;
public RunnableTask(String testIp) {
this.testIp = testIp;
}
#Override
public Boolean call() throws Exception {
try {
PingResult pingResult = Ping.onAddress(this.testIp).setTimes(1).setTimeOutMillis(1500).doPing();
if (pingResult.isReachable) {
is_Reachable = true;
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
return is_Reachable;
}
}
And use in the caller method:
private static final int NTHREDS = 255;
//.......
ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
List<Future<Boolean>> thread_Values_list = new ArrayList<>();
for (int i = 1; i <= 255; i++) {
final int j = i;
try {
try {
String testIp = prefix + String.valueOf(j);
RunnableTask worker = new RunnableTask(testIp);
Future<Boolean> submit = executor.submit(worker);
thread_Values_list.add(submit);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
}
}
for (Future<Boolean> finishedThread : thread_Values_list) {
String reachable_Ip = "";
try {
if (finishedThread.get()) {
reachable_Ip = prefix + String.valueOf(finishThread_counter);
ipList.add(reachable_Ip);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
finishThread_counter++;
}
executor.shutdown();
}
I'm trying to consolidate 2 methods into 1, because they handle exceptions the same way. I know in C# you can pass functions/actions as parameters into other functions. I tried creating a generic method to invoke a function, but can't seem to figure it out.
public String getTheStuff(String client) {
try {
return extService.getProduct(client);
} catch (UIException e) {
notHealthy();
} catch (HostException e) {
notHealthy();
} catch (Exception e) {
Throwables.propagate(e);
}
}
public CustomType getsomeMoreStuff(String source, int offset) {
try {
return extService.getMetrics(source, offset);
} catch (UIException e) {
notHealthy();
} catch (HostException e) {
notHealthy();
} catch (Exception e) {
Throwables.propagate(e);
}
}
What I'm looking for is something like
public T invokeExtService(Function functionToInvoke, Parameters[] params){
try {
return functionToInvoke.Invoke(params);
} catch (UIException e) {
notHealthy();
} catch (HostException e) {
notHealthy();
} catch (Exception e) {
Throwables.propagate(e);
}
}
As #LouisWasserman said, this would be much nicer in Java 8, but how about something like this (untested):
public <T> T invoke(Callable<T> function) {
try {
return function.call();
} catch (UIException e) {
notHealthy();
} catch (HostException e) {
notHealthy();
} catch (Exception e) {
Throwables.propagate(e);
}
}
public String getTheStuff(final String client) {
return invoke(new Callable<String>() {
#Override
public String call() {
return extService.getProduct(client);
}
});
}
public CustomType getsomeMoreStuff(final String source, final int offset) {
return invoke(new Callable<CustomType>() {
#Override
public CustomType call() {
return extService.getMetrics(source, offset);
}
});
}
To be honest, I'm not sure how worthwhile this is considering how short your methods are (and they could be even shorter with multi-catch).
I have desktop and android applications, which connected by bluetooth(in desktop side I use Bluecove 2.1.1 library). Desktop application create bluetooth service then android application connects to it. I want to add logout functionality from both desktop and android sides. For example in desktop app user click disconnect, both desktop and android apps reset their connections and should be able to connect again. Here is bluetoothService code for desktop side:
public class BluetoothService
{
private static final String serviceName = "btspp://localhost:"
// + new UUID("0000110100001000800000805F9B34F7", false).toString()
// + new UUID("0000110100001000800000805F9B34F8", false).toString()
+ new UUID("0000110100001000800000805F9B34F9", false).toString()
+ ";name=serviceName";
private StreamConnectionNotifier m_service = null;
private ListenerThread m_listenerThread;
private DataOutputStream m_outStream;
public BluetoothService()
{
Open();
}
public void Open()
{
try
{
assert (m_service == null);
m_service = (StreamConnectionNotifier) Connector.open(serviceName);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void Start()
{
try
{
StreamConnection connection = (StreamConnection) m_service
.acceptAndOpen();
System.out.println("Connected");
m_listenerThread = new ListenerThread(connection);
Thread listener = new Thread(m_listenerThread);
listener.start();
m_outStream = new DataOutputStream(connection.openOutputStream());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void Send(String message)
{
assert (m_listenerThread != null);
try
{
m_outStream.writeUTF(message);
m_outStream.flush();
System.out.println("Sent: " + message);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void Close()
{
try
{
m_service.close();
m_listenerThread.Stop();
m_listenerThread = null;
m_outStream.close();
m_outStream = null;
m_service = null;
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
class ListenerThread implements Runnable
{
private DataInputStream m_inStream;
private boolean m_isRunning;
public ListenerThread(StreamConnection connection)
{
try
{
this.m_inStream = new DataInputStream(connection.openInputStream());
m_isRunning = true;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
;
}
public void run()
{
while (m_isRunning)
{
try
{
assert (m_inStream != null);
if (m_inStream.available() > 0)
{
String message = m_inStream.readUTF();
System.out.println("Received command: " + message);
CommandManager.getInstance().Parse(message);
}
}
catch (IOException e)
{
System.err.println(e.toString());
}
}
}
public void Stop()
{
m_isRunning = false;
try
{
m_inStream.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
for restarting service I do:
BluetoothService::Close();
BluetoothService::Open();
BluetoothService::Start();
but seems I cannot reconnect. Maybe I should create service with different name?
Im trying to use ZXing library to develop a Java project for decoding a QR code. However, some of the image containing QR code can not be decoded by running my project, but these are working fine with Online ZXing decoder. I am just curious does the ZXing released version is the same as they are using for Online decoder? or they have tweaked the online version. I'm pulling my hair because of this confusion.
public class Validator implements IValidator {
private static Logger logger = Logger.getLogger(Validator.class);
private BufferedImage currentImage;
private String resultText;
private float moduleSize;
private ResultPoint[] patternCenters;
private int blockSizePower;
public Validator(BufferedImage imageFile) {
this.currentImage = imageFile;
setLuminanceThreshold(3); //default value used by validator
}
public Validator(File imageFile) {
// take input image file and store in a BufferedImage variable
try {
currentImage = ImageIO.read(imageFile);
} catch (IOException e) {
logger.error("Image cannot be opened. There is no such image file. ", e);
}
}
/**
* <p>Validating the QR code</p>
*
* #return true if the QR code can be decoded
*/
#Override
public boolean validateQRCode() {
return validateQRCode(null);
}
public boolean validateQRCode(Hashtable outValues) {
return validateQRCode(outValues, true);
}
// if localLuminanceCheck == true then call HybridBinarizer, otherwise call GlobalHistogramBinarizer
public boolean validateQRCode(Hashtable outValues, boolean localLuminanceCheck)
{
return validateQRCode(outValues, true, false);
}
public boolean validateQRCode(Hashtable outValues, boolean localLuminanceCheck, boolean scale) {
if (scale)
{
try {
this.currentImage = Thumbnails.of(currentImage).size(275, 275).asBufferedImage();
} catch (IOException e) {
logger.error("Image cannot be scaled. ", e);
}
}
// finding luminance of the image
LuminanceSource lumSource = new BufferedImageLuminanceSource(currentImage);
Binarizer qrHB;
if (!localLuminanceCheck) {
qrHB = new GlobalHistogramBinarizer(lumSource);
} else {
// creating binary bitmap from Black-White image
qrHB = new HybridBinarizer(lumSource);
((HybridBinarizer) qrHB).setBLOCK_SIZE_POWER(blockSizePower);
}
BinaryBitmap bitmap = new BinaryBitmap(qrHB);
try {
currentImage = MatrixToImageWriter.toBufferedImage(bitmap.getBlackMatrix());
} catch (NotFoundException e) {
logger.error("cannot find any bit matrix.", e);
}
Hashtable<DecodeHintType, Object> hint = new Hashtable<DecodeHintType, Object>();
hint.put(DecodeHintType.TRY_HARDER, BarcodeFormat.QR_CODE);
QRCodeReader QRreader = new QRCodeReader();
try {
// decodes the QR code
Result result = QRreader.decode(bitmap, hint);
resultText = result.getText();
return true;
} catch (NotFoundException e) {
logger.info("cannot detect any QR code (no enough finder patterns).");
return false;
} catch (ChecksumException e) {
logger.info("cannot recover the QR code. Too much data errors.");
return false;
} catch (FormatException e) {
logger.info("QR code cannot be decoded.");
return false;
} catch (FinderPatternNotFoundException e) {
// if no Finder Pattern has been found, it may be the color of
// QR is inverted. So we invert the QR and try one more time
Binarizer invertHB;
if (!localLuminanceCheck) {
invertHB = new GlobalHistogramBinarizer(lumSource);
} else {
invertHB = new HybridBinarizer(lumSource);
((HybridBinarizer) invertHB).setBLOCK_SIZE_POWER(blockSizePower);
}
// get the inverted Black-White matrix
BitMatrix invertBlackMatrix = null;
try {
invertBlackMatrix = invertHB.getBlackMatrix();
} catch (NotFoundException e1) {
logger.error(e1);
}
int invertWidth = currentImage.getWidth();
int invertHeight = currentImage.getHeight();
// flip each bit in the inverted BitMatrix
for (int x = 0; x < invertWidth; x++) {
for (int y = 0; y < invertHeight; y++) {
invertBlackMatrix.flip(x, y);
}
}
currentImage = MatrixToImageWriter.toBufferedImage(invertBlackMatrix);
// get luminance source from inverted image
lumSource = new BufferedImageLuminanceSource(currentImage);
Binarizer afterInvertHB;
if (!localLuminanceCheck) {
afterInvertHB = new GlobalHistogramBinarizer(lumSource);
} else {
// creating binary bitmap from Black-White image
afterInvertHB = new HybridBinarizer(lumSource);
((HybridBinarizer) afterInvertHB).setBLOCK_SIZE_POWER(blockSizePower);
}
BinaryBitmap invertBitMap = new BinaryBitmap(afterInvertHB);
// decoding inverted QR
QRCodeReader invertQRreader = new QRCodeReader();
try {
Result invertResult = invertQRreader.decode(invertBitMap, hint);
resultText = invertResult.getText();
System.out.println("Out put data is: " + resultText);
return true;
} catch (NotFoundException e1) {
logger.info("cannot detect any QR code (no enough finder patterns).");
return false;
} catch (ChecksumException e1) {
logger.info("cannot recover the QR code. Too much data errors.");
return false;
} catch (FormatException e1) {
logger.info("QR code cannot be decoded.");
return false;
} catch (FinderPatternNotFoundException e1) {
logger.info("Cannot confirm where all three Finder Patterns are! ");
return false;
} catch (Exception e1) {
logger.error(e1);
return false;
}
} catch (Exception e) {
logger.error(e);
return false;
}
}
}
It's not different, it's probably that you are not using TRY_HARDER mode, or are not trying both binarizers. The online version will do those things.