I'm wondering how to do this. I looked at the sdk documentation and have some examples, but am confused how the syntax generally goes.
If I want to delete a file, I assume I use deleteObject(path, key). However, what is the "key"?
Also how do you delete a directory? I can't seem to find a method for doing that.
This snippet of code works for me. folderPath is something like "topDir/secondDir/"
void deleteObjectsInFolder(String bucketName, String folderPath) {
for (S3ObjectSummary file : s3.listObjects(bucketName, folderPath).getObjectSummaries()){
s3.deleteObject(bucketName, file.getKey());
}
}
A "key" in S3 is similar to a file path:
http://bucket.s3.amazonaws.com/some/path/to/use
... is in a bucket named bucket and has a key of some/path/to/use.
It's not actually a path though, because there are no folders. The S3 key is just the file name for a file in one big directory (the entire bucket). S3 keys can contain /, but it has no special meaning unless you set the delimiter argument with listing a bucket.
In other words, having an object named some/object doesn't tell you anything about the object some (it might or might not exist -- the two objects are not related).
However, you can request keys with a specific prefix, so I could say "give me all keys starting with some/path/to/ and it will return some/path/to/use. It looks like "listing a directory", but it's really just asking for files that start with a specific string of characters.
I could just as easily name things like this:
somepathtousea
somepathtouseb
And say "give me everything starting with somepathtouse" (and it would say somepathtousea and somepathtouseb).
Note: S3 URL's come in several forms:
http://s3.amazonaws.com/bucket/key
http://bucket.s3.amazonaws.com/key
http://bucket/key (where bucket is a DNS CNAME record pointing to bucket.s3.amazonaws.com)
EDIT:
I looked at the JavaDocs and this is the function signature I see (for AmazonS3Client):
public void deleteObject(java.lang.String bucketName,
java.lang.String key)
throws AmazonClientException,
AmazonServiceException
EDIT again:
Folders do kind-of exist now, as zero-length objects with a content-type of application/x-directory and a key ending in /:
$ AWS_PROFILE=prod aws s3api head-object --bucket example-bucket --key example-directory/
{
"AcceptRanges": "bytes",
"LastModified": "Mon, 29 Apr 2019 14:59:36 GMT",
"ContentLength": 0,
"ETag": "\"d41d8cd98f00b204e9800998ecf8427e\"",
"ContentType": "application/x-directory",
"ServerSideEncryption": "AES256",
"Metadata": {}
}
This is still just convention and there's nothing stopping you from having files ending / or files inside of "folders" that don't exist.
You might want to take a look at this example for a quick reference on how you can delete objects from S3.
The syntax for delete is actually
deleteObject( bucketName, key )
where bucketName is the bucket in which you have placed your files and key is name of the file you want to delete within the bucket.
Think of a bucket as your hard disk drive like C:\ , D:\ etc. And key as the absolute pathname of a file you want to delete.
/*Here is solution that works for me. Here Bucket_Name is my bucket name on S3, and key is the path under Bucket_Name. So, if absolute path on S3 is:
s3://my_bucket/Path/to/my/folder
then, the code below should work. */
String Bucket_Name = "my_bucket";
String key = "Path/to/my/folder";
ObjectListing objects = s3Client.listObjects(BUCKET_NAME, key);
for (S3ObjectSummary objectSummary : objects.getObjectSummaries())
{
s3Client.deleteObject(BUCKET_NAME, objectSummary.getKey());
}
As question is asking about Deleting files, directories and buckets in amazon S3 java, I would like to offer code for deleting a non-empty S3 bucket (AWS Reference):
public void deleteBucket(final String bucketName) {
final AmazonS3 s3 = AmazonS3ClientBuilder.defaultClient();
try {
ObjectListing objectListing = s3.listObjects(bucketName);
while (true) {
for (Iterator<?> iterator = objectListing.getObjectSummaries().iterator(); iterator.hasNext(); ) {
S3ObjectSummary summary = (S3ObjectSummary) iterator.next();
s3.deleteObject(bucketName, summary.getKey());
}
if (objectListing.isTruncated()) {
objectListing = s3.listNextBatchOfObjects(objectListing);
} else {
break;
}
}
VersionListing versionListing = s3.listVersions(new ListVersionsRequest().withBucketName(bucketName));
while (true) {
for (Iterator<?> iterator = versionListing.getVersionSummaries().iterator(); iterator.hasNext(); ) {
S3VersionSummary vs = (S3VersionSummary) iterator.next();
s3.deleteVersion(bucketName, vs.getKey(), vs.getVersionId());
}
if (versionListing.isTruncated()) {
versionListing = s3.listNextBatchOfVersions(versionListing);
} else {
break;
}
}
s3.deleteBucket(bucketName);
} catch (AmazonServiceException e) {
System.err.println(e.getErrorMessage());
}
}
Works for me, beware of truncation!
long start = System.currentTimeMillis();
long totalSize = 0;
int totalItems = 0;
String key ="path/to/folder/"
String bucket = "my-bucket"
final ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucketName).withPrefix(key);
ObjectListing objects = s3.listObjects(listObjectsRequest);
do {
for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
totalSize += objectSummary.getSize();
totalItems++;
s3.deleteObject(bucketName, objectSummary.getKey());
}
objects = s3.listNextBatchOfObjects(objects);
} while (objects.isTruncated());
long stop = System.currentTimeMillis();
LOG.trace("User {} had {} items with {} Kb, took {} ms to delete", user.getName(), totalItems, totalSize / 1024, stop
- start);
The ListObjectsV2Result worked for me. Try once.
private void deleteObjectsInFolder() {
try {
ListObjectsV2Result result;
do {
String folderPath = " ";
result = s3.listObjectsV2(Constants.BUCKET_NAME, folderPath);
Log.e("count:", result.getKeyCount() + "");
if (result.getKeyCount() != 0) {
for (S3ObjectSummary objectSummary :
result.getObjectSummaries()) {
s3.deleteObject(Constants.BUCKET_NAME, objectSummary.getKey());
}
}
System.out.println("Next Continuation Token : " + result.getNextContinuationToken());
} while (result.isTruncated() == true);
} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, " +
"which means your request made it " +
"to Amazon S3, but was rejected with an error response " +
"for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, " +
"which means the client encountered " +
"an internal error while trying to communicate" +
" with S3, " +
"such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
}
Deleting a list of objects from S3 bucket by bulks:
public void deleteObjects(String bucketName, List<String> keys) {
List<KeyVersion> bulk = new ArrayList<>();
for (int i = 0; i < keys.size(); i++) {
bulk.add(new KeyVersion(keys.get(i)));
if (i % 100 == 0) {
try {
s3Client.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(bulk));
} catch (Exception e) {
System.err.println(e.getErrorMessage());
}
bulk.clear();
}
}
if (bulk.size() > 0) {
try {
s3Client.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(bulk));
} catch (Exception e) {
System.err.println(e.getErrorMessage());
}
}
}
Source: http://codeflex.co/delete-objects-from-amazon-s3-bucket-using-aws-sdk-for-java/
This line of code works in my case where the keyName is the file name:
s3Client.deleteObject(new DeleteObjectRequest(bucketName, keyName));
kotlin
class S3(
var bucketName: String? = null,
var key: String? = null,
val accessKey: String? = null,
val secretKey: String? = null,
val region: String? = null
)
fun delete(
s3: S3,
keyword: String = "",
) {
with(s3) {
val client = client(accessKey, secretKey, region)
var objects = client.listObjects(bucketName, key)
while (true) {
for (i in objects.objectSummaries) {
if (!i.key.contains(keyword)) {
continue
}
client.deleteObject(bucketName, i.key)
}
if (objects.isTruncated) {
objects = client.listNextBatchOfObjects(objects)
} else {
break
}
}
var versions = client.listVersions(bucketName, key)
while (true) {
for (i in versions.versionSummaries) {
if (!i.key.contains(keyword)) {
continue
}
client.deleteVersion(bucketName, i.key, i.versionId)
}
if (versions.isTruncated) {
versions = client.listNextBatchOfVersions(versions)
} else {
break
}
}
}
}
Related
I am facing an issue when i try to query the queue using createquery api to fetch the queue element.
I am getting an error at the while statement stating the error below as
errorjava.lang.illegalstateexception :unread block data
i dont know why i am getting this error. I can able to use the fetchcount() api to get the count of workitem in the queue but the hasnext() api is not working nor next().
Is there any reason why this statement is not getting executed. is this related to any java issue. Can any one help
The code is
VWSession session = new VWSession();
session.setBootstrapCEURI(Ceuri);
session.logon(cename, fnPassword, connectionPoint);
VWQueue queue = session.getQueue(queue));
int queryFlag = VWQueue.QUERY_NO_OPTIONS;
int fetchType = VWFetchType.FETCH_TYPE_STEP_ELEMENT;
VWQueueQuery queueQuery = queue.createQuery(null,null, null,queryFlag, null, null, fetchType);
while (queueQuery.hasNext()) {
queueElement = (VWStepElement) queueQuery.next();
}
In you main (calling) method, do this :
VWSession vwsession = new VWSession();
vwsession.setBootstrapCEURI("http://servername:9080/wsi/FNCEWS40MTOM/");
vwsession.logon("userid", "password", "ConnPTName");
IteratePEWorkItems queueTest = new IteratePEWorkItems();
queueTest.testQueueElements(vwsession);
Later on create below metioned helper method:
public void testQueueElements(VWSession vwsession) {
System.out.println("Inside getListOfWorkitems: : ");
VWRoster roster = vwsession.getRoster("DefaultRoster");
int fetchType = VWFetchType.FETCH_TYPE_STEP_ELEMENT;
int queryFlags = VWQueue.QUERY_READ_UNWRITABLE;
try {
dispatchWorkItems(roster, fetchType, queryFlags, vwsession);
} catch (Exception exception) {
log.error(exception.getMessage());
}
}
public void dispatchWorkItems(VWRoster roster, int fetchType, int queryFlags, VWSession vwsession) {
String filter = "SLA_Date>=:A";
// get value and replace with 1234567890 as shown in process administrator
Object[] subVars = { 1234567890 };
VWRosterQuery rosterQuery = roster.createQuery(null, null, null,
VWRoster.QUERY_MIN_VALUES_INCLUSIVE | VWRoster.QUERY_MAX_VALUES_INCLUSIVE, filter, subVars,
VWFetchType.FETCH_TYPE_WORKOBJECT);
int i = 0;
// Iterate work items here...
while (rosterQuery.hasNext() == true) {
VWWorkObject workObject = (VWWorkObject) rosterQuery.next();
try {
i++;
System.out.println(" Subject: " + workObject.getFieldValue("F_Subject") + " Count: " + i);
} catch (Exception exception) {
exception.printStackTrace();
log.error(exception);
}
}
}
Try it and share the output.
I want to discover all the destinations from solace (queues and topics)
I tried using MBeanServerConnection and query after names (but I didn't find a proper way to use this) or JNDI lookups Destination dest = (Destination) context.lookup(Dest_name), but I don't have the names of the queues/topics.
I am using solace - jms library.
I am searching for smth like this: (but for solace, not activeMq)
get all Queue from activeMQ
You will need to make use of SEMP over the management interface for this.
Sample commands:
curl -d '<rpc><show><queue><name>*</name></queue></show></rpc>' -u semp_username:semp_password http://your_management_ip:your_management_port/SEMP
curl -d '<rpc><show><topic-endpoint><name>*</name></topic-endpoint></show></rpc>' -u semp_username:semp_password http://your_management_ip:your_management_port/SEMP
Note that I'm using curl for simplicity, but any application can perform HTTP POSTs to execute these commands.
If you are using Java, you can refer to the SempHttpSetRequest sample found within the Solace API samples.
Documentation on SEMP can be found here.
However, the larger question here is why do you need to discover all destinations?
One of the features of the message broker is to decouple the publishers and consumers.
If you need to know if your persistent message is being published to a topic with no consumers, you can make use of the reject-msg-to-sender-on-no-subscription-match setting in the publishing application's client-profile.
This means that the publisher will obtain a negative acknowledgement in the event that it tries to publish a message on a topic that has no matching subscribers.
You can refer to "Handling Guaranteed Messages with No Matches" at https://docs.solace.com/Configuring-and-Managing/Configuring-Client-Profiles.htm for further details.
Here is some source code that might help. With the appliance configured correctly, SEMP is also available over JMS on topic "#SEMP/(router)/SHOW".
/**
* Return the SolTopicInfo for this topic (or all topics if 'topic' is null).
*
* #param session
* #param endpointName
* #return
*/
public static SolTopicInfo[] getTopicInfo(JCSMPSession session, String endpointName, String vpn,
String sempVersion) {
XMLMessageConsumer cons = null;
XMLMessageProducer prod = null;
Map<String, SolTopicInfo> tiMap = new HashMap<String, SolTopicInfo>();
try {
// Create a producer and a consumer, and connect to appliance.
prod = session.getMessageProducer(new PubCallback());
cons = session.getMessageConsumer(new SubCallback());
cons.start();
if (vpn == null) vpn = (String) session.getProperty(JCSMPProperties.VPN_NAME);
if (sempVersion == null) sempVersion = getSempVersion(session);
// Extract the router name.
final String SEMP_SHOW_TE_TOPICS = "<rpc semp-version=\""
+ sempVersion
+ "\"><show><topic-endpoint><name>"
+ endpointName
+ "</name><vpn-name>"+ vpn + "</vpn-name></topic-endpoint></show></rpc>";
RpcReply teTopics = sendRequest(session, SEMP_SHOW_TE_TOPICS);
for (TopicEndpoint2 te : teTopics.getRpc().getShow().getTopicEndpoint().getTopicEndpoints()
.getTopicEndpointArray()) {
SolTopicInfo ti = new SolTopicInfo();
ti.setBindCount(te.getInfo().getBindCount());
//qi.setDescription(qt.getInfo().getNetworkTopic());
ti.setEndpoint(te.getName());
ti.setMessageVPN(te.getInfo().getMessageVpn());
ti.setTopic(te.getInfo().getDestination());
ti.setDurable(te.getInfo().getDurable());
ti.setInSelPres(te.getInfo().getIngressSelectorPresent());
ti.setHwmMB(formatter.format(te.getInfo().getHighWaterMarkInMb()));
ti.setSpoolUsageMB(formatter.format(te.getInfo().getCurrentSpoolUsageInMb()));
ti.setMessagesSpooled(te.getInfo().getNumMessagesSpooled().longValue());
String status = te.getInfo().getIngressConfigStatus().substring(0, 1).toUpperCase();
status += " " + te.getInfo().getEgressConfigStatus().substring(0, 1).toUpperCase();
status += " " + te.getInfo().getIngressSelectorPresent().substring(0, 1).toUpperCase();
status += " " + te.getInfo().getType().substring(0, 1).toUpperCase();
ti.setStatus(status);
tiMap.put(ti.getEndpoint(), ti);
}
} catch (JCSMPException e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
if (cons != null)
cons.close();
if (prod != null)
prod.close();
}
return tiMap.values().toArray(new SolTopicInfo[0]);
}
/**
* Return the SolQueueInfo for this queue (or all queues if 'queue' is null).
*
* #param session
* #param queue
* #param vpn (if null, use the session's vpn name)
* #param sempVersion, if null use 'soltr/7_1_1'
* #return
*/
public static SolQueueInfo[] getQueueInfo(JCSMPSession session, String queue, String vpn,
String sempVersion) {
XMLMessageConsumer cons = null;
XMLMessageProducer prod = null;
Map<String, SolQueueInfo> qiMap = new HashMap<String, SolQueueInfo>();
try {
// Create a producer and a consumer, and connect to appliance.
prod = session.getMessageProducer(new PubCallback());
cons = session.getMessageConsumer(new SubCallback());
cons.start();
if (vpn == null) vpn = (String) session.getProperty(JCSMPProperties.VPN_NAME);
if (sempVersion == null) sempVersion = getSempVersion(session);
// Extract the router name.
final String SEMP_SHOW_QUEUE_SUBS = "<rpc semp-version=\""
+ sempVersion
+ "\"><show><queue><name>"
+ queue
+ "</name><vpn-name>"+ vpn + "</vpn-name><subscriptions/><count/><num-elements>200</num-elements></queue></show></rpc>";
RpcReply queueSubs = sendRequest(session, SEMP_SHOW_QUEUE_SUBS);
for (QueueType qt : queueSubs.getRpc().getShow().getQueue().getQueues().getQueueArray()) {
SolQueueInfo qi = new SolQueueInfo();
qi.setBindCount(qt.getInfo().getBindCount());
//qi.setDescription(qt.getInfo().getNetworkTopic());
qi.setName(qt.getName());
qi.setMessageVPN(qt.getInfo().getMessageVpn());
qi.setDurable(qt.getInfo().getDurable());
qi.setEgSelPres(qt.getInfo().getEgressSelectorPresent());
qi.setHwmMB(formatter.format(qt.getInfo().getHighWaterMarkInMb()));
qi.setMessagesSpooled(qt.getInfo().getNumMessagesSpooled().longValue());
qi.setSpoolUsageMB(formatter.format(qt.getInfo().getCurrentSpoolUsageInMb()));
String status = qt.getInfo().getIngressConfigStatus().substring(0, 1).toUpperCase();
status += " " + qt.getInfo().getEgressConfigStatus().substring(0, 1).toUpperCase();
status += " " + qt.getInfo().getAccessType().substring(0, 1).toUpperCase();
status += " " + qt.getInfo().getEgressSelectorPresent().substring(0, 1).toUpperCase();
status += " " + qt.getInfo().getType().substring(0, 1).toUpperCase();
status += qt.getInfo().getDurable() ? " D" : " N";
qi.setStatus(status);
for (Subscription sub : qt.getSubscriptions().getSubscriptionArray()) {
qi.addSubscription(sub.getTopic());
}
qiMap.put(qi.getName(), qi);
}
} catch (JCSMPException e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
if (cons != null)
cons.close();
if (prod != null)
prod.close();
}
return qiMap.values().toArray(new SolQueueInfo[0]);
}
private static String getSempVersion(JCSMPSession session)
{
String retval = "soltr/7_1_1";
try {
String peerVersion = (String)session.getCapability(CapabilityType.PEER_SOFTWARE_VERSION);
if (peerVersion != null)
{
retval = "soltr/";
String[] version = peerVersion.split("\\.");
retval += version[0];
retval += "_" + version[1];
if (!version[2].equals("0")) retval += "_" + version[2];
}
} catch (Throwable e) {
System.err.println(e);
}
return retval;
}
private static RpcReply sendRequest(JCSMPSession session,
final String requestStr) {
try {
// Set up the requestor and request message.
String routerName = (String) session
.getCapability(CapabilityType.PEER_ROUTER_NAME);
final String SEMP_TOPIC_STRING = String.format("#SEMP/%s/SHOW",
routerName);
final Topic SEMP_TOPIC = JCSMPFactory.onlyInstance().createTopic(
SEMP_TOPIC_STRING);
Requestor requestor = session.createRequestor();
BytesXMLMessage requestMsg = JCSMPFactory.onlyInstance().createMessage(
BytesXMLMessage.class);
requestMsg.writeAttachment(requestStr.getBytes());
BytesXMLMessage replyMsg = requestor
.request(requestMsg, 5000, SEMP_TOPIC);
String replyStr = new String();
if (replyMsg.getAttachmentContentLength() > 0) {
byte[] bytes = new byte[replyMsg.getAttachmentContentLength()];
replyMsg.readAttachmentBytes(bytes);
replyStr = new String(bytes, "US-ASCII");
}
RpcReplyDocument doc = RpcReplyDocument.Factory.parse(replyStr);
RpcReply reply = doc.getRpcReply();
if (reply.isSetPermissionError()) {
throw new RuntimeException(
"Permission Error: Make sure SEMP over message bus SHOW commands are enabled for this VPN");
}
if( reply.isSetParseError() ) {
throw new RuntimeException( "SEMP Parse Error: " + reply.getParseError() );
}
if( reply.isSetLimitError() ) {
throw new RuntimeException( "SEMP Limit Error: " + reply.getLimitError() );
}
if( reply.isSetExecuteResult() && reply.getExecuteResult().isSetReason() ) { // axelp: encountered this error on invalid 'queue' name
throw new RuntimeException( "SEMP Execution Error: " + reply.getExecuteResult().getReason() );
}
return reply;
} catch (JCSMPException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (XmlException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
You can get message VPN specific queues and topics using following SEMPv2 command.
curl -s -X GET -u semp_user:semp_pass management_host:management_port/SEMP/v2/monitor/msgVpns/{vpn-name}/queues?select="queueName"
curl -s -X GET -u semp_user:semp_pass management_host:management_port/SEMP/v2/monitor/msgVpns/{vpn-name}/topicEndpoints?select="topicEndpointName"
I Know this question has been asked multiple times, but I couldn't find one working for me.
Basically I am trying to get a youtube video basic info which I get the proper result for that but then when I trigger to get the comments of that video the error pops out saying:
There was a service error: 403 : Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.
My code:
public String getyoutubeitemfull_details(String URI) throws SQLException, IOException{
try {
YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("APP_ID").build();
String apiKey = "API Key";
YouTube.Videos.List listVideosRequest = youtube.videos().list("statistics");
listVideosRequest.setId("qUvPzjSWMSM");
listVideosRequest.setKey(apiKey);
VideoListResponse listResponse = listVideosRequest.execute();
Video video = listResponse.getItems().get(0);
BigInteger viewCount = video.getStatistics().getViewCount();
BigInteger Likes = video.getStatistics().getLikeCount();
BigInteger DisLikes = video.getStatistics().getDislikeCount();
BigInteger Comments = video.getStatistics().getCommentCount();
System.out.println("[View Count] " + viewCount);
System.out.println("[Likes] " + Likes);
System.out.println("[Dislikes] " + DisLikes);
System.out.println("[Comments] " + Comments);
CommentThreadListResponse videoCommentsListResponse = youtube.commentThreads()
.list("snippet").setVideoId("qUvPzjSWMSM").setMaxResults(50l).setTextFormat("plainText").execute();
List<CommentThread> videoComments = videoCommentsListResponse.getItems();
for (CommentThread videoComment : videoComments) {
CommentSnippet snippet = videoComment.getSnippet().getTopLevelComment().getSnippet();
System.out.println(" - Author: " + snippet.getAuthorDisplayName());
System.out.println(" - Comment: " + snippet.getTextDisplay());
System.out.println("\n-------------------------------------------------------------\n");
}
} catch (GoogleJsonResponseException e) {
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
} catch (IOException e) {
System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
FYI: So much of question that I have been through so far talk about adding listVideosRequest.setKey(apiKey); which I have it done. I also Have enable OAuth 2.0 enabled in my google console.
Thanks to #DalmTo for throwing to its direction.
Basically Api Key doesn't have priviledges to retrieve comments and things like that. for deep priviledges I had to use Oauth, which basically is being created the same was as API Key but in Oauth you receive a client_secrets.json file containing: client secret, client ID and etc...
Then you call that in you code.
Note: Their is verious ways of calling you client_secrets.json file but it depends on your need.
My way: Reader clientSecretReader = new InputStreamReader(
new FileInputStream("/home/Downloads/src/client_secrets.json"));
I use OpenCmis in-memory for testing. But when I create a document I am not allowed to set the versioningState to something else then versioningState.NONE.
The doc created is not versionable some way... I used the code from http://chemistry.apache.org/java/examples/example-create-update.html
The test method:
public void test() {
String filename = "test123";
Folder folder = this.session.getRootFolder();
// Create a doc
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
properties.put(PropertyIds.NAME, filename);
String docText = "This is a sample document";
byte[] content = docText.getBytes();
InputStream stream = new ByteArrayInputStream(content);
ContentStream contentStream = this.session.getObjectFactory().createContentStream(filename, Long.valueOf(content.length), "text/plain", stream);
Document doc = folder.createDocument(
properties,
contentStream,
VersioningState.MAJOR);
}
The exception I get:
org.apache.chemistry.opencmis.commons.exceptions.CmisConstraintException: The versioning state flag is imcompatible to the type definition.
What am I missing?
I found the reason...
By executing the following code I discovered that the OBJECT_TYPE_ID 'cmis:document' don't allow versioning.
Code to view all available OBJECT_TYPE_ID's (source):
boolean includePropertyDefintions = true;
for (t in session.getTypeDescendants(
null, // start at the top of the tree
-1, // infinite depth recursion
includePropertyDefintions // include prop defs
)) {
printTypes(t, "");
}
static void printTypes(Tree tree, String tab) {
ObjectType objType = tree.getItem();
println(tab + "TYPE:" + objType.getDisplayName() +
" (" + objType.getDescription() + ")");
// Print some of the common attributes for this type
print(tab + " Id:" + objType.getId());
print(" Fileable:" + objType.isFileable());
print(" Queryable:" + objType.isQueryable());
if (objType instanceof DocumentType) {
print(" [DOC Attrs->] Versionable:" +
((DocumentType)objType).isVersionable());
print(" Content:" +
((DocumentType)objType).getContentStreamAllowed());
}
println(""); // end the line
for (t in tree.getChildren()) {
// there are more - call self for next level
printTypes(t, tab + " ");
}
}
This resulted in a list like this:
TYPE:CMIS Folder (Description of CMIS Folder Type) Id:cmis:folder
Fileable:true Queryable:true
TYPE:CMIS Document (Description of CMIS Document Type)
Id:cmis:document Fileable:true Queryable:true [DOC Attrs->]
Versionable:false Content:ALLOWED
TYPE:My Type 1 Level 1 (Description of My Type 1 Level 1 Type)
Id:MyDocType1 Fileable:true Queryable:true [DOC Attrs->]
Versionable:false Content:ALLOWED
TYPE:VersionedType (Description of VersionedType Type)
Id:VersionableType Fileable:true Queryable:true [DOC Attrs->]
Versionable:true Content:ALLOWED
As you can see the last OBJECT_TYPE_ID has versionable: true... and when I use that it does work.
I'm trying to find out how to list the music on my computer by a certain artist. I understand how to list all the music in the directory but I can't find a way to show only the music from one of the artists. Below is the code I'm using to list all the music in the directory.
How do I search the meta data for the artist's name and filter those files? Feel free to comment on the code if that's not a good way to list the files, I'm pretty new to all of this.
Code Fragment:
File musicList = new File("C:\\Users\\Music");
String[] fileNames = musicList.list();
String songsResponse = "";
int number = 1;
for(int i = 0; i < fileNames.length; i++)
{
if(fileNames[i].endsWith(".mp3"))
{
songsResponse += (number + ". ") + fileNames[i] + "\n";
number++;
}
}
You could also try Java ID3 Tag Library, which supports ID3v1, ID3v1.1, Lyrics3v1, Lyrics3v2, ID3v2.2, ID3v2.3, and ID3v2.4 tags as well as reading MP3 Frame Headers:
private void printArtistFromMp3() {
final String DIRECTORY = "C:\\Freek\\Dropbox\\Freek\\Muziek\\Queens of the Stone Age\\2000 - R\\";
try {
final MP3File mp3File = new MP3File(DIRECTORY + "01-Feel good hit of the summer.mp3");
if (mp3File.hasID3v1Tag())
System.out.println("Artist (ID3v1 tag): " + mp3File.getID3v1Tag().getArtist());
if (mp3File.hasID3v2Tag())
System.out.println("Lead artist (ID3v2 tag): " + mp3File.getID3v2Tag().getLeadArtist());
} catch (IOException e) {
e.printStackTrace();
} catch (TagException e) {
e.printStackTrace();
}
}
The code above printed "Lead artist (ID3v2 tag): Queens of the Stone Age" on my laptop.
Take a look at Jaudiotagger:
Supports MP3 ID3v1,ID3v11, ID3v2.2, v2.3 and v2.4 are transparently