Create a web script to get the parameters of the document in java
Example url
localhost:8080/alfresco/s/get-document-data?nodeRef=workspace://SpacesStore/3b3597e5-b5ec-41d5-b63b-54b050dccd1b&property=cm:name
For implementation we use NodeService
nodeService.getProperty (new NodeRef (nodeRef), LmrContentModel.getQname (property));
As a result the script should return Json object of a kind
{
"nodeRef": "workspace: // SpacesStore / 3b3597e5-b5ec-41d5-b63b-54b050dccd1b",
"value": "value property - the one we got from nodRef"
}
Create a web script to retrieve all subfolder settings along the way.
Please help!
public class SimpleWebScript extends AbstractWebScript {
#Override
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
try {
List<ChildAssociationRef> nodeRef = nodeService.getChildAssocs(companyHomeRef);
for (ChildAssociationRef childAssoc : nodeRef) {
NodeRef childNodeRef = childAssoc.getChildRef();
JSONObject obj = new JSONObject();
obj.put("nodeRef", childAssoc);
obj.put("value", childAssoc.getQName());
String jsonString = obj.toString();
res.getWriter().write(jsonString);
ServiceRegistry serviceRegistry = (ServiceRegistry) context.getBean("ServiceRegistry");
}
} catch (JSONException e) {
throw new WebScriptException("Unable to serialize JSON");
}
}
}
<beans>
<bean id="webscript.org.alfresco.simple.get"
class="org.alfresco.repository.SimpleWebScript"
parent="webscript">
</bean>
</beans>
<webscript>
<shortname>Document</shortname>
<description></description>
<url>/demoSimple?nodeRef={nodeRef}&attach={attach?}</url>
<format default="json"></format>
<authentication>user</authentication>
<family>Alfresco Document</family>
</webscript>
Here I want to get the parameters of the document here is the code but it doesn't work, what's wrong with it?
Related
I'm trying to deserialize the below XML to an object, but one of the values (Required)is returning null.
<?xml version="1.0" encoding="UTF-8"?>
-<sy:config xmlns:sy="http://www.example.com/def/sy">
-<sy:configurations>
-<sy:configuration property="isReq" name="ABC">
**Required**
<atom:link title="ABC Uri" xmlns:atom="http://www.w3.org/2005/Atom" rel="http://www.example.com/def//id"
href="abc/bc/def/docid"/>
</sy:configuration>
</sy:configurations>
</sy:config>
enter code here
I'm using the below code to deserialize eclipse emfutil to deserialize could you please let me know why the configuration.getvalue() is returning null instead of returning 'Required'
private static <T extends EObject> T readEObjectFromInputStream(InputStream inputStream, String emfFileExtension,Class<T> expectedResultType) throws IOException {
org.eclipse.emf.common.util.URI emfResourceUri = org.eclipse.emf.common.util.URI
.createPlatformResourceURI(FILE_PATH + emfFileExtension, true);
Resource emfResource = new ResourceSetImpl().createResource(emfResourceUri);
emfResource.load(inputStream, null);
EObject eObject = emfResource.getContents().get(0);
T result = expectedResultType.cast(eObject);
return result;
}
This post on the Eclipse forums has an example of how to do this, and a discussion of several reasons why it might not be working.
Here's the full example:
try { ResourceSet resourceSet = new ResourceSetImpl();
Resource resource = resourceSet.createResource(URI.createURI("http:///My.chbasev21"));
DocumentRoot documentRoot = ChbaseV21Factory.eINSTANCE.createDocumentRoot();
CompanyDetailsType root = ChbaseV21Factory.eINSTANCE.createCompanyDetailsType();
documentRoot.setCompanyDetails(root);
resource.getContents().add(documentRoot);
//resource.save(Collections.EMPTY_MAP);
resource.save(System.out, null);
resource.save(new FileOutputStream("C:/test2.xml"), null);
}
catch (IOException exception) {
exception.printStackTrace();
}
Sending the request to Server with the below xml for downloading
<?xml version="1.0" encoding="UTF-8"?>
<ResourceSet xmlns:v01"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<cycleTime>123</cycleTime>
<object>
<sourceUrl>http://10.34894.494/23.png</sourceUrl>
<accessUrl>http://10.126.45.72/cme/23.png</accessUrl>
<objectMetadata>
<headerName>Content-Length</headerName>
<headerName>E-Tag</headerName>
</objectMetadata>
</object>
<object>
<sourceUrl>http://10.84375.72/cme/23.png</sourceUrl>
<accessUrl>http://10.4575.572/cme/logo/23.png</accessUrl>
<objectMetadata>
<headerName>Content-Length</headerName>
<headerName>E-Tag</headerName>
</objectMetadata>
</object>
</ResourceSet>
There are 2 objects and which has same source URL and different Access URl .
My job is to download the image only once because source URL’s are duplicated .
Am iterating through the objects , but how I will know two objects has same source URL to download ?
There are 2 objects and which has same source URL and different Access URl .
My job is to download the image only once because source URL’s are duplicated .
Am iterating through the objects , but how I will know two objects has same source URL to download ?
public void download_resourceset_object_urls_images_to_local() throws Throwable {
List<String> sourceURis = GFDUtils.getSourceOrAccessURLs(xmlPath + xmlFileName, "sourceUrl");
dwInfoList = new HashMap<String, DownloadFileInfo>();
NSAUtils.removeFiles(ConfigLoader.DOWNLOAD_DIR);
boolean flag = HTTPClientFileDownload.downloadFile(sourceURis, ConfigLoader.DOWNLOAD_DIR, dwInfoList);
if (flag == true) {
logger.info("All URL files / images are downloaded successfully....");
} else
throw new GenericException("Files are not available / Failed download ");
}
here am iterating Xml and getting the Source URL to download
public static List<String> getSourceOrAccessURLs(String xmlPath, String urlname) throws IOException {
XStream xs = new XStream();
boolean flag = XMLValidation.validateXMLSchema(xmlPath);
File file = new File(xmlPath);
String xml = FileUtils.readFileToString(file);
if (flag == true) {
List<String> urls = new ArrayList<>();
try {
xs.processAnnotations(Resourceset.class);
Resourceset rs = (Resourceset) xs.fromXML(xml);
List<ResourcesetObject> rsoOject = rs.getResourcesetObject();
for (ResourcesetObject resourcesetObject : rsoOject) {
if (urlname.equals("sourceUrl")) {
urls.add(resourcesetObject.getSourceUrl());
} else {
urls.add(resourcesetObject.getAccessUrl());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return urls;
}
return null;
}
This URL Am passing for downloading.
Please help
Thanks,
With Spring 4 and Hibernate 4, I was able to use Reflection to get the Hibernate Configuration object from the current environment, using this code:
#Autowired LocalContainerEntityManagerFactoryBean lcemfb;
EntityManagerFactoryImpl emf = (EntityManagerFactoryImpl) lcemfb.getNativeEntityManagerFactory();
SessionFactoryImpl sf = emf.getSessionFactory();
SessionFactoryServiceRegistryImpl serviceRegistry = (SessionFactoryServiceRegistryImpl) sf.getServiceRegistry();
Configuration cfg = null;
try {
Field field = SessionFactoryServiceRegistryImpl.class.getDeclaredField("configuration");
field.setAccessible(true);
cfg = (Configuration) field.get(serviceRegistry);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
SchemaUpdate update = new SchemaUpdate(serviceRegistry, cfg);
With Hibernate 5, I must use some MetadataImplementor, which doesn't seems to be available from any of those objects. I also tried to use MetadataSources with the serviceRegistry. But it did say that it's the wrong kind of ServiceRegistry.
Is there any other way to get this working?
Basic idea for this problem is:
implementation of org.hibernate.integrator.spi.Integrator which stores required data to some holder. Register implementation as a service and use it where you need.
Work example you can find here https://github.com/valery-barysok/spring4-hibernate5-stackoverflow-34612019
create org.hibernate.integrator.api.integrator.Integrator class
import hello.HibernateInfoHolder;
import org.hibernate.boot.Metadata;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.service.spi.SessionFactoryServiceRegistry;
public class Integrator implements org.hibernate.integrator.spi.Integrator {
#Override
public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
HibernateInfoHolder.setMetadata(metadata);
HibernateInfoHolder.setSessionFactory(sessionFactory);
HibernateInfoHolder.setServiceRegistry(serviceRegistry);
}
#Override
public void disintegrate(SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
}
}
create META-INF/services/org.hibernate.integrator.spi.Integrator file
org.hibernate.integrator.api.integrator.Integrator
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
public void run(String... args) throws Exception {
new SchemaExport((MetadataImplementor) HibernateInfoHolder.getMetadata()).create(true, true);
new SchemaUpdate(HibernateInfoHolder.getServiceRegistry(), (MetadataImplementor) HibernateInfoHolder.getMetadata()).execute(true, true);
}
}
I would like to add up on Aviad's answer to make it complete as per OP's request.
The internals:
In order to get an instance of MetadataImplementor, the workaround is to register an instance of SessionFactoryBuilderFactory through Java's ServiceLoader facility. This registered service's getSessionFactoryBuilder method is then invoked by MetadataImplementor with an instance of itself, when hibernate is bootstrapped. The code references are below:
Service Loading
Invocation of getSessionFactoryBuilder
So, ultimately to get an instance of MetadataImplementor, you have to implement SessionFactoryBuilderFactory and register so ServiceLoader can recognize this service:
An implementation of SessionFactoryBuilderFactory:
public class MetadataProvider implements SessionFactoryBuilderFactory {
private static MetadataImplementor metadata;
#Override
public SessionFactoryBuilder getSessionFactoryBuilder(MetadataImplementor metadata, SessionFactoryBuilderImplementor defaultBuilder) {
this.metadata = metadata;
return defaultBuilder; //Just return the one provided in the argument itself. All we care about is the metadata :)
}
public static MetadataImplementor getMetadata() {
return metadata;
}
}
In order to register the above, create simple text file in the following path(assuming it's a maven project, ultimately we need the 'META-INF' folder to be available in the classpath):
src/main/resources/META-INF/services/org.hibernate.boot.spi.SessionFactoryBuilderFactory
And the content of the text file should be a single line(can even be multiple lines if you need to register multiple instances) stating the fully qualified class path of your implementation of SessionFactoryBuilderFactory. For example, for the above class, if your package name is 'com.yourcompany.prj', the following should be the content of the file.
com.yourcompany.prj.MetadataProvider
And that's it, if you run your application, spring app or standalone hibernate, you will have an instance of MetadataImplementor available through a static method once hibernate is bootstraped.
Update 1:
There is no way it can be injected via Spring. I digged into Hibernate's source code and the metadata object is not stored anywhere in SessionFactory(which is what we get from Spring). So, it's not possible to inject it. But there are two options if you want it in Spring's way:
Extend existing classes and customize all the way from
LocalSessionFactoryBean -> MetadataSources -> MetadataBuilder
LocalSessionFactoryBean is what you configure in Spring and it has an object of MetadataSources. MetadataSources creates MetadataBuilder which in turn creates MetadataImplementor. All the above operations don't store anything, they just create object on the fly and return. If you want to have an instance of MetaData, you should extend and modify the above classes so that they store a local copy of respective objects before they return. That way you can have a reference to MetadataImplementor. But I wouldn't really recommend this unless it's really needed, because the APIs might change over time.
On the other hand, if you don't mind building a MetaDataImplemetor from SessionFactory, the following code will help you:
EntityManagerFactoryImpl emf=(EntityManagerFactoryImpl)lcemfb.getNativeEntityManagerFactory();
SessionFactoryImpl sf=emf.getSessionFactory();
StandardServiceRegistry serviceRegistry = sf.getSessionFactoryOptions().getServiceRegistry();
MetadataSources metadataSources = new MetadataSources(new BootstrapServiceRegistryBuilder().build());
Metadata metadata = metadataSources.buildMetadata(serviceRegistry);
SchemaUpdate update=new SchemaUpdate(serviceRegistry,metadata); //To create SchemaUpdate
// You can either create SchemaExport from the above details, or you can get the existing one as follows:
try {
Field field = SessionFactoryImpl.class.getDeclaredField("schemaExport");
field.setAccessible(true);
SchemaExport schemaExport = (SchemaExport) field.get(serviceRegistry);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
Take a look on this one:
public class EntityMetaData implements SessionFactoryBuilderFactory {
private static final ThreadLocal<MetadataImplementor> meta = new ThreadLocal<>();
#Override
public SessionFactoryBuilder getSessionFactoryBuilder(MetadataImplementor metadata, SessionFactoryBuilderImplementor defaultBuilder) {
meta.set(metadata);
return defaultBuilder;
}
public static MetadataImplementor getMeta() {
return meta.get();
}
}
Take a look on This Thread which seems to answer your needs
Well, my go to on this:
public class SchemaTranslator {
public static void main(String[] args) throws Exception {
new SchemaTranslator().run();
}
private void run() throws Exception {
String packageName[] = { "model"};
generate(packageName);
}
private List<Class<?>> getClasses(String packageName) throws Exception {
File directory = null;
try {
ClassLoader cld = getClassLoader();
URL resource = getResource(packageName, cld);
directory = new File(resource.getFile());
} catch (NullPointerException ex) {
throw new ClassNotFoundException(packageName + " (" + directory + ") does not appear to be a valid package");
}
return collectClasses(packageName, directory);
}
private ClassLoader getClassLoader() throws ClassNotFoundException {
ClassLoader cld = Thread.currentThread().getContextClassLoader();
if (cld == null) {
throw new ClassNotFoundException("Can't get class loader.");
}
return cld;
}
private URL getResource(String packageName, ClassLoader cld) throws ClassNotFoundException {
String path = packageName.replace('.', '/');
URL resource = cld.getResource(path);
if (resource == null) {
throw new ClassNotFoundException("No resource for " + path);
}
return resource;
}
private List<Class<?>> collectClasses(String packageName, File directory) throws ClassNotFoundException {
List<Class<?>> classes = new ArrayList<>();
if (directory.exists()) {
String[] files = directory.list();
for (String file : files) {
if (file.endsWith(".class")) {
// removes the .class extension
classes.add(Class.forName(packageName + '.' + file.substring(0, file.length() - 6)));
}
}
} else {
throw new ClassNotFoundException(packageName + " is not a valid package");
}
return classes;
}
private void generate(String[] packagesName) throws Exception {
Map<String, String> settings = new HashMap<String, String>();
settings.put("hibernate.hbm2ddl.auto", "drop-create");
settings.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQL94Dialect");
MetadataSources metadata = new MetadataSources(
new StandardServiceRegistryBuilder()
.applySettings(settings)
.build());
for (String packageName : packagesName) {
System.out.println("packageName: " + packageName);
for (Class<?> clazz : getClasses(packageName)) {
System.out.println("Class: " + clazz);
metadata.addAnnotatedClass(clazz);
}
}
SchemaExport export = new SchemaExport(
(MetadataImplementor) metadata.buildMetadata()
);
export.setDelimiter(";");
export.setOutputFile("db-schema.sql");
export.setFormat(true);
export.execute(true, false, false, false);
}
}
I have custom class generator. in this generator I creating two classes
public class WsRpcServerGenerator extends Generator{
#Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
JClassType classType;
try {
classType = context.getTypeOracle().getType(typeName);
SourceWriter src;
try {
// generating first file xxxAsync for client
src = generateMethod( classType, context, logger);
// generating second class for server side
SourceWriter src2 = generateMethodArgs( classType, context, logger);
if (src2!=null)
src2.commit(logger);
} catch (Exception e) {}
// returning first class for client
if (src == null)return typeName + "__AsyncWsRpcGenerated";
src.commit(logger);
return typeName + "__AsyncWsRpcGenerated";
} catch (NotFoundException e) {}
}
}
I use
TestObject obj = GWT.create(TestObject.class);
This is work. gwt generated two files. and first is loaded in client.
But I dont know how I can load second file on server side. If I refreshing project in eclipse for visibility generated classes, class is loaded with test=Class.forName("com.xxx.TestObject__ArgsGenerated");. but I not wont refreshing project, its library.
Thanks
What Im looking how do it default gwtRpc, gwtRpc save info about rpc serialization policy, what Im saving to class com.xxx.TestObject__ArgsGenerated, to plain text file to web directory.
So I must go this way.
in my generator I must create resource file, and put serialization policy there.
public class WsRpcServerGenerator extends Generator{
#Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
JClassType classType;
try {
classType = context.getTypeOracle().getType(typeName);
SourceWriter src;
try {
// generating first file xxxAsync for client
src = generateMethod( classType, context, logger);
// generating file to war directorz
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(baos, SerializationPolicyLoader.SERIALIZATION_POLICY_FILE_ENCODING);
TypeOracle oracle = context.getTypeOracle();
PrintWriter pw = new PrintWriter(osw);
// generate content here
pw.close();
byte[] serializationPolicyFileContents = baos.toByteArray();
String serializationPolicyName = Util.computeStrongName(serializationPolicyFileContents);
String serializationPolicyFileName = SerializationPolicyLoader.getSerializationPolicyFileName(serializationPolicyName);
OutputStream os = context.tryCreateResource(logger, serializationPolicyFileName);
if (os != null) {
os.write(serializationPolicyFileContents);
GeneratedResource resource = ctx.commitResource(logger, os);
}
// returning first class for client
if (src == null)return typeName + "__AsyncWsRpcGenerated";
src.commit(logger);
return typeName + "__AsyncWsRpcGenerated";
} catch (NotFoundException e | IOException e) {}
}
}
reading policy on server side
HttpServlet servlet;
String modulename; // sended from client GWT.getModuleBaseURL() reolacing host
Sending serialiyationpolicyid; // from generated xxxAsync
// Open the RPC resource file and read its contents.
InputStream is=servlet.getServletContext().getResourceAsStream(modulename+"/"+serialiyationpolicyid+".rpc");
// read policy
Im found the solution and make own compiler inspirated by original gwt ClassSourceFileComposerFactory
Generator source
usage
DynamicJavaFileObject composer = new DynamicJavaFileObject("com.xxx","ClassName");
composer.setSuperclass("superclass");
composer.addImport(GWT.class.getCanonicalName());
SourceWriter writer = composer.getSourceWriter();
writer.println("public String test(){return \"test\"}");
writer.commit(logger);
Now I can find class on server side
Class.forName("com.xxx.ClassName");
When using regular JSP forms for printing to the client, configuring the web.xml properly works for me (http://stackoverflow.com/questions/2147958/how-do-i-prevent-people-from-doing-xss-in-java).
Is there any "best practice" on how to escape/entityze strings which will be send via JSON to a jQuery function, which then populates the DOM with these values? Any recommended libraries or Spring Web Framework build-ins?
jQuery $.ajax-call to Spring MVC
Spring MVC responds in JSON
(magic encoding happens, e.g. <a> becomes <a> ) <= this one
jQuery receives the JSON and populates the DOM XSS-safe
Thanks in advance!
edit: I am also sometimes sending HTML on purpose, so the solution would need to be able to only handle the user input. It will probably turn out that every user-poisoned string will have to be sanitized manually?
try this class which I wrote for my use .
it may be useful check wether any case is missing . . . as no detailed testing is done on this yet.
If any issue arise please let me know. . .
(add corresponding jar Apache commons and net.sf.json)
package myutil;
import java.util.Iterator;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringEscapeUtils;
public class JSONCleaner {
public static void main(String[] args) {
// TODO Auto-generated method stub
JSONObject jsonchild2=new JSONObject();
jsonchild2.put("subchlidkey1", "subchildvalue1");
jsonchild2.put("subchlidkey2", "subchildvalue2");
jsonchild2.put("subchlidkey3", "subchildvalue3");
JSONObject jsonchild=new JSONObject();
jsonchild.put("chlidkey1", "childvalue1");
jsonchild.put("chlidkey2", "childvalue2");
jsonchild.put("chlidkey3", "childvalue3");
JSONArray jsonarray=new JSONArray();
jsonarray.add("option1");
jsonarray.add("<p>option2</p>");
jsonarray.add(jsonchild2);
JSONObject json=new JSONObject();
json.put("name", "<b>nirbhay</b>");
json.put("age", 23);
json.put("jsonChildObject", jsonchild);
json.put("weight", 65);
json.put("array", jsonarray);
System.out.println(cleanJSONObject(json));
//System.out.println(json.getString("name"));
}
public static JSONObject cleanJSONObject(JSONObject jsonObject)
{
JSONObject returnJson=new JSONObject();
Iterator<?> keys = jsonObject.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
//System.out.println(jsonObject.get(key));
if(jsonObject.optJSONObject(key)==null)
{
if(jsonObject.optJSONArray(key)!=null)
{
returnJson.put(key, cleanJSONArray(jsonObject.getJSONArray(key)));
}
else
{
returnJson.put(key, StringEscapeUtils.escapeHtml(jsonObject.getString(key)));
}
}
else
{
returnJson.put(key,cleanJSONObject(jsonObject.optJSONObject(key)));
}
}
return returnJson;
}
private static JSONArray cleanJSONArray(JSONArray array)
{
JSONArray returnArray=new JSONArray();
for(int i=0,j=array.size();i<j;i++)
{
if(array.optJSONObject(i)==null)
{
if(array.optJSONArray(i) != null)
{
returnArray.add(cleanJSONArray((JSONArray) array.get(i)));
}
else
{
returnArray.add(StringEscapeUtils.escapeHtml(array.getString(i)));
}
}
else
{
returnArray.add(cleanJSONObject((JSONObject) array.get(i)));
}
}
return returnArray;
}
}