I need to create the Structure and Template progrmatically through java code.I used following code snippets.
Structure:
public void createStructure(String userName,long userId){
log_.info("Inside create structure ");
long structureId=115203;
DDMStructure ddmStructure=DDMStructureLocalServiceUtil.createDDMStructure(structureId);
ddmStructure.setName("MigrationStructure");
ddmStructure.setDescription("This Structure created programatically");
ddmStructure.setUserId(userId);
ddmStructure.setUserName(userName);
File fXmlFile = new File("D:/FilesDataMigration/structure.xml");
try {
Document document = SAXReaderUtil.read(fXmlFile);
ddmStructure.setDocument(document);
DDMStructureLocalServiceUtil.addDDMStructure(ddmStructure);
}catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log_.info("Inside create structure done");
}
Template:
public void createTemplate(String userName,long userId){
log_.info("Inside create template ");
long templateId=12504;
DDMTemplate ddmTemplate=DDMTemplateLocalServiceUtil.createDDMTemplate(templateId);
ddmTemplate.setName("MigrationTemplate");
ddmTemplate.setDescription("This Template created programatically");
ddmTemplate.setUserId(userId);
ddmTemplate.setUserName(userName);
try {
BufferedReader br = new BufferedReader(new FileReader("D:/FilesDataMigration/template.txt"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String script = sb.toString();
ddmTemplate.setScript(script);
DDMTemplateLocalServiceUtil.addDDMTemplate(ddmTemplate);
}catch(IOException e){
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log_.info("Inside create template done");
}
The above snippets are executing properly with out any exceptions But unable to see in the content section of Control Panel.Suggest me if anything wrong
There are couple of issues with your code:
You are not setting all the required properties, like groupId, companyId, classNameId, structureKey, dates etc.
There isn't any setName and setDescription method for DDMStructure or DDMTemplate accepting String argument (Liferay 6.2 GA2). Instead, there are only setNameMap and setDescriptionMap methods for both accepting Map<Locale, String>.
Use dynamic ids (structureId and templateId) in place of hard-coded ids, as following:
DDMStructure ddmStructure = DDMStructureUtil.create(CounterLocalServiceUtil.increment());and
DDMTemplate ddmTemplate = DDMTemplateUtil.create(CounterLocalServiceUtil.increment());
For classNameId, you can get it using it's value, like:
ClassName className = ClassNameLocalServiceUtil.getClassName("com.liferay.portlet.journal.model.JournalArticle");
long classNameId = className.getClassNameId();
Also, better to use update over populated object in place of adding:
DDMStructureUtil.update(ddmStructure);
and
DDMTemplateUtil.update(ddmTemplate);
Additionally, if you have access to the ThemeDisplay object, you can get groupId, companyId, userId, userFullName from it. Also, set new Date() for createDate and modifiedDate properties.
Related
The first method below (getMetadataTitle) simply retrieves the Title metadata from an mp3 file. It works fine. How would one write or update the Title metadata in the mp3 file, see the second method (putMetadataTitle) below?
private String getMetadataTitle(Context myContext, Uri myMp3) {
MediaMetadataRetriever retriever;
String title = null;
try {
retriever = new MediaMetadataRetriever();
retriever.setDataSource(myContext, myMp3);
title = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
} catch (Exception e) {
e.printStackTrace();
}
return title;
}
private void putMetadataTitle(String newTitle, Uri myMp3) {
// need help here!
}
Here is the completed putMetadataTitle() method from my question. I downloaded the MyID3_for_android jar file as suggested in question 9707572 and answers, How to get and set (change) ID3 tag (metadata) of audio files?.
private void putMetadataTitle(String newTitle, Uri myUri) {
File myMp3 = new File(myUri.getPath());
MusicMetadataSet mySet = null;
MusicMetadata myMetadata = new MusicMetadata("name");
try {
mySet = new MyID3().read(myMp3);
if (mySet == null) {
Log.i("NULL", "NULL");
} else {
myMetadata.setSongTitle(newTitle);
new MyID3().update(myMp3, mySet, myMetadata);
}
} catch (Exception e) {
e.printStackTrace();
}
}
My purpose is to upload the file on primary location synchronously and same time upload same file on multiple secondary locations asynchronously. So can you please help me to implement multi threading for secondary locations writing(e.g. same file to write multiple paths simultaneously while reading it)
Below is a code to read from input stream
List<FileUploadMultiLocator> fileUploadList = new ArrayList<>();
FileUploadMultiLocator fum1 = new FileUploadMultiLocator("fileserver0", new BufferedOutputStream(new FileOutputStream(new File(reposMap.get("D:\\Harisingh\\FileUpload\\Destination1.txt")))));
FileUploadMultiLocator fum2 = new FileUploadMultiLocator("fileserver0", new BufferedOutputStream(new FileOutputStream(new File(reposMap.get("D:\\Harisingh\\FileUpload\\Destination2.txt")))));
fileUploadList.add(fum1);
fileUploadList.add(fum2);
while((len=channel.read(byteBuffer))>=0)
{
itrCount++;
totalBytes+=len;
baOS.write(byteBuffer.array(),0,len);
if(itrCount>=maxIterateCnt)
{
//primary location writing
bFout.write(baOS.toByteArray(),0,totalBytes);
// this is for secondary location writing
for (FileUploadMultiLocator fileUploadMultiLocator : fileUploadList) {
fileUploadMultiLocator.baOS = baOS;
fileUploadMultiLocator.totalBytes = totalBytes;
new Thread(fileUploadMultiLocator).start();
}
totalBytes=0;
baOS.reset();
itrCount=0;
}
byteBuffer.clear();
}
This is my runnable class to write multiple BufferedOutputStream same time
public class FileUploadMultiLocator implements Runnable{
public FileUploadMultiLocator(String fileserver,BufferedOutputStream bFout) {
// TODO Auto-generated constructor stub
this.fileserver = fileserver;
this.bFout = bFout;
}
#Override
public void run() {
// TODO Auto-generated method stub
try
{
bFout.write(baOS.toByteArray(),0,totalBytes);
bFout.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I have somewhat lost touch with custom search engines ever since Google switched from its more legacy search engine api in favor of the google custom search api. I'm hoping someone might be able to tell me whether a (pretty simple) goal can be accomplished with the new framework, and potentially any starting help would be great.
Specifically, I am looking to write a program which will read in text from a text file, then use five words from said document in a google search - the point being to figure out how many results accrue from said search.
An example input/output would be:
Input: "This is my search term" -- quotations included in the search!
Output: there were 7 total results
Thanks so much, all, for your time/help
First you need to create a Google Custom Search project inside you google account.
From this project you must obtain a Custom Search Engine ID , known as cx parameter. You must also obtain a API key parameter. Both of these are available from your Google Custom Search API project inside your google account.
Then, if you prefer Java , here's a working example:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class GoogleCustonSearchAPI {
public static void main(String[] args) throws Exception {
String key="your_key";
String qry="your_query";
String cx = "your_cx";
//Fetch urls
URL url = new URL(
"https://www.googleapis.com/customsearch/v1?key="+key+"&cx="+cx+"&q="+ qry +"&alt=json&queriefields=queries(request(totalResults))");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
//Remove comments if you need to output in JSON format
/*String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}*/
//Print the urls and domains from Google Custom Search String searchResult;
while ((searchResult = output.readLine()) != null) {
int startPos=searchResult.indexOf("\"link\": \"")+("\"link\": \"").length();
int endPos=searchResult.indexOf("\",");
if(searchResult.contains("\"link\": \"") && (endPos>startPos)){
String link=searchResult.substring(startPos,endPos);
if(link.contains(",")){
String tempLink = "\"";
tempLink+=link;
tempLink+="\"";
System.out.println(tempLink);
}
else{
System.out.println(link);
}
System.out.println(getDomainName(link));
}
}
conn.disconnect();
}
public static String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}
The "&queriefields=queries(request(totalResults))" is what makes the difference and gives sou what you need. But keep in mind that you can perform only 100 queries per day for free and that the results of Custom Search API are sometimes quite different from the those returned from Google.com search
If anybody would still need some example of CSE (Google Custom Search Engine) API, this is working method
public static List<Result> search(String keyword){
Customsearch customsearch= null;
try {
customsearch = new Customsearch(new NetHttpTransport(),new JacksonFactory(), new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) {
try {
// set connect and read timeouts
httpRequest.setConnectTimeout(HTTP_REQUEST_TIMEOUT);
httpRequest.setReadTimeout(HTTP_REQUEST_TIMEOUT);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
List<Result> resultList=null;
try {
Customsearch.Cse.List list=customsearch.cse().list(keyword);
list.setKey(GOOGLE_API_KEY);
list.setCx(SEARCH_ENGINE_ID);
Search results=list.execute();
resultList=results.getItems();
}
catch ( Exception e) {
e.printStackTrace();
}
return resultList;
}
This method returns List of Result Objects, so you can iterate through it
List<Result> results = new ArrayList<>();
try {
results = search(QUERY);
} catch (Exception e) {
e.printStackTrace();
}
for(Result result : results){
System.out.println(result.getDisplayLink());
System.out.println(result.getTitle());
// all attributes
System.out.println(result.toString());
}
I use gradle dependencies
dependencies {
compile 'com.google.apis:google-api-services-customsearch:v1-rev57-1.23.0'
}
Don't forget to define your own GOOGLE_API_KEY, SEARCH_ENGINE_ID (cx), QUERY and HTTP_REQUEST_TIMEOUT (ie private static final int HTTP_REQUEST_TIMEOUT = 3 * 600000;)
I have looked in so many places on a lead on how or if it is possible to view images uploaded to cloudinary, by a specific tag through Android studio app i am trying to build.
I was able to implement the upload option by user, with adding a tag to the images, and public id, also retrieving these information, but i cant find anything on how to view these images, for example i want the app to be able to view all images with a specific tag ( username ) to the user that uploaded the pictures, and could delete them ? and also view other images uploaded by other user with no other permission.
Is it possible and how !?
I ended up with this code, and i encountered a problem;
#Override
public void onClick(View v) {
new JsonTask().execute("http://res.cloudinary.com/cloudNAme/video/list/xxxxxxxxxxxxxxxxxxx.json");
// uploadExtract();
}
});
public class JsonTask extends AsyncTask<String ,String,String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
In the log i get the following;
03-28 12:36:14.726 20333-21459/net.we4x4.we4x4 W/System.err: java.io.FileNotFoundException: http://res.cloudinary.com/we4x4/video/list/3c42f867-8c3a-423b-89e8-3fb777ab76f8.json
i am not sure if my understanding is correct of the method or i am doing something wrong ? since in the Admin API Docs. or cloudinary the syntax for the HTML request and also in the suggested page by Nadav:
https://support.cloudinary.com/hc/en-us/articles/203189031-How-to-retrieve-a-list-of-all-resources-sharing-the-same-tag-
this should've returned a JSON ?
The following feature allows you to retrieve a JSON formatted list of resources that which share a common tag:
https://support.cloudinary.com/hc/en-us/articles/203189031-How-to-retrieve-a-list-of-all-resources-sharing-the-same-tag-
Note that image removal will coerce you to use server-side code (e.g. JAVA), since deleting via Cloudinary requires a signature that is based on your API_SECRET.
I'm using asyncTask to download some files over the internet. This is the code I've written which works
downloadUrl task = new downloadUrl(url1,"jsonData1","/sdcard/appData/LocalJson/jsonData1",context);
task.execute();
downloadUrl task1 = new downloadUrl(url2,"jsonData2","/sdcard/appData/LocalJson/jsonData2",context);
task1.execute();
downloadUrl task2 = new downloadUrl(url3,"jsonData3","/sdcard/appData/LocalJson/jsonData3",context);
task2.execute();
downloadUrl task3 = new downloadUrl(url4,"jsonData4","/sdcard/appData/LocalJson/jsonData4",context);
task3.execute();
Now, the tasks run in parallel considering the UI-Thread but they run serialized between one another, which is time consuming. So instead I've tried to execute them on the executor But the thing is that this way I'm missing some files, meaning that when they run serialized I end up with 38 files downloaded while the run on the Executor I end up with 20. I'm pretty sure that is, because I messed up something in the multi-threading code So I'll post it that to:
#Override
protected String doInBackground(String... args) {
downloadAndStoreJson(url,targetFolder);
JSONObject jsonObj = loadJSONObject(pathForLoad);
try {
processJsonData(jsonObj);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "done";
}
#Override
protected void onPostExecute(String result) {
s(targetFolder+" Finished!");
++mutex;
progressBar.setProgress(25*mutex);
if(mutex==4){
mutex=0;
progressBar.setProgress(100);
progressBar.dismiss();
s(monuments.size());
Intent intent = new Intent (getApplicationContext(),NextClass.class);
intent.putExtra("monuments", monuments);
startActivity(intent);
}
}
private void downloadAndStoreJson(String url,String tag){
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
String jsonString = json.toString();
byte[] jsonArray = jsonString.getBytes();
File fileToSaveJson = new File("/sdcard/appData/LocalJson/",tag);
BufferedOutputStream bos;
try {
bos = new BufferedOutputStream(new FileOutputStream(fileToSaveJson));
bos.write(jsonArray);
bos.flush();
bos.close();
} catch (FileNotFoundException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
jsonArray=null;
jParser=null;
System.gc();
}
}
private JSONObject loadJSONObject(String path){
JSONObject jsonObj = null;
File readFromJson = new File(path);
byte[] lala;
try {
lala= org.apache.commons.io.FileUtils.readFileToByteArray(readFromJson);
s("---------------"+lala.length);
String decoded = new String(lala, "UTF-8");
jsonObj = new JSONObject(decoded);
} catch (IOException e5) {
// TODO Auto-generated catch block
e5.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObj;
}
and processJsonData is a long method which parses the json files, creates objects and then stores them in an ArrayList, that's where a problem might exist.
You need to make sure your code is Reentrant, meaning it must be possible to run it by several threads at the same time. Or if some code is used to syncronize the execution between your threads you need to make sure it is synchronized.
Looking at your code I see that the mutex is a static variable, which you use to keep track of your threads. Make sure that the operation on the mutex is synchronized, just to keep it clean. But that will not cause you problem...
I dont see your error in this code-snippet, either I fail to see the problem or it might be located in some other methods? Can you please share "downloadAndStoreJson"?