Get ShoutCast/IceStream metadata with mp3spi1.9.5 - java

I am using JLayer to stream online radio music so a simple code for this is here:(Where StreamPlayer is a special implementation of JLayer)
//Radio Station URL example is http://radio.flex.ru:8000/radionami
/**
* Plays the Given Online Stream
*
* #param url
* <b> The Specified url you want to connect </b>
* #throws IOException
* #throws JavaLayerException
*/
public void playRadioStream(URL spec) {
try {
// Connection
URLConnection urlConnection = spec.openConnection();
// Connecting
urlConnection.connect();
// Try to play it
StreamPlayer player = new StreamPlayer();
player.open((urlConnection.getInputStream()));
player.play();
} catch (StreamPlayerException | IOException e) {
e.printStackTrace();
}
}
The problem:
I can't figure out how to retrieve information from this connection like the song is playing now from this Radio Station or the name of Station etc...The help is really appreciated!!
Edit:
If you want you can use JLayer instead of StreamPlayer it will work ,although you have to run it on different Thread from the main app Thread.

Related

Twilio: How can I send a link on the body message

I need to send a whatsapp message with a link in its content using twilio.
Here is my code:
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
Message message = Message.creator(
new PhoneNumber("whatsapp:" + phoneNumber),
new PhoneNumber("whatsapp:" + PHONE_FROM),
"Hello: http://www.google.com")
.create();
How can I send a link on the body message. Please help!!
Use this creator method from MessageCreator class.
/**
* Create a MessageCreator to execute create.
*
* #param to The phone number to receive the message
* #param from The phone number that initiated the message
* #param mediaUrl The media_url
* #return MessageCreator capable of executing the create
*/
public static MessageCreator creator(final com.twilio.type.PhoneNumber to,
final com.twilio.type.PhoneNumber from,
final List<URI> mediaUrl) {
return new MessageCreator(to, from, mediaUrl);
}
Also, checkout another question related to this problem.

IOException writing data to NFC card

I am trying to write data to an NFC card using an Android application but when I try to write the data I get a java.io.IOExcetion. The log tells me that it is null. I have added printstacktrace and it points to an error at android.nfc.tech.NdefFormatble.format(NdefFormarmatable.java:131) and android.nfc.tech.NdefFormatble.format(NdefFormarmatable.java:94). I have had a look at this class to see what the error is and Android Studio says that it cannot resolve symbol on some of the imports in that class. I can not figure out what is going wrong and I would appreciate any help in sorting this problem. I did have this working before and then all of a sudden I started getting this error. I did update Android Studio to 3.1.1 but I tried using AS 3.0 and 2.3 but I get the same error. I have included the methods which all being called as well as the stacktrace.
This is where the card is formatted and written to:
private void formatTag(Tag tag, NdefMessage ndefMessage) {
try {
NdefFormatable ndefFormatable = NdefFormatable.get(tag);
if (ndefFormatable == null) {
Toast.makeText(this, "Tag is not ndef formatable!", Toast.LENGTH_SHORT).show();
return;
}
ndefFormatable.connect();
ndefFormatable.format(ndefMessage); ***<----MainActivity.java:469***
ndefFormatable.close();
Toast.makeText(this, "Tag writen!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e("formatTag", "" + e.getMessage());
e.printStackTrace();
}
}
This is the method for writing the NDEF message
private void writeNdefMessage(Tag tag, NdefMessage ndefMessage) {
try {
if (tag == null) {
Toast.makeText(this, "Tag object cannot be null", Toast.LENGTH_SHORT).show();
return;
}
Ndef ndef = Ndef.get(tag);
if (ndef == null) {
// format tag with the ndef format and writes the message.
formatTag(tag, ndefMessage); **<----- MainActivity.java 494**
} else {
ndef.connect();
if (!ndef.isWritable()) {
Toast.makeText(this, "Tag is not writable!", Toast.LENGTH_SHORT).show();
ndef.close();
return;
}
ndef.writeNdefMessage(ndefMessage);
ndef.close();
Toast.makeText(this, "Tag writen!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e("writeNdefMessage", "" + e.getMessage());
e.printStackTrace();
}
This is where writeNdefMessage is call from
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) {
Toast.makeText(this, "NfcIntent!", Toast.LENGTH_SHORT).show();
if(tglReadWrite.isChecked())
{
Parcelable[] parcelables = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if(parcelables != null && parcelables.length > 0)
{
readDataFromMessage((NdefMessage) parcelables[0]);
}else{
Toast.makeText(this, "No NDEF messages found!", Toast.LENGTH_SHORT).show();
}
}else{
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
NdefMessage ndefMessage = createNdefMessage(mToken.getText()+";");
writeNdefMessage(tag, ndefMessage); ***<---- MainActivity.java:406***
}
}
}
and here is the StackTrace
04-13 02:50:51.112 6311-6311/com.appsolutedevelopment.labourstaff E/formatTag: null
04-13 02:50:51.112 6311-6311/com.appsolutedevelopment.labourstaff W/System.err: java.io.IOException
04-13 02:50:51.113 6311-6311/com.appsolutedevelopment.labourstaff W/System.err: at android.nfc.tech.NdefFormatable.format(NdefFormatable.java:131)
at android.nfc.tech.NdefFormatable.format(NdefFormatable.java:94)
at com.appsolutedevelopment.labourstaff.MainActivity.formatTag(MainActivity.java:469)
at com.appsolutedevelopment.labourstaff.MainActivity.writeNdefMessage(MainActivity.java:494)
at com.appsolutedevelopment.labourstaff.MainActivity.onNewIntent(MainActivity.java:406)
at android.app.Instrumentation.callActivityOnNewIntent(Instrumentation.java:1228)
at android.app.Instrumentation.callActivityOnNewIntent(Instrumentation.java:1240)
at android.app.ActivityThread.deliverNewIntents(ActivityThread.java:2946)
at android.app.ActivityThread.performNewIntents(ActivityThread.java:2958)
at android.app.ActivityThread.handleNewIntent(ActivityThread.java:2967)
at android.app.ActivityThread.-wrap15(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1648)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
And finally the NdefFormatable class
package android.nfc.tech;
import android.nfc.ErrorCodes; ***<---- Cannot resolve symbol 'ErrorCodes'***
import android.nfc.FormatException;
import android.nfc.INfcTag; ***<---- Cannot resolve symbol 'INfcTag'***
import android.nfc.NdefMessage;
import android.nfc.Tag;
import android.nfc.TagLostException;
import android.os.RemoteException;
import android.util.Log;
import java.io.IOException;
/**
* Provide access to NDEF format operations on a {#link Tag}.
*
* <p>Acquire a {#link NdefFormatable} object using {#link #get}.
*
* <p>Android devices with NFC must only enumerate and implement this
* class for tags for which it can format to NDEF.
*
* <p>Unfortunately the procedures to convert unformated tags to NDEF formatted
* tags are not specified by NFC Forum, and are not generally well-known. So
* there is no mandatory set of tags for which all Android devices with NFC
* must support {#link NdefFormatable}.
*
* <p class="note"><strong>Note:</strong> Methods that perform I/O operations
* require the {#link android.Manifest.permission#NFC} permission.
*/
public final class NdefFormatable extends BasicTagTechnology {
private static final String TAG = "NFC";
/**
* Get an instance of {#link NdefFormatable} for the given tag.
* <p>Does not cause any RF activity and does not block.
* <p>Returns null if {#link NdefFormatable} was not enumerated in {#link Tag#getTechList}.
* This indicates the tag is not NDEF formatable by this Android device.
*
* #param tag an NDEF formatable tag
* #return NDEF formatable object
*/
public static NdefFormatable get(Tag tag) {
if (!tag.hasTech(TagTechnology.NDEF_FORMATABLE)) return null;
try {
return new NdefFormatable(tag);
} catch (RemoteException e) {
return null;
}
}
/**
* Internal constructor, to be used by NfcAdapter
* #hide
*/
public NdefFormatable(Tag tag) throws RemoteException {
super(tag, TagTechnology.NDEF_FORMATABLE);
}
/**
* Format a tag as NDEF, and write a {#link NdefMessage}.
*
* <p>This is a multi-step process, an IOException is thrown
* if any one step fails.
* <p>The card is left in a read-write state after this operation.
*
* <p>This is an I/O operation and will block until complete. It must
* not be called from the main application thread. A blocked call will be canceled with
* {#link IOException} if {#link #close} is called from another thread.
*
* <p class="note">Requires the {#link android.Manifest.permission#NFC} permission.
*
* #param firstMessage the NDEF message to write after formatting, can be null
* #throws TagLostException if the tag leaves the field
* #throws IOException if there is an I/O failure, or the operation is canceled
* #throws FormatException if the NDEF Message to write is malformed
*/
public void format(NdefMessage firstMessage) throws IOException, FormatException {
format(firstMessage, false); ***<----NdefFormatable.java:94***
}
/**
* Formats a tag as NDEF, write a {#link NdefMessage}, and make read-only.
*
* <p>This is a multi-step process, an IOException is thrown
* if any one step fails.
* <p>The card is left in a read-only state if this method returns successfully.
*
* <p>This is an I/O operation and will block until complete. It must
* not be called from the main application thread. A blocked call will be canceled with
* {#link IOException} if {#link #close} is called from another thread.
*
* <p class="note">Requires the {#link android.Manifest.permission#NFC} permission.
*
* #param firstMessage the NDEF message to write after formatting
* #throws TagLostException if the tag leaves the field
* #throws IOException if there is an I/O failure, or the operation is canceled
* #throws FormatException if the NDEF Message to write is malformed
*/
public void formatReadOnly(NdefMessage firstMessage) throws IOException, FormatException {
format(firstMessage, true);
}
/*package*/ void format(NdefMessage firstMessage, boolean makeReadOnly) throws IOException,
FormatException {
checkConnected();
try {
int serviceHandle = mTag.getServiceHandle();
INfcTag tagService = mTag.getTagService();
int errorCode = tagService.formatNdef(serviceHandle, MifareClassic.KEY_DEFAULT);
switch (errorCode) {
case ErrorCodes.SUCCESS:
break;
case ErrorCodes.ERROR_IO:
throw new IOException(); ***<---- NdefFormatable.java:131***
case ErrorCodes.ERROR_INVALID_PARAM:
throw new FormatException();
default:
// Should not happen
throw new IOException();
}
// Now check and see if the format worked
if (!tagService.isNdef(serviceHandle)) {
throw new IOException();
}
// Write a message, if one was provided
if (firstMessage != null) {
errorCode = tagService.ndefWrite(serviceHandle, firstMessage);
switch (errorCode) {
case ErrorCodes.SUCCESS:
break;
case ErrorCodes.ERROR_IO:
throw new IOException();
case ErrorCodes.ERROR_INVALID_PARAM:
throw new FormatException();
default:
// Should not happen
throw new IOException();
}
}
// optionally make read-only
if (makeReadOnly) {
errorCode = tagService.ndefMakeReadOnly(serviceHandle);
switch (errorCode) {
case ErrorCodes.SUCCESS:
break;
case ErrorCodes.ERROR_IO:
throw new IOException();
case ErrorCodes.ERROR_INVALID_PARAM:
throw new IOException();
default:
// Should not happen
throw new IOException();
}
}
} catch (RemoteException e) {
Log.e(TAG, "NFC service dead", e);
}
}
}
If I have missed anything or anybody needs more info put up just ask and I'll get whatever is needed. Id be very grateful if someone could shed some light on this as it has been driving me around the twist for so long.
Thanks.
I found the answer to this question here Android NFC - ndef.writeNdefMessage() throws IOException and erases tag data. This explains what is going on in my app when I try to write to the NFC card after an unsuccessful write operation. If anyone is looking for a solution to this problem then this Android nfcA.connect(), nfcA.transceive(), nfcA.setTimeout() and nfcA.getMaxTransceiveLength() might be of some help. If reading and writing critical data to NFC tokens/cards is what you are trying to achieve then I would suggest using nfcA as oppossed to NDEF.

Quickblox android chat - audio attachment uploading failed

I am trying to upload an audio file using quickblox api. I am able to upload audio attachment in my Nexus 7. The issue is, when I try to upload audio files using the same code, in other available devices (Asus zenphone and Karbonn Android one) , I am getting quickblox response exception. The exception is "content_type is too short (minimum is 5 characters),content_type is invalid". Please someone help me with this exception. I am getting exception in the following block.
/**
* This method will invoke when user try to upload a file in the chatbox.
*
* #param dialogId
* #param inputFile
* #param messageId
* #return
* #throws Exception
*
**/
public QBFile loadAttachFile(String dialogId, final File inputFile, final String messageId) throws Exception {
QBFile file = null;
try {
file = QBContent.uploadFileTask(inputFile, true, (String) null,
new QBProgressCallback() {
#Override
public void onProgressUpdate(int arg0) {
// TODO Auto-generated method stub
if (!lastUpdatedProgress.contains(arg0)) {
lastUpdatedProgress.add(arg0);
//Here we will update the progress of the progressbar details
updateAttachmentUploadingProgress(messageId, arg0);
}
}
});
} catch (QBResponseException exc) {
throw new Exception(context.getString(R.string.dlg_fail_upload_attach) );
}
return file;
}
This was an issue with 'acc' file format and 'android.webkit.MimeTypeMap' class
QuickBlox has released the Android SDK 2.3 version with the fix
http://quickblox.com/developers/Android#Framework_changelog
Check it out

Getting error Error: Could not find or load main class JavaFixHistoryMiner, Don't know how to fix

Everything in the code seems fine. I do not understand why it is giving me this error.
Using Eclipse IDE (Juno), I've clicked "Run" and got the following message on the console:
Error: Could not find or load main class JavaFixHistoryMiner
This was an imported file, I also added an external library
/**
* Example of how to request and process historical rate data from the Java API
*
* #author rkichenama
*/
public class JavaFixHistoryMiner
implements IGenericMessageListener, IStatusMessageListener
{
private static final String server = "http://www.fxcorporate.com/Hosts.jsp";
private static final String TEST_CURRENCY = "EUR/USD";
private FXCMLoginProperties login;
private IGateway gateway;
private String currentRequest;
private boolean requestComplete;
private ArrayList<CollateralReport> accounts = new ArrayList<CollateralReport>();
private HashMap<UTCDate, MarketDataSnapshot> historicalRates = new HashMap<UTCDate, MarketDataSnapshot>();
private static PrintWriter output = new PrintWriter((OutputStream)System.out, true);
public PrintWriter getOutput() { return output; }
public void setOutput(PrintWriter newOutput) { output = newOutput; }
/**
* Creates a new JavaFixHistoryMiner with credentials with configuration file
*
* #param username
* #param password
* #param terminal - which terminal to login into, dependent on the type of account, case sensitive
* #param server - url, like 'http://www.fxcorporate.com/Hosts.jsp'
* #param file - a local file used to define configuration
*/
public JavaFixHistoryMiner(String username, String password, String terminal, String file)
{
// if file is not specified
if(file == null)
// create a local LoginProperty
this.login = new FXCMLoginProperties(username, password, terminal, server);
else
this.login = new FXCMLoginProperties(username, password, terminal, server, file);
}
/**
* Creates a new JavaFixHistoryMiner with credentials and no configuration file
*
* #param username
* #param password
* #param terminal - which terminal to login into, dependent on the type of account, case sensitive
* #param server - url, like 'http://www.fxcorporate.com/Hosts.jsp'
*/
public JavaFixHistoryMiner(String username, String password, String terminal)
{
// call the proper constructor
this(username, password, terminal, null);
}
public JavaFixHistoryMiner(String[] args)
{
// call the proper constructor
this(args[0], args[1], args[2], null);
}
/**
* Attempt to login with credentials supplied in constructor, assigning self as listeners
*/
public boolean login()
{
return this.login(this, this);
}
/**
* Attempt to login with credentials supplied in constructor
*
* #param genericMessageListener - the listener object for trading events
* #param statusMessageListener - the listener object for status events
*
* #return true if login successful, false if not
*/
public boolean login(IGenericMessageListener genericMessageListener, IStatusMessageListener statusMessageListener)
{
try
{
// if the gateway has not been defined
if(gateway == null)
// assign it to a new gateway created by the factory
gateway = GatewayFactory.createGateway();
// register the generic message listener with the gateway
gateway.registerGenericMessageListener(genericMessageListener);
// register the status message listener with the gateway
gateway.registerStatusMessageListener(statusMessageListener);
// if the gateway has not been connected
if(!gateway.isConnected())
{
// attempt to login with the local login properties
gateway.login(this.login);
}
else
{
// attempt to re-login to the api
gateway.relogin();
}
// set the state of the request to be incomplete
requestComplete = false;
// request the current trading session status
currentRequest = gateway.requestTradingSessionStatus();
// wait until the request is complete
while(!requestComplete) {}
// return that this process was successful
return true;
}
catch(Exception e) { e.printStackTrace(); }
// if any error occurred, then return that this process failed
return false;
}
/**
* Attempt to logout, assuming that the supplied listeners reference self
*/
public void logout()
{
this.logout(this, this);
}
/**
* Attempt to logout, removing the supplied listeners prior to disconnection
*
* #param genericMessageListener - the listener object for trading events
* #param statusMessageListener - the listener object for status events
*/
public void logout(IGenericMessageListener genericMessageListener, IStatusMessageListener statusMessageListener)
{
// attempt to logout of the api
gateway.logout();
// remove the generic message listener, stop listening to updates
gateway.removeGenericMessageListener(genericMessageListener);
// remove the status message listener, stop listening to status changes
gateway.removeStatusMessageListener(statusMessageListener);
}
/**
* Request a refresh of the collateral reports under the current login
*/
public void retrieveAccounts()
{
// if the gateway is null then attempt to login
if(gateway == null) this.login();
// set the state of the request to be incomplete
requestComplete = false;
// request the refresh of all collateral reports
currentRequest = gateway.requestAccounts();
// wait until all the reqports have been processed
while(!requestComplete) {}
}
/**
* Send a fully formed order to the API and wait for the response.
*
* #return the market order number of placed trade, NONE if the trade did not execute, null on error
*/
public String sendRequest(ITransportable request)
{
try
{
// set the completion status of the requst to false
requestComplete = false;
// send the request message to the api
currentRequest = gateway.sendMessage(request);
// wait until the api answers on this particular request
// while(!requestComplete) {}
// if there is a value to return, it will be passed by currentResult
return currentRequest;
}
catch(Exception e) { e.printStackTrace(); }
// if an error occured, return no result
return null;
}
/**
* Implementing IStatusMessageListener to capture and process messages sent back from API
*
* #param status - status message received by API
*/
#Override public void messageArrived(ISessionStatus status)
{
// check to the status code
if(status.getStatusCode() == ISessionStatus.STATUSCODE_ERROR ||
status.getStatusCode() == ISessionStatus.STATUSCODE_DISCONNECTING ||
status.getStatusCode() == ISessionStatus.STATUSCODE_CONNECTING ||
status.getStatusCode() == ISessionStatus.STATUSCODE_CONNECTED ||
status.getStatusCode() == ISessionStatus.STATUSCODE_CRITICAL_ERROR ||
status.getStatusCode() == ISessionStatus.STATUSCODE_EXPIRED ||
status.getStatusCode() == ISessionStatus.STATUSCODE_LOGGINGIN ||
status.getStatusCode() == ISessionStatus.STATUSCODE_LOGGEDIN ||
status.getStatusCode() == ISessionStatus.STATUSCODE_PROCESSING ||
status.getStatusCode() == ISessionStatus.STATUSCODE_DISCONNECTED)
{
// display status message
output.println("\t\t" + status.getStatusMessage());
}
}
/**
* Implementing IGenericMessageListener to capture and process messages sent back from API
*
* #param message - message received for processing by API
*/
#Override public void messageArrived(ITransportable message)
{
// decide which child function to send an cast instance of the message
try
{
// if it is an instance of CollateralReport, process the collateral report
if(message instanceof CollateralReport) messageArrived((CollateralReport)message);
// if it is an instance of MarketDataSnapshot, process the historical data
if(message instanceof MarketDataSnapshot) messageArrived((MarketDataSnapshot)message);
// if it is an instance of MarketDataRequestReject, process the historical data request error
if(message instanceof MarketDataRequestReject) messageArrived((MarketDataRequestReject)message);
// if the message is an instance of TradingSessionStatus, cast it and send to child function
else if(message instanceof TradingSessionStatus) messageArrived((TradingSessionStatus)message);
}
catch(Exception e) { e.printStackTrace(output); }
}
/**
* Separate function to handle collateral report requests
*
* #param cr - message interpreted as an instance of CollateralReport
*/
public void messageArrived(CollateralReport cr)
{
// if this report is the result of a direct request by a waiting process
if(currentRequest.equals(cr.getRequestID()) && !accounts.contains(cr))
{
// add the trading account to the account list
accounts.add(cr);
// set the state of the request to be completed only if this is the last collateral report
// requested
requestComplete = cr.isLastRptRequested();
}
}
/**
/**
* Separate function to handle the trading session status updates and pull the trading instruments
*
* #param tss - the message interpreted as a TradingSessionStatus instance
*/
public void messageArrived(TradingSessionStatus tss)
{
// check to see if there is a request from main application for a session update
if(currentRequest.equals(tss.getRequestID()))
{
// set that the request is complete for any waiting thread
requestComplete = true;
// attempt to set up the historical market data request
try
{
// create a new market data request
MarketDataRequest mdr = new MarketDataRequest();
// set the subscription type to ask for only a snapshot of the history
mdr.setSubscriptionRequestType(SubscriptionRequestTypeFactory.SNAPSHOT);
// request the response to be formated FXCM style
mdr.setResponseFormat(IFixDefs.MSGTYPE_FXCMRESPONSE);
// set the intervale of the data candles
mdr.setFXCMTimingInterval(FXCMTimingIntervalFactory.MIN15);
// set the type set for the data candles
mdr.setMDEntryTypeSet(MarketDataRequest.MDENTRYTYPESET_ALL);
// configure the start and end dates
Date now = new Date();
Calendar calendar = (Calendar)Calendar.getInstance().clone();
calendar.setTime(now);
calendar.add(Calendar.DAY_OF_MONTH, -1);
Date beforeNow = calendar.getTime();
// set the dates and times for the market data request
mdr.setFXCMStartDate(new UTCDate(beforeNow));
mdr.setFXCMStartTime(new UTCTimeOnly(beforeNow));
mdr.setFXCMEndDate(new UTCDate(now));
mdr.setFXCMEndTime(new UTCTimeOnly(now));
// set the instrument on which the we want the historical data
mdr.addRelatedSymbol(tss.getSecurity(TEST_CURRENCY));
// send the request
sendRequest(mdr);
}
catch(Exception e) { e.printStackTrace(); }
}
}
/**
* Separate function to handle the rejection of a market data historical snapshot
*
* #param mdrr - message interpreted as an instance of MarketDataRequestReject
*/
public void messageArrived(MarketDataRequestReject mdrr)
{
// display note consisting of the reason the request was rejected
output.println("Historical data rejected; " + mdrr.getMDReqRejReason());
// set the state of the request to be complete
requestComplete = true;
}
/**
* Separate function to handle the receipt of market data snapshots
*
* Current dealing rates are retrieved through the same class as historical requests. The difference
* is that historical requests are 'answers' to a specific request.
*
* #param mds
*/
public void messageArrived(MarketDataSnapshot mds)
{
// if the market data snapshot is part of the answer to a specific request
try
{
if(mds.getRequestID() != null && mds.getRequestID().equals(currentRequest))
{
// add that snapshot to the historicalRates table
synchronized(historicalRates) { historicalRates.put(mds.getDate(), mds); }
// set the request to be complete only if the continuous flaf is at the end
requestComplete = (mds.getFXCMContinuousFlag() == IFixDefs.FXCMCONTINUOUS_END);
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Display the historical rates captured
*/
public void displayHistory()
{
// give the table a header
output.println("Rate 15 minute candle History for " + TEST_CURRENCY);
// give the table column headings
output.println("Date\t Time\t\tOBid\tCBid\tHBid\tLBid");
// get the keys for the historicalRates table into a sorted list
SortedSet<UTCDate> candle = new TreeSet<UTCDate>(historicalRates.keySet());
// define a format for the dates
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss z");
// make the date formatter above convert from GMT to EST
sdf.setTimeZone(TimeZone.getTimeZone("EST"));
// go through the keys of the historicalRates table
for(int i = 0; i < candle.size(); i++)
{
// create a single instance of the snapshot
MarketDataSnapshot candleData;
synchronized(historicalRates) { candleData = historicalRates.get(candle.toArray()[i]); }
// convert the key to a Date
Date candleDate = ((UTCDate)candle.toArray()[i]).toDate();
// print out the historicalRate table data
output.println(
sdf.format(candleDate) + "\t" + // the date and time formatted and converted to EST
candleData.getBidOpen() + "\t" + // the open bid for the candle
candleData.getBidClose() + "\t" + // the close bid for the candle
candleData.getBidHigh() + "\t" + // the high bid for the candle
candleData.getBidLow()); // the low bid for the candle
}
// repeat the table column headings
output.println("Date\t Time\t\tOBid\tCBid\tHBid\tLBid");
}
public static void main(String[] args)
{
try
{
// create an instance of the JavaFixHistoryMiner
JavaFixHistoryMiner miner = new JavaFixHistoryMiner("rkichenama", "1311016", "Demo");
// login to the api
miner.login();
// retrieve the trader accounts to ensure login process is complete
miner.retrieveAccounts();
// display nore that the history display is delayed
// partially for theatrics, partially to ensure all the rates are collected
output.println("Displaying history in");
// wait ~ 2.5 seconds
for(int i = 5; i > 0; i--)
{
output.println(i + "...");
Thread.sleep(500);
}
// display the collected rates
miner.displayHistory();
// log out of the api
miner.logout();
}
catch (Exception e) { e.printStackTrace(); }
}
}

How to get screenshot of any Linux/Windows application running outside of the JVM

Is it possible to use Java to get a screenshot of an application external to Java, say VLC/Windows Media Player, store it as an Image object and then display it in a JLabel or something of a similar nature? Does anybody know if this is possible and if so does anybody have a general idea as to how to do it?
Note: I just need to find out how to get a screenshot and store it as some form of Image object. After that I can use, manipulate it, display it, etc.
Here is the answer for Windows (not sure if alt+printScr works on linux :P)
I guess one way to achieve this
1. using Robot class to fire alt+printScreen Command (this captures active window to clipboard)
2. read the clipboard!
Here are the two pieces of code that do that. I have not actually tried, but something that I pieced together.
Code to Fire commands to get active window on clipboard
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class ActiveWindowScreenShot
{
/**
* Main method
*
* #param args (not used)
*/
public static void main(String[] args)
{
Robot robot;
try {
robot = new Robot();
} catch (AWTException e) {
throw new IllegalArgumentException("No robot");
}
// Press Alt + PrintScreen
// (Windows shortcut to take a screen shot of the active window)
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_ALT);
System.out.println("Image copied.");
}
}
Code to read image on clipboard
// If an image is on the system clipboard, this method returns it;
// otherwise it returns null.
public static Image getClipboard() {
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
try {
if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
Image text = (Image)t.getTransferData(DataFlavor.imageFlavor);
return text;
}
} catch (UnsupportedFlavorException e) {
} catch (IOException e) {
}
return null;
}
You can manage the control as you need to! Let me know if this works for you. but this is certainly on my todo to try it out!
You can get screen shot of whole screen using class named Robot. Unfortunately you cannot get location and size of windows that belong to other applications using pure java solution. To do this you need other tools (scripting, JNI, JNA). These tools are not cross-platform.

Categories

Resources