calling a java class method in another class - java

Hi I have below Java Class for Sending Fax from Java
package oracle.apps.print;
import com.softlinx.replixfax.*;
import javax.xml.ws.*;
import org.apache.commons.codec.binary.Base64;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.io.File;
public class Fax {
public void SendFax(String Filepath, String faxno) {
try {
ReplixFaxService service = new ReplixFaxService();
ReplixFaxPort port = service.getReplixFaxPort();
((BindingProvider)port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "admin");
// ((BindingProvider) port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"https://api.rpxfax.com/softlinx/replixfax/wsapi");
((BindingProvider)port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
"https://api.rpxtest.com:9999/softlinx/replixfax/wsapi");
Authentication auth = new Authentication();
auth.setLogin("user");
String password = "pwd";
auth.setPassword(org.apache.commons.codec.binary.Base64.encodeBase64String(password.getBytes()));
auth.setRealm("MTBC");
auth.setPasswordSecurity("base64");
SendFaxInput sendFaxInput = new SendFaxInput();
sendFaxInput.setAuthentication(auth);
FaxRecipient recipient = new FaxRecipient();
recipient.setFaxNumber(faxno.toString());
Attachment attachment = new Attachment();
File f = new File(Filepath.toString());
attachment.setFileName(f.getName());
Path path = Paths.get(Filepath.toString());
byte[] data = Files.readAllBytes(path);
attachment.setAttachmentContent(data);
sendFaxInput.getFaxRecipient().add(recipient);
sendFaxInput.getAttachment().add(attachment);
SendFaxOutput result = port.sendFax(sendFaxInput);
System.out.println("Status Code= " + result.getRequestStatus().getStatusCode());
if (result.getFaxInfo() != null) {
System.out.println("Fax ID = " + result.getFaxInfo().get(0).getFaxId());
}
} catch (Exception ex) {
System.out.println("Exception: " + ex.getMessage());
}
}
}
I am compiling this class like this
javac -cp .;./commons-codec-1.10.jar Fax.java
However Compiling of both classes is fine no error at compile time
when i call the method Fax in another class (XXEmail) like this
package oracle.apps.print;
public class XXEmail implements JavaConcurrentProgram {
public static void main(String[] args) {
try {
Fax mtbcfax = new Fax();
mtbcfax.SendFax("E:\\csv_svb\\3010218.pdf", "173224xxxx");
out.writeln("Fax Sent Successfully");
} catch (Exception i) {
log.writeln("Error while Sending Fax " + i.getMessage(), LogFile.STATEMENT);
} finally {
log.writeln("Error while Sending Fax ");
}
}
}
It always goes to Finally block with out showing any error
How can i call this method so it should return with success code or exception

Try to:
Comment all lines in the SendFax function and add only a log:
public void SendFax(String Filepath, String faxno) {
out.writeln("No problem here");
}
Now start the program and see if the function is correctly called or not.
If It is correctly called, so probably the arguments you send are wrong.

Related

Youtube live stream to specific Channel

I am using the below code to create event in Youtube for Live Streaming. Everything works fine, my problem, I want users to live stream to our company's Channel.
At present events are getting created in users channel, this is wrong, we want to create the event in our channel and live stream should come to our company's channel. I would like to know how we should specify our company's channel to create the events.
I tried to specify
YouTube.LiveBroadcasts.Insert liveBroadcastInsert = youtube
.liveBroadcasts().insert(Arrays.asList(lbInsert),
broadcast);
liveBroadcastInsert.onBehalfOfContentOwner("user#company.com");
liveBroadcastInsert.onBehalfOfContentOwnerChannel("ChannelID");
Both did not work. It gave error
"errors": [
{
"domain": "youtube.common",
"message": "The authenticated user cannot act on behalf of the specified Google account.",
"reason": "accountDelegationForbidden"
}
//// Code ///
import com.google.android.gms.common.Scopes;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.util.DateTime;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.YouTube.LiveBroadcasts.Transition;
import com.google.api.services.youtube.YouTubeScopes;
import com.google.api.services.youtube.model.CdnSettings;
import com.google.api.services.youtube.model.ChannelListResponse;
import com.google.api.services.youtube.model.IngestionInfo;
import com.google.api.services.youtube.model.LiveBroadcast;
import com.google.api.services.youtube.model.LiveBroadcastContentDetails;
import com.google.api.services.youtube.model.LiveBroadcastListResponse;
import com.google.api.services.youtube.model.LiveBroadcastSnippet;
import com.google.api.services.youtube.model.LiveBroadcastStatus;
import com.google.api.services.youtube.model.LiveStream;
import com.google.api.services.youtube.model.LiveStreamListResponse;
import com.google.api.services.youtube.model.LiveStreamSnippet;
import com.google.api.services.youtube.model.MonitorStreamInfo;
import com.test.tv.usb.MainActivity;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
public class YouTubeApi {
public static final String RTMP_URL_KEY = "rtmpUrl";
public static final String BROADCAST_ID_KEY = "broadcastId";
private static final int FUTURE_DATE_OFFSET_MILLIS = 5 * 1000;
public static void createLiveEvent(YouTube youtube, String description,
String name) {
// We need a date that's in the proper ISO format and is in the future,
// since the API won't
// create events that start in the past.
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
long futureDateMillis = System.currentTimeMillis()
+ FUTURE_DATE_OFFSET_MILLIS;
Date futureDate = new Date();
futureDate.setTime(futureDateMillis);
String date = dateFormat.format(futureDate);
Log.i(MainActivity.APP_NAME, String.format(
"Creating event: name='%s', description='%s', date='%s'.",
name, description, date));
try {
LiveBroadcastSnippet broadcastSnippet = new LiveBroadcastSnippet();
broadcastSnippet.setTitle(name);
broadcastSnippet.setScheduledStartTime(new DateTime(futureDate));
LiveBroadcastContentDetails contentDetails = new LiveBroadcastContentDetails();
MonitorStreamInfo monitorStream = new MonitorStreamInfo();
monitorStream.setEnableMonitorStream(false);
contentDetails.setMonitorStream(monitorStream);
// Create LiveBroadcastStatus with privacy status.
LiveBroadcastStatus status = new LiveBroadcastStatus();
status.setPrivacyStatus("public");
LiveBroadcast broadcast = new LiveBroadcast();
broadcast.setKind("youtube#liveBroadcast");
broadcast.setSnippet(broadcastSnippet);
broadcast.setStatus(status);
broadcast.setContentDetails(contentDetails);
// Create the insert request
String[] lbInsert = {"snippet", "status","contentDetails"};
YouTube.LiveBroadcasts.Insert liveBroadcastInsert = youtube
.liveBroadcasts().insert(Arrays.asList(lbInsert),
broadcast);
// Request is executed and inserted broadcast is returned
LiveBroadcast returnedBroadcast = liveBroadcastInsert.execute();
// Create a snippet with title.
LiveStreamSnippet streamSnippet = new LiveStreamSnippet();
streamSnippet.setTitle(name);
// Create content distribution network with format and ingestion
// type.
CdnSettings cdn = new CdnSettings();
cdn.setIngestionType("rtmp");
cdn.setResolution("1080p");
cdn.setFrameRate("30fps");
LiveStream stream = new LiveStream();
stream.setKind("youtube#liveStream");
stream.setSnippet(streamSnippet);
stream.setCdn(cdn);
// Create the insert request
String[] lsInsert = {"snippet", "cdn"};
YouTube.LiveStreams.Insert liveStreamInsert = youtube.liveStreams()
.insert(Arrays.asList(lsInsert), stream);
// Request is executed and inserted stream is returned
LiveStream returnedStream = liveStreamInsert.execute();
// Create the bind request
String[] lbBind = {"id", "contentDetails"};
YouTube.LiveBroadcasts.Bind liveBroadcastBind = youtube
.liveBroadcasts().bind(returnedBroadcast.getId(),
Arrays.asList(lbBind));
// Set stream id to bind
liveBroadcastBind.setStreamId(returnedStream.getId());
// Request is executed and bound broadcast is returned
liveBroadcastBind.execute();
} catch (GoogleJsonResponseException e) {
System.err.println("GoogleJsonResponseException code: "
+ e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
e.printStackTrace();
} catch (Throwable t) {
System.err.println("Throwable: " + t.getStackTrace());
t.printStackTrace();
}
}
// TODO: Catch those exceptions and handle them here.
public static List<EventData> getLiveEvents(
YouTube youtube) throws IOException {
Log.i(MainActivity.APP_NAME, "Requesting live events.");
String[] yReq = {"id", "snippet", "contentDetails"};
YouTube.LiveBroadcasts.List liveBroadcastRequest = youtube
.liveBroadcasts().list(Arrays.asList(yReq));
// liveBroadcastRequest.setMine(true);
liveBroadcastRequest.setBroadcastStatus("upcoming");
// List request is executed and list of broadcasts are returned
LiveBroadcastListResponse returnedListResponse = liveBroadcastRequest.execute();
// Get the list of broadcasts associated with the user.
List<LiveBroadcast> returnedList = returnedListResponse.getItems();
List<EventData> resultList = new ArrayList<EventData>(returnedList.size());
EventData event;
for (LiveBroadcast broadcast : returnedList) {
event = new EventData();
event.setEvent(broadcast);
String streamId = broadcast.getContentDetails().getBoundStreamId();
if (streamId != null) {
String[] strID = {streamId};
String ingestionAddress = getIngestionAddress(youtube, strID);
event.setIngestionAddress(ingestionAddress);
}
resultList.add(event);
}
return resultList;
}
public static void startEvent(YouTube youtube, String broadcastId)
throws IOException {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Log.e(MainActivity.APP_NAME, "", e);
}
String[] tReq = {"status"};
Transition transitionRequest = youtube.liveBroadcasts().transition(
"live", broadcastId, Arrays.asList(tReq));
transitionRequest.execute();
}
public static void endEvent(YouTube youtube, String broadcastId)
throws IOException {
String[] tReq = {"status"};
Transition transitionRequest = youtube.liveBroadcasts().transition(
"complete", broadcastId, Arrays.asList(tReq));
transitionRequest.execute();
}
public static String getIngestionAddress(YouTube youtube, String[] streamId)
throws IOException {
String[] tReq = {"cdn"};
YouTube.LiveStreams.List liveStreamRequest = youtube.liveStreams()
.list(Arrays.asList(tReq));
liveStreamRequest.setId(Arrays.asList(streamId));
LiveStreamListResponse returnedStream = liveStreamRequest.execute();
List<LiveStream> streamList = returnedStream.getItems();
if (streamList.isEmpty()) {
return "";
}
IngestionInfo ingestionInfo = streamList.get(0).getCdn().getIngestionInfo();
return ingestionInfo.getIngestionAddress() + "/"
+ ingestionInfo.getStreamName();
}
}

Is there a standard way to transform a String into a File considerning the possibility of a URL/URI formatted input String

I would like to obtain the most accurate File typed representation of a String that is supposed to refer to a local (existing) file in one of several forms like:
String file0 = "/home/my_user/file.txt"
String file1 = "file:///home/my_user/file.txt"
String file2 = "file.txt"; // assuming that the working dir is /home/my_user.
Is there a (quasy) single liner using the standard library or perhaps a common third party like apache-commons that would do the trick?
Thanks.
You can define your own function for this purpose. Given below is the function definition and test code:
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
public class Main {
public static void main(String[] args) {
String file0 = "/Users/arvind.avinash/file.txt";
String file1 = "file:///Users/arvind.avinash/file.txt";
String file2 = "file.txt"; // assuming that the working dir is /Users/arvind.avinash.
System.out.println(getFile(file0).exists());
System.out.println(getFile(file1).exists());
System.out.println(getFile(file2).exists());
}
static File getFile(String pathOrUri) {
URI uri;
File file = null;
try {
uri = new URL(pathOrUri).toURI();
} catch (MalformedURLException e) {
return new File(pathOrUri);
} catch (URISyntaxException e) {
return new File(pathOrUri);
}
if (uri != null) {
file = new File(uri);
}
return file;
}
}
Output:
true
true
true
[Update]
Given below is a more simplified version:
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
public class Main {
public static void main(String[] args) {
String file0 = "/Users/arvind.avinash/file.txt";
String file1 = "file:///Users/arvind.avinash/file.txt";
String file2 = "file.txt"; // assuming that the working dir is /Users/arvind.avinash.
System.out.println(getFile(file0).exists());
System.out.println(getFile(file1).exists());
System.out.println(getFile(file2).exists());
}
static File getFile(String pathOrUri) {
URI uri;
try {
uri = new URL(pathOrUri).toURI();
} catch (MalformedURLException | URISyntaxException e) {
return new File(pathOrUri);
}
return new File(uri);
}
}
You be able to call new File(x) on examples 1 and 3 and it should work.
As for #2, you can create a URI, and then create File from that. In fact I think they all probably will work using URI
String fileStr = "file:///home/my_user/file.txt";
try {
URI uri = new URI(fileStr);
File f = new File(uri);
} catch (URISyntaxException ex) { ...}

My module is stopping my Wowza application from loading because of required dependencies

Local - Wowza Streaming Engine 4.1.0, Windows 8, Java version 1.7.0_67
Server - The Wowza Streaming Engine AMI here. Java version 1.7.0_65
I have Wowza running locally and on an EC2 instance.
Locally it works fine and I can connect and publish streams to my application without a problem. I cannot connect or publish streams to the application on my server, however.
I removed the .jar (module) that went with the application, and I was able to connect and publish to my app, though it gave me a warning that it couldn't find the associated module, which was to be expected.
I put the module back in, restarted the server, and I was unable to connect.
It appears that my .jar file is stopping the application from loading for some reason.
Here's the source for my module:
package com.xxxxxxxxxxxxxxx.recorder;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.S3ClientOptions;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.wowza.wms.application.*;
import com.wowza.wms.amf.*;
import com.wowza.wms.client.*;
import com.wowza.wms.module.*;
import com.wowza.wms.request.*;
import com.wowza.wms.stream.*;
import com.wowza.wms.rtp.model.*;
import com.wowza.wms.httpstreamer.model.*;
import com.wowza.wms.httpstreamer.cupertinostreaming.httpstreamer.*;
import com.wowza.wms.httpstreamer.smoothstreaming.httpstreamer.*;
public class RecorderModules extends ModuleBase implements AWSCredentialsProvider {
IApplicationInstance appInstance;
private String videoBucket;
private String thumbBucket;
private String videoDistro;
private String thumbnailDistro;
private String region;
private AmazonS3Client s3;
private String dir;
public void onAppStart(IApplicationInstance appInstance) {
String fullname = appInstance.getApplication().getName() + "/"
+ appInstance.getName();
getLogger().info("onAppStart: " + fullname);
this.appInstance = appInstance;
try{
videoBucket = appInstance.getProperties().getPropertyStr("videoBucket");
getLogger().info("Video bucket is " + videoBucket);
thumbBucket = appInstance.getProperties().getPropertyStr("thumbBucket");
getLogger().info("Thumb bucket is " + thumbBucket);
videoDistro = appInstance.getProperties().getPropertyStr("videoDistro");
getLogger().info("Video distro is " + videoDistro);
thumbnailDistro =appInstance.getProperties().getPropertyStr("thumbnailDistro");
getLogger().info("thumbnail distro is " + thumbnailDistro);
region = appInstance.getProperties().getPropertyStr("region");
getLogger().info("region is " + region);
s3 = new AmazonS3Client();
s3.setEndpoint(region);
getLogger().info("AmazonS3Client is created");
}catch(Exception e){
getLogger().info("Could not read config " + e);
}
}
public void doSave(IClient client, RequestFunction function, AMFDataList params) {
getLogger().info("doSave hit ");
new File(dir + params.getString(3) + ".flv").renameTo(new File(dir+params.getString(4)+".flv"));
getLogger().info("Starting upload");
String thumbName = params.getString(4).replace("vid_", "thumb_")+".jpg";
String flvName = params.getString(4)+".flv";
String mp4Name = params.getString(4)+".mp4";
try{
PutObjectRequest p = new PutObjectRequest(videoBucket,flvName, new File(dir+flvName));
p.setRequestCredentials(getCredentials());
p.setCannedAcl(CannedAccessControlList.BucketOwnerFullControl);
getLogger().info("attempting to upload " + flvName + " to " + videoBucket);
s3.putObject(p);
getLogger().info("flv upload complete " + videoBucket + " " + flvName);
PutObjectRequest p2 = new PutObjectRequest(thumbBucket,thumbName, new File(dir+thumbName));
p2.setRequestCredentials(getCredentials());
p2.setCannedAcl(CannedAccessControlList.PublicRead);
getLogger().info("attempting to upload " + thumbName + " to " + thumbBucket);
s3.putObject(p2);
getLogger().info("thumb upload complete " + thumbBucket + " " + thumbName);
String[] info = new String[5];
info[0] = videoDistro+params.getString(4);
info[1] = thumbnailDistro+thumbName;
info[2] = params.getString(4);
info[3] = videoBucket;
info[4] = thumbBucket;
getLogger().info("sending info to client " + info[0]);
//client.call("uploadDone", null,(Object[])info);
}catch(Exception e){
getLogger().info("Upload failed");
getLogger().info(e);
//client.call("uploadFailed")
}
//transcode
//-crf 23 -refs 3 -profile:v baseline -level 3.0 -pix_fmt yuv420p -preset veryslow
String[] command = {"ffmpeg",
"-i", dir+params.getString(4)+".flv",
"-crf", "23",
"-refs","3",
"-profile:v","baseline",
"-level","3.0",
"-pix_fmt","yuv420p",
"-preset","veryslow",
dir+params.getString(4)+".mp4"};
try {
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
getLogger().info("Starting process");
Process process = builder.start();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while((line = in.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
PutObjectRequest p = new PutObjectRequest(videoBucket,mp4Name, new File(dir+mp4Name));
p.setRequestCredentials(getCredentials());
p.setCannedAcl(CannedAccessControlList.BucketOwnerFullControl);
getLogger().info("transcoding completed");
s3.putObject(p);
getLogger().info("mp4 file uploaded");
} catch (Exception e) {
getLogger().info("Error running ffmpeg");
e.printStackTrace();
}
deleteFiles(params.getString(4).replace("vid_",""));
}
public void saveThumbnail(IClient client, RequestFunction function, AMFDataList params){
String dir = client.getAppInstance().getStreamStoragePath()+"/"+"thumb_"+params.getString(4).split(",")[2]+".jpg";
getLogger().info(params);
Path path = Paths.get(dir);
byte[] byteArr = (byte[])((AMFDataByteArray)params.get(3)).getValue();
try {
Files.write(path, byteArr, StandardOpenOption.CREATE_NEW);
} catch (IOException e) {
e.printStackTrace();
}
}
public void onAppStop(IApplicationInstance appInstance) {
String fullname = appInstance.getApplication().getName() + "/"
+ appInstance.getName();
getLogger().info("onAppStop: " + fullname);
}
public void onConnect(IClient client, RequestFunction function, AMFDataList params) {
getLogger().info("onConnect: " + client.getClientId());
}
public void onConnectAccept(IClient client) {
getLogger().info("onConnectAccept: " + client.getClientId());
}
public void onConnectReject(IClient client) {
getLogger().info("onConnectReject: " + client.getClientId());
}
public void onDisconnect(IClient client) {
getLogger().info("onDisconnect: " + client.getClientId());
}
public void onStreamCreate(IMediaStream stream) {
getLogger().info("onStreamCreate: " + stream.getSrc());
}
public void onStreamDestroy(IMediaStream stream) {
getLogger().info("onStreamDestroy: " + stream.getSrc());
}
public void onHTTPSessionCreate(IHTTPStreamerSession httpSession) {
getLogger().info("onHTTPSessionCreate: " + httpSession.getSessionId());
}
public void onHTTPSessionDestroy(IHTTPStreamerSession httpSession) {
getLogger().info("onHTTPSessionDestroy: " + httpSession.getSessionId());
}
public void onHTTPCupertinoStreamingSessionCreate(HTTPStreamerSessionCupertino httpSession) {
getLogger().info(
"onHTTPCupertinoStreamingSessionCreate: "
+ httpSession.getSessionId());
}
public void onHTTPCupertinoStreamingSessionDestroy(HTTPStreamerSessionCupertino httpSession) {
getLogger().info(
"onHTTPCupertinoStreamingSessionDestroy: "
+ httpSession.getSessionId());
}
public void onHTTPSmoothStreamingSessionCreate( HTTPStreamerSessionSmoothStreamer httpSession) {
getLogger().info(
"onHTTPSmoothStreamingSessionCreate: "
+ httpSession.getSessionId());
}
public void onHTTPSmoothStreamingSessionDestroy( HTTPStreamerSessionSmoothStreamer httpSession) {
getLogger().info(
"onHTTPSmoothStreamingSessionDestroy: "
+ httpSession.getSessionId());
}
public void onRTPSessionCreate(RTPSession rtpSession) {
getLogger().info("onRTPSessionCreate: " + rtpSession.getSessionId());
}
public void onRTPSessionDestroy(RTPSession rtpSession) {
getLogger().info("onRTPSessionDestroy: " + rtpSession.getSessionId());
}
public void onCall(String handlerName, IClient client, RequestFunction function, AMFDataList params) {
getLogger().info("onCall: " + handlerName);
}
/* Overwritten method: Delete content of the same name before starting */
public void publish(IClient client, RequestFunction function, AMFDataList params) {
getLogger().info("publish hit");
String name = params.getString(3).replace("flv:","").replace("vid_","").replace("_temp", "");
getLogger().info("name:" + name);
dir = appInstance.decodeStorageDir("${com.wowza.wms.AppHome}"+"/content/recorder/");
deleteFiles(name);
invokePrevious(client,function,params);
}
private void deleteFiles(String name){
getLogger().info("deleting " + name);
try {
if(Files.exists(Paths.get(dir+"thumb_"+name+".jpg"))){
getLogger().info("deleting thumbnail");
Files.delete(Paths.get(dir+"thumb_"+name+".jpg"));
}
if(Files.exists((Paths.get(dir+"vid_"+name+".flv")))){
getLogger().info("deleting video");
Files.delete(Paths.get(dir+"vid_"+name+".flv"));
}
if(Files.exists((Paths.get(dir+"vid_"+name+".mp4")))){
getLogger().info("deleting mp4 video");
Files.delete(Paths.get(dir+"vid_"+name+".mp4"));
}
if(Files.exists((Paths.get(dir+"vid_"+name+"_temp.flv")))){
getLogger().info("deleting temp video");
Files.delete(Paths.get(dir+"vid_"+name+"_temp.flv"));
}
} catch (IOException e) {
getLogger().info("Could not delete old files");
}
}
#Override
public AWSCredentials getCredentials() {
getLogger().info("getting credentials");
return new BasicAWSCredentials(appInstance.getProperties().getPropertyStr("accessKey"),appInstance.getProperties().getPropertyStr("secretKey"));
}
#Override
public void refresh() {
// TODO Auto-generated method stub
}
}
It could be related to this:
http://www.wowza.com/forums/showthread.php?36693-Aws-plugin-breaks-application-with-no-errors
That might mean that my .jar file isn't being built with the required dependencies (the AWS stuff).
EDIT:
So I included all the dependencies, making sure that the AWS stuff was in the .jar (I looked at it with winrar), and now it gives me "Module class not found or could not be loaded" when the application starts. I can see that the application is there.
This might be related with this error I get in Eclipse when I tried to create a runnable jar with all the dependencies extracted: "Could not find main method from given launch configuration." Even though I got this error, it appeared to work, as the .jar file grew several times in size.
Make sure the applications folder actually exists; in your wowza-install-folder there must be a subfolder called "applications". If it's not there, create it manually.
In Wowza 4.x, you must use the Engine Manager to create applications and manage them. Open the Engine Manager (http://your.ec2.server:8088) and choose the specific application; then select "Incoming security" and check what it says under "RTMP Publishing". If you don't want any protection, change it to "Open (no authentication required)"; otherwise you must send along credentials from your AS3 code when connecting with the NetConnection.
You may also want to check the Wowza logs in [wowza-install-folder]/logs - if the connection fails, there should be a message in the log about this that may give you useful information.
PS: I usually use the Pre-Built AMIs from Wowza's website to initiate a new instance.
I resolved it by installing everything differently on a new server.
I took by auto-generated .jar file, and the two jar files that it depended on, commons-codec-1.9 and aws-java-sdk-1.4.7, and installed them using the "startup package" method, as opposed to transferring the dependencies later over ftp.
And everything worked fine.

Getting IllegalAccessError

When i am using this code it gives error:
2011-08-10 13:18:13.368::WARN: EXCEPTION
java.lang.IllegalAccessError: tried to access method org.mortbay.util.Utf8StringBuffer.(I)V from class org.mortbay.jetty.HttpURI
Code:
package com.google.api.client.sample.docs.v3;
import com.google.api.client.auth.oauth.OAuthCredentialsResponse;
import com.google.api.client.auth.oauth.OAuthHmacSigner;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthAuthorizeTemporaryTokenUrl;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetAccessToken;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetTemporaryToken;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.sample.docs.v3.model.DocsUrl;
import java.awt.Desktop;
import java.awt.Desktop.Action;
import java.net.URI;
public class Auth {
private static final String APP_NAME ="Google Documents List Data API Java Client Sample";
private static OAuthHmacSigner signer;
private static OAuthCredentialsResponse credentials;
static void authorize(HttpTransport transport) throws Exception {
// callback server
LoginCallbackServer callbackServer = null;
String verifier = null;
String tempToken = null;
try {
callbackServer = new LoginCallbackServer();
callbackServer.start();
// temporary token
GoogleOAuthGetTemporaryToken temporaryToken =new GoogleOAuthGetTemporaryToken();
signer = new OAuthHmacSigner();
signer.clientSharedSecret = "anonymous";
temporaryToken.signer = signer;
temporaryToken.consumerKey = "in.gappsdemo.in";
//temporaryToken.scope ="https://apps-apis.google.com/a/feeds/user/";
temporaryToken.scope = DocsUrl.ROOT_URL;
temporaryToken.displayName = APP_NAME;
temporaryToken.callback = callbackServer.getCallbackUrl();
System.out.println("temporaryToken.callback: "+temporaryToken.callback);
OAuthCredentialsResponse tempCredentials = temporaryToken.execute();
signer.tokenSharedSecret = tempCredentials.tokenSecret;
System.out.println("signer.tokenSharedSecret: " + signer.tokenSharedSecret);
// authorization URL
GoogleOAuthAuthorizeTemporaryTokenUrl authorizeUrl =new GoogleOAuthAuthorizeTemporaryTokenUrl();
authorizeUrl.temporaryToken = tempToken = tempCredentials.token;
String authorizationUrl = authorizeUrl.build();
System.out.println("Go to this authorizationUrl: " + authorizationUrl);
// launch in browser
boolean browsed = false;
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Action.BROWSE)) {
System.out.println("In if browsed condition:");
desktop.browse(URI.create(authorizationUrl));
browsed = true;
}
}
if (!browsed) {
String browser = "google-chrome";
Runtime.getRuntime().exec(new String[] {browser, authorizationUrl});
System.out.println("In if !browsed condition1:");
}
System.out.println("tempToken: "+tempToken);
verifier = callbackServer.waitForVerifier(tempToken);
System.out.println("GoogleOAuthGetAccessToken: ");
} finally {
System.out.println("server Stop:");
if (callbackServer != null) {
System.out.println("server Stop:");
callbackServer.stop();
}
}
System.out.println("GoogleOAuthGetAccessToken: ");
GoogleOAuthGetAccessToken accessToken = new GoogleOAuthGetAccessToken();
accessToken.temporaryToken = tempToken;
accessToken.signer = signer;
accessToken.consumerKey = "in.gappsdemo.in";
accessToken.verifier = verifier;
credentials = accessToken.execute();
signer.tokenSharedSecret = credentials.tokenSecret;
System.out.println("signer.tokenSharedSecret: ");
createOAuthParameters().signRequestsUsingAuthorizationHeader(transport);
}
static void revoke() {
if (credentials != null) {
try {
GoogleOAuthGetAccessToken.revokeAccessToken(createOAuthParameters());
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
private static OAuthParameters createOAuthParameters() {
OAuthParameters authorizer = new OAuthParameters();
authorizer.consumerKey = "in.gappsdemo.in";
authorizer.signer = signer;
authorizer.token = credentials.token;
return authorizer;
}
}
Here are two potentially related, posts. Notice you're getting an Error, not an Exception, so that is interesting. You might try running your JVM with -verbose to see where each class is getting loaded from, to see if maybe you're compiling with one class/jar, but accidentally running with another.
Also notice from the error that the packages are slightly different "org.mortbay.util" vs. "org.mortbay.jetty", so the UTF8StringBuffer constructor would need to be more visible. But again, normally a compiler would catch that.
I realize this isn't a full answer, to be sure, but at least a couple places to start looking.

How to read MP3 file tags

I want to have a program that reads metadata from an MP3 file. My program should also able to edit these metadata. What can I do?
I got to search out for some open source code. But they have code; but not simplified idea for my job they are going to do.
When I read further I found the metadata is stored in the MP3 file itself. But I am yet not able to make a full idea of my baby program.
Any help will be appreciated; with a program or very idea (like an algorithm). :)
The last 128 bytes of a mp3 file contains meta data about the mp3 file., You can write a program to read the last 128 bytes...
UPDATE:
ID3v1 Implementation
The Information is stored in the last 128 bytes of an MP3. The Tag
has got the following fields, and the offsets given here, are from
0-127.
Field Length Offsets
Tag 3 0-2
Songname 30 3-32
Artist 30 33-62
Album 30 63-92
Year 4 93-96
Comment 30 97-126
Genre 1 127
WARINING- This is just an ugly way of getting metadata and it might not actually be there because the world has moved to id3v2. id3v1 is actually obsolete. Id3v2 is more complex than this, so ideally you should use existing libraries to read id3v2 data from mp3s . Just putting this out there.
You can use apache tika Java API for meta-data parsing from MP3 such as title, album, genre, duraion, composer, artist and etc.. required jars are tika-parsers-1.4, tika-core-1.4.
Sample Program:
package com.parse.mp3;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.mp3.Mp3Parser;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class AudioParser {
/**
* #param args
*/
public static void main(String[] args) {
String fileLocation = "G:/asas/album/song.mp3";
try {
InputStream input = new FileInputStream(new File(fileLocation));
ContentHandler handler = new DefaultHandler();
Metadata metadata = new Metadata();
Parser parser = new Mp3Parser();
ParseContext parseCtx = new ParseContext();
parser.parse(input, handler, metadata, parseCtx);
input.close();
// List all metadata
String[] metadataNames = metadata.names();
for(String name : metadataNames){
System.out.println(name + ": " + metadata.get(name));
}
// Retrieve the necessary info from metadata
// Names - title, xmpDM:artist etc. - mentioned below may differ based
System.out.println("----------------------------------------------");
System.out.println("Title: " + metadata.get("title"));
System.out.println("Artists: " + metadata.get("xmpDM:artist"));
System.out.println("Composer : "+metadata.get("xmpDM:composer"));
System.out.println("Genre : "+metadata.get("xmpDM:genre"));
System.out.println("Album : "+metadata.get("xmpDM:album"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
}
}
}
For J2ME(which is what I was struggling with), here's the code that worked for me..
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.*;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.MetaDataControl;
import javax.microedition.midlet.MIDlet;
public class MetaDataControlMIDlet extends MIDlet implements CommandListener {
private Display display = null;
private List list = new List("Message", List.IMPLICIT);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Alert alert = new Alert("Message");
private Player player = null;
public MetaDataControlMIDlet() {
display = Display.getDisplay(this);
alert.addCommand(exitCommand);
alert.setCommandListener(this);
list.addCommand(exitCommand);
list.setCommandListener(this);
//display.setCurrent(list);
}
public void startApp() {
try {
FileConnection connection = (FileConnection) Connector.open("file:///e:/breathe.mp3");
InputStream is = null;
is = connection.openInputStream();
player = Manager.createPlayer(is, "audio/mp3");
player.prefetch();
player.realize();
} catch (Exception e) {
alert.setString(e.getMessage());
display.setCurrent(alert);
e.printStackTrace();
}
if (player != null) {
MetaDataControl mControl = (MetaDataControl) player.getControl("javax.microedition.media.control.MetaDataControl");
if (mControl == null) {
alert.setString("No Meta Information");
display.setCurrent(alert);
} else {
String[] keys = mControl.getKeys();
for (int i = 0; i < keys.length; i++) {
list.append(keys[i] + " -- " + mControl.getKeyValue(keys[i]), null);
}
display.setCurrent(list);
}
}
}
public void commandAction(Command cmd, Displayable disp) {
if (cmd == exitCommand) {
notifyDestroyed();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}

Categories