Project

General

Profile

« Previous | Next » 

Revision 47819

[maven-release-plugin] copy for tag cnr-enabling-inspector-2.0.2

View differences:

modules/cnr-enabling-inspector/tags/cnr-enabling-inspector-2.0.2/deploy.info
1
{"type_source": "SVN", "goal": "package -U -T 4C source:jar", "url": "http://svn-public.driver.research-infrastructures.eu/driver/dnet45/modules/cnr-enabling-inspector/trunk/", "deploy_repository": "dnet45-snapshots", "version": "4", "mail": "sandro.labruzzo@isti.cnr.it,michele.artini@isti.cnr.it, claudio.atzori@isti.cnr.it, alessia.bardi@isti.cnr.it", "deploy_repository_url": "http://maven.research-infrastructures.eu/nexus/content/repositories/dnet45-snapshots", "name": "cnr-enabling-inspector"}
modules/cnr-enabling-inspector/tags/cnr-enabling-inspector-2.0.2/src/test/java/eu/dnetlib/enabling/inspector/ResourceLinkToolTest.java
1
package eu.dnetlib.enabling.inspector;
2

  
3

  
4
import org.junit.Before;
5
import org.junit.Test;
6

  
7
import eu.dnetlib.enabling.tools.CompatResourceIdentifierResolverImpl;
8

  
9
public class ResourceLinkToolTest {
10

  
11
	private static String PROFILE = 
12
		"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
13
		"<RESOURCE_PROFILE xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n"+
14
		    "<HEADER>\n"+
15
		        "<RESOURCE_IDENTIFIER value=\"3cdc5e58-24c6-47ac-b678-401c84956e35_VHJhbnNmb3JtYXRpb25EU1Jlc291cmNlcy9UcmFuc2Zvcm1hdGlvbkRTUmVzb3VyY2VUeXBl\"/>\n"+
16
		        "<RESOURCE_TYPE value=\"TransformationDSResourceType\"/>\n"+
17
		        "<RESOURCE_KIND value=\"TransformationDSResources\"/>\n"+
18
		        "<RESOURCE_URI value=\"http://146.48.85.175:8280/efg-is/services/msro\"/>\n"+
19
		        "<DATE_OF_CREATION value=\"2010-10-27T10:41:24+02:00\"/>\n"+
20
		    "</HEADER>\n"+
21
		    "<BODY>\n"+
22
		        "<CONFIGURATION>\n"+
23
		            "<REPOSITORY_SERVICE_IDENTIFIER>d937bab1-d44c-44aa-bf7d-df5312a3b623_UmVwb3NpdG9yeVNlcnZpY2VSZXNvdXJjZXMvUmVwb3NpdG9yeVNlcnZpY2VSZXNvdXJjZVR5cGU=</REPOSITORY_SERVICE_IDENTIFIER>\n"+
24
		            "<TRANSFORMATION_MANAGER_SERVICE_IDENTIFIER/>\n"+
25
		            "<TRANSFORMATION_MANAGER_SERVICE_URI/>\n"+
26
		            "<SOURCE_METADATA_FORMATS>\n"+
27
		                "<SOURCE_METADATA_FORMAT name=\"oai_efg\" layout=\"store\" interpretation=\"native\"/>\n"+
28
		            "</SOURCE_METADATA_FORMATS>\n"+
29
		            "<SINK_METADATA_FORMAT interpretation=\"cleaned\" name=\"oai_efg\" layout=\"store\"/>\n"+
30
		            "<DATA_SOURCES>\n"+
31
		                "<DATA_SOURCE>dnet://MDStoreDS/8d1ab5bb-176c-4eef-9ed3-b46a0aa31d09_TURTdG9yZURTUmVzb3VyY2VzL01EU3RvcmVEU1Jlc291cmNlVHlwZQ==</DATA_SOURCE>\n"+
32
		            "</DATA_SOURCES>\n"+
33
		            "<DATA_SINK>dnet://MDStoreDS/a3a2c757-1726-41b2-9e37-bceb3f8bbd8b_TURTdG9yZURTUmVzb3VyY2VzL01EU3RvcmVEU1Jlc291cmNlVHlwZQ==?type=REFRESH</DATA_SINK>\n"+
34
		            "<TRANSFORMATION_RULE_DS_IDENTIFIER/>\n"+
35
		            "<SCHEDULING/>\n"+
36
		        "</CONFIGURATION>\n"+
37
		        "<STATUS>\n"+
38
		            "<LAST_UPDATE_DATE>2011-01-24T17:22:09+01:00</LAST_UPDATE_DATE>\n"+
39
		            "<LAST_UPDATE_STATUS>LAST_UPDATE_STATUS</LAST_UPDATE_STATUS>\n"+
40
		            "<LAST_UPDATE_ERROR_MESSAGE>LAST_UPDATE_ERROR_MESSAGE</LAST_UPDATE_ERROR_MESSAGE>\n"+
41
		        "</STATUS>\n"+
42
		        "<SECURITY_PARAMETERS>SECURITY_PARAMETERS</SECURITY_PARAMETERS>\n"+
43
		    "</BODY>\n"+
44
		"</RESOURCE_PROFILE>";		
45
	
46
	private ResourceLinkTool linkTool;
47
	
48
	@Before
49
	public void setUp() throws Exception {
50
		linkTool = new ResourceLinkTool();
51
		linkTool.setResolver(new CompatResourceIdentifierResolverImpl());
52
	}
53
	
54
	@Test
55
	public void linkfyToHtmlTest() {
56
		System.out.println(linkTool.linkfyToHtml(PROFILE));
57
	}
58

  
59
}
modules/cnr-enabling-inspector/tags/cnr-enabling-inspector-2.0.2/src/test/java/eu/dnetlib/enabling/inspector/TouchUtilsTest.java
1
package eu.dnetlib.enabling.inspector;
2

  
3
import static org.junit.Assert.*;
4

  
5
import org.apache.commons.logging.Log;
6
import org.apache.commons.logging.LogFactory;
7
import org.dom4j.DocumentException;
8
import org.junit.Before;
9
import org.junit.Test;
10

  
11
public class TouchUtilsTest {
12
	private static final Log log = LogFactory.getLog(TouchUtilsTest.class); // NOPMD by marko on 11/24/08 5:02 PM
13

  
14
	private transient TouchUtils touch;
15

  
16
	@Before
17
	public void setUp() throws Exception {
18
		touch = new TouchUtils();
19
	}
20

  
21
	@Test
22
	public void testUpdateProfile() throws DocumentException {
23
		log.fatal("test");
24

  
25
		final String res = touch.updateProfile("<a><b/></a>", "/a/b");
26
		System.out.println(res);
27
	}
28

  
29
	@Test(expected = DocumentException.class)
30
	public void testUpdateProfile2() throws DocumentException {
31
		touch.updateProfile("<a><b/></a>", "/a/x");
32
	}
33

  
34
	@Test(expected = DocumentException.class)
35
	public void testUpdateProfile3() throws DocumentException {
36
		touch.updateProfile("<a>xx</a>", "/a/text()");
37
	}
38

  
39
	@Test
40
	public void testVerifyIsDate() {
41
		assertTrue(touch.verifyIsDate("2010-04-27T12:04:22+02:00"));
42
		assertTrue(touch.verifyIsDate("2010-04-27T12:04:22Z"));
43
		assertTrue(touch.verifyIsDate("2010-04-27T12:04:22+00:00"));
44
		assertTrue(touch.verifyIsDate("2010-04-27T12:04:22+0000"));
45
		assertFalse(touch.verifyIsDate("201asdas"));
46
	}
47

  
48
	@Test
49
	public void testSpanize() {
50
		String res = touch.spanize("<a><b/><b><c v='1'/><c v='2'/></b></a>");
51
		System.out.println(res);
52
	}
53

  
54
}
modules/cnr-enabling-inspector/tags/cnr-enabling-inspector-2.0.2/src/test/resources/log4j.properties
1
log4j.rootLogger=INFO, Console
2

  
3
log4j.appender.Console=org.apache.log4j.ConsoleAppender
4
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
5
log4j.appender.Console.layout.ConversionPattern=%-5p [%t] %37c %3x - %m%n
6

  
7
log4j.logger.eu.dnetlib=INFO
8
log4j.logger.eu.dnetlib.enabling.test=DEBUG
9
log4j.logger.eu.dnetlib.enabling.is.sn=DEBUG
10
log4j.logger.eu.dnetlib.enabling.is.sn.resourcestate=DEBUG
11

  
12
log4j.logger.org.apache.cxf.interceptor=FATAL
13
log4j.logger.org.apache.cxf.ws.addressing.ContextUtils=FATAL
14
log4j.logger.eu.dnetlib.enabling.tools.AbstractBaseService=INFO
15
log4j.logger.eu.dnetlib.xml.database.LoggingTrigger=FATAL
16

  
17

  
18
log4j.logger.eu.dnetlib.enabling.inspector=WARN
modules/cnr-enabling-inspector/tags/cnr-enabling-inspector-2.0.2/src/main/java/eu/dnetlib/enabling/inspector/ResourceLinkTool.java
1
package eu.dnetlib.enabling.inspector;
2

  
3
import java.util.List;
4
import java.util.regex.Matcher;
5
import java.util.regex.Pattern;
6

  
7
import org.springframework.beans.factory.annotation.Required;
8

  
9
import com.google.common.collect.Lists;
10

  
11
import eu.dnetlib.enabling.tools.ResourceIdentifierResolver;
12

  
13
/**
14
 * This class allows to create links between profiles.
15
 *  
16
 * @author claudio
17
 *
18
 */
19
public class ResourceLinkTool {
20

  
21
	/**
22
	 * Regular expression used to match resource ids.
23
	 */
24
	private static String REGEX = "([a-zA-Z0-9]+\\-)+[a-zA-Z0-9]+_[a-zA-Z0-9]+";
25
	
26
	/**
27
	 * Base url.
28
	 */
29
	private String serviceBaseUrl;
30
	
31
	/**
32
	 * ResourceIdentifierResolver.
33
	 */
34
	private ResourceIdentifierResolver resolver;
35
	
36
	/**
37
	 * Method parses a profile and transforms all the ids into an html link
38
	 * 
39
	 * @param profile
40
	 * 			the given profile.
41
	 * @return
42
	 * 			the linkfied profile
43
	 */
44
	public String linkfyToHtml(final String profile) {
45
		String tmp = new String(profile);		
46
		for (String id : enumerateIds(profile))
47
			tmp = tmp.replaceAll(id, toLink(id));
48

  
49
		return tmp;
50
	}
51
	
52
	/**
53
	 * Performs the actual transformation.
54
	 * 
55
	 * @param id
56
	 * @return
57
	 */
58
	protected String toLink(String id) {
59
		return "<a href=\"" + serviceBaseUrl + 
60
					"/inspector/index.do/db/DRIVER/" + 
61
					getResolver().getCollectionName(id) + "/" + 
62
					getResolver().getFileName(id) + "/show\">" + id + "</a>";
63
	}
64

  
65
	/**
66
	 * Lists all the ids in the given profile.
67
	 * 
68
	 * @param profile
69
	 * @return
70
	 */
71
	private List<String> enumerateIds(final String profile) {
72
		List<String> ids = Lists.newArrayList(); 
73
		String tmp = new String(profile);
74
		
75
		Pattern p = Pattern.compile(REGEX);
76
		Matcher m = p.matcher(tmp);
77
		
78
		while(m.find())
79
			ids.add(m.group());
80
		return ids;
81
	}
82

  
83
	@Required
84
	public void setResolver(ResourceIdentifierResolver resolver) {
85
		this.resolver = resolver;
86
	}
87

  
88
	public ResourceIdentifierResolver getResolver() {
89
		return resolver;
90
	}
91

  
92
	@Required
93
	public void setServiceBaseUrl(String serviceBaseUrl) {
94
		this.serviceBaseUrl = serviceBaseUrl;
95
	}
96

  
97
	public String getServiceBaseUrl() {
98
		return serviceBaseUrl;
99
	}
100
}
modules/cnr-enabling-inspector/tags/cnr-enabling-inspector-2.0.2/src/main/java/eu/dnetlib/enabling/inspector/TouchUtils.java
1
package eu.dnetlib.enabling.inspector;
2

  
3
import java.io.StringReader;
4
import java.util.List;
5
import java.util.Map;
6
import java.util.Map.Entry;
7

  
8
import org.apache.commons.logging.Log;
9
import org.apache.commons.logging.LogFactory;
10
import org.dom4j.Attribute;
11
import org.dom4j.Document;
12
import org.dom4j.DocumentException;
13
import org.dom4j.Element;
14
import org.dom4j.Node;
15
import org.dom4j.io.SAXReader;
16

  
17
import com.google.common.collect.Maps;
18

  
19
import eu.dnetlib.miscutils.datetime.DateUtils;
20
import eu.dnetlib.miscutils.dom4j.XPathHelper;
21

  
22
/**
23
 * Utility class that provides the "touch" functionality
24
 * 
25
 * @author claudio
26
 *
27
 */
28
public class TouchUtils {
29

  
30
	/**
31
	 * logger
32
	 */
33
	private static final Log log = LogFactory.getLog(TouchUtils.class);
34
	
35
	/**
36
	 * Updates the date value of the given xpath
37
	 * 
38
	 * @param file
39
	 * @param xpath
40
	 * @return
41
	 * @throws DocumentException
42
	 */
43
	public String updateProfile(String file, String xpath) throws DocumentException {
44
		SAXReader reader = new SAXReader();
45

  
46
		log.debug("updating XPath: " + xpath);
47
		Document document = reader.read(new StringReader(file));
48

  
49
		Node node = document.selectSingleNode(xpath);
50

  
51
		if (node == null || (node.getNodeType() != Node.ELEMENT_NODE && node.getNodeType() != Node.ATTRIBUTE_NODE))
52
			throw new DocumentException("Invalid xpath: " + xpath + ": " + node);
53

  
54
		if (verifyIsDate(node.getText()))
55
			node.setText(DateUtils.now_ISO8601());
56

  
57
		return document.asXML();
58
	}
59

  
60
	/**
61
	 * 
62
	 * @param text
63
	 *            is the value to check
64
	 * @return true if text is a well formatted timestamp
65
	 */
66
	protected boolean verifyIsDate(String text) {
67
		try {
68
			new DateUtils().parse(text);
69
			return true;
70
		} catch (IllegalStateException e) {
71
			return false;
72
		}
73
	}
74

  
75
	/**
76
	 * Adds "<span id='xpath'>item</span>" where: - item is an element or an attribute name - xpath is the corresponding
77
	 * xpath
78
	 * 
79
	 * @param file
80
	 * @return the "spanized" xml file
81
	 */
82
	protected String spanize(String file) {
83
		SAXReader reader = new SAXReader();
84
		try {
85
			Document document = reader.read(new StringReader(file));
86
			traverse(document.getRootElement(), "/*");
87
			
88
			//TODO find a solution to this crime (damn dom4j!)
89
			return document.asXML().replace("&apos;", "'");
90
		} catch (DocumentException e) {
91
			log.warn(e);
92
			return e.getMessage();
93
		}
94
	}
95

  
96
	private void traverse(Element element, String xpathFather) {
97
		int i = 1;
98

  
99
		for (Element node : XPathHelper.selectElements(element, "./*")) {
100
			String xpath = xpathFather + "/*[" + (i++) + "]";
101

  
102
			Map<Attribute, String> attributeXPaths = Maps.newHashMap();
103

  
104
			@SuppressWarnings("unchecked")
105
			List<Attribute> attributes = (List<Attribute>) node.attributes();
106
			for (Attribute attribute : attributes)
107
				attributeXPaths.put(attribute, xpath + "/@" + attribute.getName());
108

  
109
			node.attributes().clear();
110
			for (Entry<Attribute, String> entry : attributeXPaths.entrySet()) {
111
				Attribute attribute = entry.getKey();
112
				String modifiedName = "_|span id='" + entry.getValue() + "'|_" + attribute.getName() + "_|/span|_";
113

  
114
				node.addAttribute(modifiedName, attribute.getValue());
115
			}
116
			if (node.isTextOnly())
117
				node.setName("_|span id='" + xpath + "'|_" + node.getName() + "_|/span|_");
118
			traverse(node, xpath);
119
		}
120
	}
121

  
122
	/**
123
	 * 
124
	 * @param file
125
	 * @return
126
	 */
127
	public String escape(String file) {
128
		return file.replace("_|", "<").replace("|_", ">");
129
	}
130
	
131
}
modules/cnr-enabling-inspector/tags/cnr-enabling-inspector-2.0.2/src/main/java/eu/dnetlib/enabling/inspector/SubscriptionController.java
1
package eu.dnetlib.enabling.inspector;
2

  
3
import java.util.ArrayList;
4
import java.util.HashMap;
5
import java.util.List;
6
import java.util.Map;
7

  
8
import javax.annotation.Resource;
9
import javax.xml.transform.dom.DOMResult;
10
import javax.xml.xpath.XPathExpressionException;
11
import javax.xml.xpath.XPathFactory;
12

  
13
import eu.dnetlib.enabling.is.sn.SubscriptionRegistry;
14
import org.apache.commons.logging.Log;
15
import org.apache.commons.logging.LogFactory;
16
import org.springframework.stereotype.Controller;
17
import org.springframework.ui.Model;
18
import org.springframework.web.bind.annotation.RequestMapping;
19
import org.springframework.web.bind.annotation.RequestParam;
20

  
21
import eu.dnetlib.enabling.is.sn.NotificationInvocationLogger;
22
import eu.dnetlib.enabling.is.sn.resourcestate.ResourceStateSubscription;
23
import eu.dnetlib.enabling.is.sn.resourcestate.ResourceStateSubscriptionRegistry;
24
import eu.dnetlib.miscutils.coupling.StaticCondition;
25

  
26
/**
27
 * Low-level basic interface for managing SN subscriptions.
28
 *
29
 * @author marko
30
 *
31
 */
32
@Controller
33
public class SubscriptionController extends AbstractInspectorController {
34
	/**
35
	 * logger.
36
	 */
37
	private static final Log log = LogFactory.getLog(SubscriptionController.class); // NOPMD by marko on 11/24/08 5:02 PM
38

  
39
	/**
40
	 * is sn subscription registries.
41
	 */
42
	@Resource(name = "issResourceStateNotificationRegistry")
43
	private transient SubscriptionRegistry registry;
44

  
45
	/**
46
	 * allows to control the global enable of issn.
47
	 */
48
	@Resource(name = "issnInhibitionCondition")
49
	private transient StaticCondition inhibitionCondition;
50

  
51
	/**
52
	 * issn invocation logger.
53
	 */
54
	@Resource
55
	private transient NotificationInvocationLogger invocationLogger;
56

  
57
	/**
58
	 * show a list of subscriptions.
59
	 *
60
	 * @param model
61
	 *            view parameters
62
	 * @return view
63
	 * @throws XPathExpressionException
64
	 *             could happen
65
	 */
66
	@RequestMapping("/inspector/sn.do")
67
	String listSubscriptions(final Model model) throws XPathExpressionException {
68

  
69
		log.debug("registries: " + registry);
70

  
71
		final List<Map<String, String>> subscriptions = new ArrayList<Map<String, String>>();
72

  
73
		for (ResourceStateSubscription sub : registry.listSubscriptions()) {
74
			final Map<String, String> attrs = new HashMap<String, String>(); // NOPMD
75
			attrs.put("prefix", sub.getPrefix());
76
			attrs.put("type", sub.getType());
77
			attrs.put("resourceId", sub.getResourceId());
78
			attrs.put("xpath", sub.getXpath());
79
			attrs.put("id", sub.getSubscriptionId());
80

  
81
			final DOMResult result = new DOMResult(); // NOPMD
82
			sub.getSubscriberAsEpr().writeTo(result);
83
			attrs.put("address", XPathFactory.newInstance().newXPath().evaluate("//*[local-name() = 'Address']", result.getNode()));
84
			subscriptions.add(attrs);
85
		}
86

  
87
		model.addAttribute("subscriptions", subscriptions);
88
		model.addAttribute("enabled", !inhibitionCondition.isTrue());
89
		return "inspector/subscriptions";
90
	}
91
	
92
	/**
93
	 * show a list of subscriptions.
94
	 *
95
	 * @param model
96
	 *            view parameters
97
	  @param address
98
	 *            the address prefix used as filter
99
	 * @return view
100
	 * @throws XPathExpressionException
101
	 *             could happen
102
	 */
103
	@RequestMapping("/inspector/snByAddress.do")
104
	String listSubscriptionsByAddress(final Model model, @RequestParam(value="address", required=false) final String address) throws XPathExpressionException {
105

  
106
		log.debug("registries: " + registry);
107

  
108
		final List<Map<String, String>> subscriptions = new ArrayList<Map<String, String>>();
109
		log.debug("Address is "+address);
110
		
111
			model.addAttribute("address", address);
112
			
113
			for (ResourceStateSubscription sub : registry.listSubscriptions()) {
114
				final DOMResult result = new DOMResult(); // NOPMD
115
				sub.getSubscriberAsEpr().writeTo(result);
116
				final String addr = XPathFactory.newInstance().newXPath().evaluate("//*[local-name() = 'Address']", result.getNode());
117

  
118
				if ( address==null || (addr != null && addr.startsWith(address)) ) {
119
					final Map<String, String> attrs = new HashMap<String, String>(); // NOPMD
120
					attrs.put("prefix", sub.getPrefix());
121
					attrs.put("type", sub.getType());
122
					attrs.put("resourceId", sub.getResourceId());
123
					attrs.put("xpath", sub.getXpath());
124
					attrs.put("id", sub.getSubscriptionId());
125
                    attrs.put("address", addr);
126
					subscriptions.add(attrs);
127
				}
128
			}
129

  
130
		model.addAttribute("subscriptions", subscriptions);
131
		model.addAttribute("enabled", !inhibitionCondition.isTrue());
132
		return "inspector/subscriptionsByAddress";
133
	}
134
	/**
135
	 * toggle global notification inhibit flag.
136
	 *
137
	 * @return view name (redirect)
138
	 */
139
	@RequestMapping("/inspector/toggleNotifications.do")
140
	String deleteSubscription() {
141
		inhibitionCondition.setCondition(! inhibitionCondition.isTrue());
142
		return "redirect:sn.do";
143
	}
144

  
145
	/**
146
	 * delete a issn subscription.
147
	 *
148
	 * @param subscriptionId
149
	 *            subscription identifier web parameter
150
	 * @return view name (redirect)
151
	 */
152
	@RequestMapping("/inspector/deleteSubscription.do")
153
	String deleteSubscription(@RequestParam("id") final String subscriptionId) {
154
		registry.removeSubscription(subscriptionId);
155
		return "redirect:sn.do";
156
	}
157
	
158
	/**
159
	 * delete issn subscriptions by address prefix.
160
	 * @param model
161
	 *            view parameters
162
	 * @param address
163
	 *            address prefix 
164
	 * @return view name (redirect)
165
	 * @throws XPathExpressionException 
166
	 */
167
	@RequestMapping("/inspector/deleteSubscriptionsByAddress.do")
168
	String deleteSubscriptionsByAddress(final Model model, @RequestParam("address") final String address) throws XPathExpressionException {
169
		
170
		final List<String> deleted = new ArrayList<String>();
171
		
172
		if (address != null && address.length() > "http://".length()) {
173

  
174
			for (ResourceStateSubscription sub : registry.listSubscriptions()) {
175
				final DOMResult result = new DOMResult(); // NOPMD
176
				sub.getSubscriberAsEpr().writeTo(result);
177
				final String addr = XPathFactory.newInstance().newXPath().evaluate("//*[local-name() = 'Address']", result.getNode());
178

  
179
				if (addr != null && addr.startsWith(address)) {
180
					String id = sub.getSubscriptionId();
181
					registry.removeSubscription(id);
182
					deleted.add(id + " ("+ addr +")");
183
				}
184
			}
185
		}
186
		
187
		model.addAttribute("deleted", deleted);
188
		
189
		return "inspector/deleteSubscriptionsByAddress";
190
	}
191
	/**
192
	 * Show log of notifications.
193
	 *
194
	 * @param model mvc model
195
	 */
196
	@RequestMapping("/inspector/notificationLog.do")
197
	void notificationLog(final Model model) {
198
		model.addAttribute("log", invocationLogger.getEntries());
199
	}
200
}
modules/cnr-enabling-inspector/tags/cnr-enabling-inspector-2.0.2/src/main/java/eu/dnetlib/enabling/inspector/BackupController.java
1
package eu.dnetlib.enabling.inspector;
2

  
3
import java.io.File;
4
import java.io.FileInputStream;
5
import java.io.FileReader;
6
import java.io.FilenameFilter;
7
import java.io.IOException;
8
import java.io.InputStream;
9
import java.io.OutputStream;
10
import java.io.StringWriter;
11
import java.util.Arrays;
12
import java.util.Comparator;
13

  
14
import javax.annotation.Resource;
15
import javax.servlet.http.HttpServletResponse;
16

  
17
import org.apache.commons.logging.Log;
18
import org.apache.commons.logging.LogFactory;
19
import org.apache.cxf.helpers.IOUtils;
20
import org.springframework.stereotype.Controller;
21
import org.springframework.ui.Model;
22
import org.springframework.web.bind.annotation.RequestMapping;
23
import org.springframework.web.bind.annotation.RequestParam;
24

  
25
import eu.dnetlib.enabling.is.sn.ISSNServiceCore;
26
import eu.dnetlib.xml.database.XMLDatabase;
27

  
28
/**
29
 * This controller offers a simple way to backup the xmldb.
30
 *
31
 * @author michele
32
 *
33
 */
34
@Controller
35
public class BackupController extends AbstractInspectorController {
36

  
37
	/**
38
	 * BUFFER size for file copy.
39
	 */
40
	private static final int BUFFER_SIZE = 4096;
41

  
42
	/**
43
	 * logger.
44
	 */
45
	private static final Log log = LogFactory.getLog(BackupController.class); // NOPMD by marko on 11/24/08 5:02 PM
46

  
47
	/**
48
	 * xmldb.
49
	 */
50
	@Resource(name = "existDatabase")
51
	private transient XMLDatabase xmlDatabase;
52
	
53
	/**
54
	 * is sn subscription registries.
55
	 */
56
	@Resource(name = "isSNServiceCore")
57
	private transient ISSNServiceCore issnServiceCore;
58
	
59
	private enum BackupType {
60
		profile, subscription
61
	}
62

  
63
	@RequestMapping(value = "/inspector/backups.do")
64
	public void backup(final Model model) {
65
		// only view
66
	}
67
	
68
	@RequestMapping(value = "/inspector/backupProfiles.do")
69
	public void backupProfiles(
70
			final Model model,
71
			@RequestParam(value = "exec", required = false) final String exec,
72
			@RequestParam(value = "delete", required = false) final String delete) {
73

  
74
		if (exec != null && exec.equals("1")) {
75
			execProfileBackup(model);
76
		}
77
		if (delete != null) {
78
			deleteBackup(model, xmlDatabase.getBackupDir(), delete);
79
		}
80

  
81
		listBackups(model, xmlDatabase.getBackupDir());
82
	}
83
	
84
	@RequestMapping(value = "/inspector/backupSubscriptions.do")
85
	public void backupSubscriptions(
86
			final Model model,
87
			@RequestParam(value = "exec", required = false) final String exec,
88
			@RequestParam(value = "delete", required = false) final String delete) {
89

  
90
		if (exec != null && exec.equals("1")) {
91
			execSubscriptionsBackup(model);
92
		}
93
		if (delete != null) {
94
			deleteBackup(model, issnServiceCore.getBackupDir(), delete);
95
		}
96

  
97
		listBackups(model, issnServiceCore.getBackupDir());
98
	}
99

  
100
	/**
101
	 * Executes a backup.
102
	 *
103
	 * @param model
104
	 *            mvc model
105
	 */
106
	private void execProfileBackup(final Model model) {
107
		try {
108
			xmlDatabase.backup();
109
			log.info("Backup done");
110
		} catch (final Exception e) {
111
			model.addAttribute("message", "Backup failed: please retry later");
112
			log.fatal("Backup failed", e);
113
		}
114
	}
115

  
116
	/**
117
	 * Executes a backup.
118
	 *
119
	 * @param model
120
	 *            mvc model
121
	 */
122
	private void execSubscriptionsBackup(final Model model) {
123
		try {
124
			issnServiceCore.backup();
125
			log.info("Backup done");
126
		} catch (final Exception e) {
127
			model.addAttribute("message", "Backup failed: please retry later");
128
			log.fatal("Backup failed", e);
129
		}
130
	}	
131
	
132
	/**
133
	 * Deletes a backup.
134
	 *
135
	 * @param model
136
	 *            mvc model
137
	 * @param backup
138
	 *            backup file name
139
	 */
140
	private void deleteBackup(final Model model, final String backupDir, final String backup) {
141
		try {
142
			final String logFile = backup.replaceFirst("data-", "report-").replace(".zip", ".log");
143
			(new File(backupDir + "/" + backup)).delete();
144
			(new File(backupDir + "/" + logFile)).delete();
145
			log.info("Backup deleted");
146
		} catch (final Exception e) {
147
			model.addAttribute("message", "failed: " + e.getMessage());
148
			log.info("Backup deletion failed: " + e.getMessage());
149
		}
150
	}
151

  
152
	/**
153
	 * List backups.
154
	 *
155
	 * @param model
156
	 *            mvc mode
157
	 */
158
	private void listBackups(final Model model, final String backupDir) {
159
		model.addAttribute("size", 0);
160
		
161
		final File dir = new File(backupDir);
162
		if (dir.exists() && dir.isDirectory()) {
163
			final FilenameFilter filter = new FilenameFilter() { // NOPMD
164
				@Override
165
				public boolean accept(final File dir, final String name) {
166
					return (name.startsWith("data-") && name.endsWith(".zip"));
167
				}
168
			};
169
			final File[] list = dir.listFiles(filter);
170
			if (list != null) {
171
				Arrays.sort(list, new Comparator<File>(){
172
				    @Override
173
					public int compare(final File f1, final File f2) {
174
				        return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
175
				    } });				
176
				
177
				model.addAttribute("size", list.length);
178
				model.addAttribute("backups", list);
179
			}
180
		}
181
	}
182

  
183
	/**
184
	 * get a backup Log.
185
	 *
186
	 * @throws IOException
187
	 *             could happen
188
	 * @param model
189
	 *            mvc model
190
	 * @param backup
191
	 *            the name of backup
192
	 * @throws
193
	 */
194
	@RequestMapping(value = "/inspector/backupLog.do")
195
	void backupLog(final Model model, 
196
			@RequestParam(value = "backup") final String backup,
197
			@RequestParam(value = "type") final String type) throws IOException {
198
		
199
		final String logFile = backup.replaceFirst("data-", "report-").replace(".zip", ".log");
200
		
201
		final FileReader freader = new FileReader(getBackupDir(type) + "/" + logFile);
202
		final StringWriter blog = new StringWriter();
203

  
204
		try {
205
			IOUtils.copy(freader, blog, BUFFER_SIZE);
206
		} finally {
207
			freader.close();
208
		}
209

  
210
		model.addAttribute("log", blog);
211
		model.addAttribute("backup", backup);
212
	}
213

  
214
	/**
215
	 * Download a backup.
216
	 *
217
	 * @param response
218
	 *            response
219
	 * @param backup
220
	 *            the name of backup
221
	 * @param out
222
	 *            response stream
223
	 * @throws IOException
224
	 *             could happen
225
	 */
226
	@RequestMapping(value = "/inspector/backupDownload.do")
227
	void downloadBackup(
228
			final HttpServletResponse response,
229
			@RequestParam(value = "backup", required = true) final String backup,
230
			@RequestParam(value = "type", required = true) final String type,
231
			final OutputStream out) throws IOException {
232
		response.setContentType("application/zip");
233

  
234
		final String endUserFilename = backup.replaceFirst("data", "dlib-backup-" + type);
235
		response.addHeader("Content-disposition", "attachment; filename=" + endUserFilename);
236

  
237
		final InputStream backupStream = new FileInputStream(getBackupDir(type) + "/" + backup);
238

  
239
		try {
240
			IOUtils.copy(backupStream, out);
241
		} finally {
242
			backupStream.close();
243
		}
244

  
245
		out.flush();
246
		out.close();
247
	}
248
	
249
	private String getBackupDir(final String type) {
250
		switch(BackupType.valueOf(type)) {
251
			case profile:
252
				return xmlDatabase.getBackupDir();
253
			case subscription:
254
				return issnServiceCore.getBackupDir();
255
			default:
256
				throw new IllegalArgumentException("wrong backup type parameter: " + type);
257
		}
258
	}	
259
}
modules/cnr-enabling-inspector/tags/cnr-enabling-inspector-2.0.2/src/main/java/eu/dnetlib/enabling/inspector/QueryController.java
1
package eu.dnetlib.enabling.inspector;
2

  
3
import java.util.*;
4
import java.util.stream.Collectors;
5
import java.util.stream.StreamSupport;
6

  
7
import javax.annotation.Resource;
8

  
9
import com.google.common.base.Function;
10
import com.google.common.collect.Iterators;
11
import com.google.common.collect.Lists;
12
import org.apache.commons.lang.StringEscapeUtils;
13
import org.apache.commons.logging.Log;
14
import org.apache.commons.logging.LogFactory;
15
import org.springframework.stereotype.Controller;
16
import org.springframework.ui.Model;
17
import org.springframework.web.bind.annotation.RequestMapping;
18
import org.springframework.web.bind.annotation.RequestParam;
19
import org.xmldb.api.base.XMLDBException;
20

  
21
import eu.dnetlib.xml.database.XMLDatabase;
22

  
23
/**
24
 * This controller offers a simple way to run arbitrary queries on the xmldb.
25
 *
26
 * @author marko
27
 *
28
 */
29
@Controller
30
public class QueryController extends AbstractInspectorController {
31

  
32
	/**
33
	 * logger.
34
	 */
35
	private static final Log log = LogFactory.getLog(QueryController.class); // NOPMD by marko on 11/24/08 5:02 PM
36

  
37
	/**
38
	 * xmldb.
39
	 */
40
	@Resource(name = "existDatabase")
41
	private transient XMLDatabase xmlDatabase;
42
	
43
	/**
44
	 * utility to parse resource ids and allows to navigate them.
45
	 */
46
	@Resource(name = "resourcelinkTool")
47
	private ResourceLinkTool linkTool;	
48

  
49
	/**
50
	 * run a query.
51
	 *
52
	 * @param model
53
	 *            mvc model
54
	 * @param query
55
	 *            query (optional)
56
	 * @throws
57
	 */
58
	@RequestMapping(value = "/inspector/query.do")
59
	void query(final Model model, @RequestParam(value = "query", required = false) final String query) {
60
		if (query != null) {
61
			log.info("running query: " + query);
62

  
63
			try {
64
				final Iterator<String> it = xmlDatabase.xquery(query);
65
				final List<String> res = StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, Spliterator.IMMUTABLE), false)
66
						.map(StringEscapeUtils::escapeHtml)
67
						.map(linkTool::linkfyToHtml)
68
						.collect(Collectors.toList());
69

  
70
				model.addAttribute("size", res.size());
71
				model.addAttribute("results", res);
72
			} catch (XMLDBException e) {
73
				model.addAttribute("message", "failed: " + e.getMessage());
74
			}
75
		}
76

  
77
		model.addAttribute("query", query);
78

  
79
	}
80

  
81
}
modules/cnr-enabling-inspector/tags/cnr-enabling-inspector-2.0.2/src/main/java/eu/dnetlib/enabling/inspector/ResourceTreeController.java
1
package eu.dnetlib.enabling.inspector;
2

  
3
import java.io.File;
4
import java.io.IOException;
5
import java.io.StringReader;
6
import java.util.ArrayList;
7
import java.util.Collection;
8
import java.util.Collections;
9
import java.util.HashMap;
10
import java.util.List;
11
import java.util.Map;
12

  
13
import javax.annotation.Resource;
14
import javax.servlet.ServletOutputStream;
15
import javax.servlet.http.HttpServletRequest;
16
import javax.servlet.http.HttpServletResponse;
17

  
18
import org.apache.commons.io.IOUtils;
19
import org.apache.commons.lang.StringEscapeUtils;
20
import org.apache.commons.logging.Log;
21
import org.apache.commons.logging.LogFactory;
22
import org.dom4j.DocumentException;
23
import org.springframework.stereotype.Controller;
24
import org.springframework.ui.Model;
25
import org.springframework.web.bind.annotation.RequestMapping;
26
import org.springframework.web.bind.annotation.RequestParam;
27
import org.xmldb.api.base.XMLDBException;
28

  
29
import com.google.common.collect.Lists;
30

  
31
import eu.dnetlib.miscutils.collections.MappedCollection;
32
import eu.dnetlib.miscutils.functional.UnaryFunction;
33
import eu.dnetlib.xml.database.XMLDatabase;
34

  
35
/**
36
 * test controller.
37
 *
38
 * @author marko
39
 */
40
@Controller
41
public class ResourceTreeController extends AbstractInspectorController { // NOPMD
42

  
43
	/**
44
	 * The list view uses this model to represent a collection
45
	 *
46
	 * @author marko
47
	 */
48
	public class CollectionModel {
49

  
50
		/**
51
		 * absolute path used to query the xmldb.
52
		 */
53
		private String path;
54
		/**
55
		 * relative path, used to construct the uri used by the view.
56
		 */
57
		private String rel;
58

  
59
		/**
60
		 * the collection name.
61
		 */
62
		private String name;
63

  
64
		public CollectionModel(final String path, final String rel, final String name) {
65
			super();
66
			this.path = path;
67
			this.rel = rel;
68
			this.name = name;
69
		}
70

  
71
		/**
72
		 * We want to be able to skip useless collections which have only one child collection etc etc.
73
		 * <p>
74
		 * <p>
75
		 * This method returns us the deepest path containing only one collection at each level
76
		 * </p>
77
		 *
78
		 * @return list of collection names to be displayed in one "row"
79
		 */
80
		public Collection<CollectionModel> getCollectionPath() {
81
			final ArrayList<CollectionModel> res = Lists.newArrayList(this);
82

  
83
			try {
84
				List<String> children = xmlDatabase.listChildCollections(path + '/' + name);
85
				if (children.size() == 1) {
86
					res.addAll(new CollectionModel(path + '/' + name, rel + '/' + name, children.get(0)).getCollectionPath());
87
				}
88

  
89
				return res;
90
			} catch (XMLDBException e) {
91
				return res;
92
			}
93
		}
94

  
95
		/**
96
		 * Uri is computed from relative base path.
97
		 *
98
		 * @return
99
		 */
100
		public String getUrl() {
101
			return (rel + '/' + getName());
102
		}
103

  
104
		public String getPath() {
105
			return path;
106
		}
107

  
108
		public void setPath(final String path) {
109
			this.path = path;
110
		}
111

  
112
		public String getName() {
113
			return name;
114
		}
115

  
116
		public void setName(final String name) {
117
			this.name = name;
118
		}
119

  
120
	}
121

  
122
	/**
123
	 * base index.do path.
124
	 */
125
	private static final String INDEX_DO = "/inspector/index.do";
126

  
127
	/**
128
	 * logger.
129
	 */
130
	private static final Log log = LogFactory.getLog(ResourceTreeController.class); // NOPMD by marko on 11/24/08 5:02 PM
131

  
132
	/**
133
	 * xml database.
134
	 */
135
	@Resource(name = "existDatabase")
136
	private transient XMLDatabase xmlDatabase;
137

  
138
	/**
139
	 * utility to parse resource ids and allows to navigate them.
140
	 */
141
	@Resource(name = "resourcelinkTool")
142
	private ResourceLinkTool linkTool;
143

  
144
	/**
145
	 * debug.
146
	 */
147
	public ResourceTreeController() {
148
		super();
149
		log.info("ResourceTreeController created");
150
	}
151

  
152
	/**
153
	 * handles relative paths.
154
	 *
155
	 * @return redirect
156
	 */
157
	// @RequestMapping("/inspector/")
158
	// String indexSlash() {
159
	// return "redirect:index.do/db/list";
160
	// }
161

  
162
	/**
163
	 * handles relative paths.
164
	 *
165
	 * @return redirect
166
	 */
167
	@RequestMapping("/inspector/index.do")
168
	String indexDo() {
169
		return "redirect:index.do/db/list";
170
	}
171

  
172
	/**
173
	 * index.
174
	 *
175
	 * @param model   model
176
	 * @param request http request
177
	 * @throws XMLDBException happens
178
	 */
179
	@RequestMapping("/inspector/index.do/**/list")
180
	String list(final Model model, final HttpServletRequest request) throws XMLDBException {
181
		final String path = request.getPathInfo().replace(INDEX_DO, "").replace("/list", "");
182

  
183
		log.debug("xml db: " + xmlDatabase);
184

  
185
		final Collection<String> children = xmlDatabase.listChildCollections(path);
186
		final Collection<String> files = xmlDatabase.list(path);
187

  
188
		Collections.sort((List<String>) children);
189
		Collections.sort((List<String>) files);
190

  
191
		UnaryFunction<CollectionModel, String> mapper = new UnaryFunction<CollectionModel, String>() {
192

  
193
			@Override
194
			public CollectionModel evaluate(final String name) {
195
				return new CollectionModel(path, ".", name);
196
			}
197
		};
198
		final Collection<CollectionModel> richChildren = Lists.newArrayList(new MappedCollection<CollectionModel, String>(children, mapper));
199

  
200
		model.addAttribute("path", path);
201
		model.addAttribute("pathComponents", extractPathComponents(path, ""));
202
		model.addAttribute("collections", richChildren);
203
		model.addAttribute("files", files);
204
		model.addAttribute("title", "Title");
205

  
206
		return "inspector/index";
207
	}
208

  
209
	/**
210
	 * return a list of pairs (name, relative url bases) for each path component.
211
	 *
212
	 * @param path slash separated path
213
	 * @param base prepend this to all paths
214
	 * @return list of path components
215
	 */
216
	private List<Map<String, String>> extractPathComponents(final String path, final String base) {
217
		final String[] rawPathComponents = path.split("/");
218
		final List<Map<String, String>> pathComponents = new ArrayList<Map<String, String>>();
219
		for (String rawPathComponent : rawPathComponents) {
220
			final Map<String, String> pathElement = new HashMap<String, String>(); // NOPMD
221
			pathElement.put("name", rawPathComponent);
222

  
223
			pathComponents.add(pathElement);
224
		}
225
		Collections.reverse(pathComponents);
226
		final StringBuffer current = new StringBuffer(base); // NOPMD
227
		for (Map<String, String> pathComponent : pathComponents) {
228
			pathComponent.put("url", current.toString());
229
			current.append("../");
230
		}
231
		Collections.reverse(pathComponents);
232
		return pathComponents;
233
	}
234

  
235
	/**
236
	 * show a file.
237
	 *
238
	 * @param model   model
239
	 * @param request request
240
	 * @return view name
241
	 * @throws XMLDBException happens
242
	 */
243
	@RequestMapping("/inspector/index.do/**/show")
244
	String show(final Model model, final HttpServletRequest request) throws XMLDBException {
245

  
246
		final String path = request.getPathInfo().replace(INDEX_DO, "").replace("/show", "");
247
		log.info("index: " + path);
248

  
249
		final File fileHelper = new File(path);
250
		final String collection = fileHelper.getParent();
251
		final String fileName = fileHelper.getName();
252
		final TouchUtils touch = new TouchUtils();
253

  
254
		String file = xmlDatabase.read(fileName, collection);
255
		if (file == null) {
256
			file = "no such file, click on edit to create";
257
		}
258

  
259
		file = touch.spanize(file);
260
		file = StringEscapeUtils.escapeHtml(file);
261
		file = touch.escape(file);
262
		// log.info("XML ESCAPED:" + file);
263

  
264
		model.addAttribute("file", linkTool.linkfyToHtml(file));
265
		model.addAttribute("pathComponents", extractPathComponents(collection, "../"));
266

  
267
		return "inspector/show";
268
	}
269

  
270
	@RequestMapping("/inspector/index.do/**/touch")
271
	public void updateDate(@RequestParam(value = "xpath", required = true) final String xpath,
272
			final HttpServletRequest request,
273
			final HttpServletResponse response) throws XMLDBException {
274

  
275
		final String path = request.getPathInfo().replace(INDEX_DO, "").replace("/touch", "");
276
		final File fileHelper = new File(path);
277
		final String collection = fileHelper.getParent();
278
		final String fileName = fileHelper.getName();
279
		final TouchUtils touch = new TouchUtils();
280

  
281
		String file = xmlDatabase.read(fileName, collection);
282
		if (file != null) {
283
			String updatedProfile;
284
			try {
285
				updatedProfile = touch.updateProfile(file, xpath);
286
				xmlDatabase.update(fileName, collection, updatedProfile);
287
			} catch (DocumentException e) {
288
				log.warn(e);
289
			}
290

  
291
		}
292
	}
293

  
294
	/**
295
	 * Show raw profile.
296
	 *
297
	 * @param request  servlet request
298
	 * @param response servlet response
299
	 * @throws XMLDBException could happen
300
	 * @throws IOException
301
	 */
302
	@RequestMapping("/inspector/index.do/**/raw")
303
	public void raw(final HttpServletRequest request, final HttpServletResponse response) throws XMLDBException, IOException {
304

  
305
		final String path = request.getPathInfo().replace(INDEX_DO, "").replace("/raw", "");
306
		// log.info("index: " + path);
307

  
308
		final File fileHelper = new File(path);
309
		final String collection = fileHelper.getParent();
310
		final String fileName = fileHelper.getName();
311

  
312
		String file = xmlDatabase.read(fileName, collection);
313
		if (file == null) {
314
			file = "no such file to show";
315
		}
316

  
317
		response.setContentType("text/xml");
318
		ServletOutputStream out = response.getOutputStream();
319
		IOUtils.copy(new StringReader(file), out);
320
		out.flush();
321
		out.close();
322
	}
323

  
324
	/**
325
	 * show a file editor.
326
	 *
327
	 * @param model   model
328
	 * @param request request
329
	 * @return view name
330
	 * @throws XMLDBException happens
331
	 */
332
	@RequestMapping("/inspector/index.do/**/edit")
333
	public String edit(final Model model, final HttpServletRequest request) throws XMLDBException {
334

  
335
		final String path = request.getPathInfo().replace(INDEX_DO, "").replace("/edit", "");
336

  
337
		final File fileHelper = new File(path);
338
		final String collection = fileHelper.getParent();
339
		final String fileName = fileHelper.getName();
340

  
341
		final String file = xmlDatabase.read(fileName, collection);
342
		if (file == null) {
343
			model.addAttribute("creating", "true");
344
		}
345

  
346
		model.addAttribute("file", StringEscapeUtils.escapeHtml(file));
347
		model.addAttribute("pathComponents", extractPathComponents(collection, "../"));
348

  
349
		return "inspector/edit";
350
	}
351

  
352
	/**
353
	 * update or create a file.
354
	 *
355
	 * @param model   model
356
	 * @param request request
357
	 * @return view name
358
	 * @throws XMLDBException happens
359
	 */
360
	@RequestMapping("/inspector/index.do/**/save")
361
	public String save(final Model model, final HttpServletRequest request) throws XMLDBException {
362

  
363
		final String path = request.getPathInfo().replace(INDEX_DO, "").replace("/save", "");
364

  
365
		final File fileHelper = new File(path);
366
		final String collection = fileHelper.getParent();
367
		final String fileName = fileHelper.getName();
368

  
369
		log.info("saving: " + path);
370
		final String source = request.getParameter("source");
371

  
372
		if ("true".equals(request.getParameter("creating"))) {
373
			xmlDatabase.create(fileName, collection, source);
374
		} else {
375
			xmlDatabase.update(fileName, collection, source);
376
		}
377

  
378
		return "redirect:show";
379
	}
380

  
381
	/**
382
	 * delete a file.
383
	 *
384
	 * @param model   model
385
	 * @param request request
386
	 * @return view name
387
	 * @throws XMLDBException happens
388
	 */
389
	@RequestMapping("/inspector/index.do/**/delete")
390
	public String delete(final Model model, final HttpServletRequest request) throws XMLDBException {
391

  
392
		final String path = request.getPathInfo().replace(INDEX_DO, "").replace("/delete", "");
393

  
394
		final File fileHelper = new File(path);
395
		final String collection = fileHelper.getParent();
396
		final String fileName = fileHelper.getName();
397

  
398
		log.info("deleting: " + path);
399
		xmlDatabase.remove(fileName, collection);
400

  
401
		return "redirect:../list";
402
	}
403

  
404
	/**
405
	 * delete a collection.
406
	 *
407
	 * @param model   model
408
	 * @param request request
409
	 * @return view name
410
	 * @throws XMLDBException happens
411
	 */
412
	@RequestMapping("/inspector/index.do/**/deleteCollection")
413
	public String deleteCollection(final Model model, final HttpServletRequest request) throws XMLDBException {
414

  
415
		final String path = request.getPathInfo().replace(INDEX_DO, "").replace("/deleteCollection", "");
416

  
417
		xmlDatabase.removeCollection(path);
418

  
419
		return "redirect:../list";
420
	}
421

  
422
	/**
423
	 * present a create form for new subcollection
424
	 *
425
	 * @param model   model
426
	 * @param request request
427
	 * @return view name
428
	 * @throws XMLDBException happens
429
	 */
430
	@RequestMapping("/inspector/index.do/**/createsubcoll")
431
	public String createSubCollection(final Model model, final HttpServletRequest request) throws XMLDBException {
432
		return "inspector/createsubcoll";
433
	}
434

  
435
	/**
436
	 * @param request request
437
	 * @return view name
438
	 * @throws XMLDBException happens
439
	 */
440
	@RequestMapping("/inspector/index.do/**/savesubcoll")
441
	public String saveSubCollection(final HttpServletRequest request, @RequestParam("collectionPath") final String collectionPath)
442
			throws XMLDBException {
443
		final String path = request.getPathInfo().replace(INDEX_DO, "").replace("/savesubcoll", "");
444
		String fullPath = path + "/" + collectionPath;
445
		log.info("Creating subcollection: " + fullPath);
446
		if (!xmlDatabase.collectionExists(fullPath)) {
447
			xmlDatabase.createCollection(fullPath);
448
		} else {
449
			log.info("Subcollection: " + fullPath + " already exists");
450
		}
451
		return "redirect:../list";
452
	}
453

  
454
	/**
455
	 * present a create form which will redirect to the edit form.
456
	 *
457
	 * @param model   model
458
	 * @param request request
459
	 * @return view name
460
	 * @throws XMLDBException happens
461
	 */
462
	@RequestMapping("/inspector/index.do/**/create")
463
	public String create(final Model model, final HttpServletRequest request) throws XMLDBException {
464
		return "inspector/create";
465
	}
466

  
467
	/**
468
	 * sample controller.
469
	 *
470
	 * @param model model
471
	 */
472
	@RequestMapping("/inspector/gadget.do")
473
	public void gadget(final Model model) {
474
		log.info("GADGED CALLED");
475

  
476
		model.addAttribute("items", new String[] { "one", "two", "three" });
477
	}
478

  
479
}
modules/cnr-enabling-inspector/tags/cnr-enabling-inspector-2.0.2/src/main/java/eu/dnetlib/enabling/inspector/GenericInfoController.java
1
package eu.dnetlib.enabling.inspector;
2

  
3
import java.lang.management.ManagementFactory;
4
import java.lang.management.RuntimeMXBean;
5
import java.util.LinkedHashMap;
6
import java.util.Map;
7

  
8
import javax.annotation.Resource;
9

  
10
import org.springframework.stereotype.Controller;
11
import org.springframework.ui.Model;
12
import org.springframework.web.bind.annotation.RequestMapping;
13

  
14
import eu.dnetlib.miscutils.datetime.DateUtils;
15
import eu.dnetlib.miscutils.datetime.HumanTime;
16

  
17
/**
18
 * This controller offers generic info about current node (ip, uptime, ...) 
19
 * 
20
 * @author michele
21
 *
22
 */
23
@Controller
24
public class GenericInfoController extends AbstractInspectorController {
25

  
26
	@Resource(name="containerInfo")
27
	Map<String,String> containerInfo;
28
	
29
	@RequestMapping(value = "/inspector/info.do")
30
	void query(final Model model) {
31
		RuntimeMXBean mxbean = ManagementFactory.getRuntimeMXBean();
32
		
33
		Map<String,String> sysinfo = new LinkedHashMap<String, String>();
34
		sysinfo.put("Uptime", HumanTime.exactly(mxbean.getUptime()));
35
		sysinfo.put("Start Time", DateUtils.calculate_ISO8601(mxbean.getStartTime()));
36

  
37
		sysinfo.put("JVM Name", mxbean.getVmName());
38
		sysinfo.put("JVM Vendor", mxbean.getVmVendor());
39
		sysinfo.put("JVM Version", mxbean.getVmVersion());
40
		sysinfo.put("JVM Spec Name", mxbean.getSpecName());
41
		sysinfo.put("JVM Spec Vendor", mxbean.getSpecVendor());
42
		sysinfo.put("JVM Spec Version", mxbean.getSpecVersion());
43

  
44
		sysinfo.put("Running JVM Name", mxbean.getName());
45
		sysinfo.put("Management Spec Version", mxbean.getManagementSpecVersion());
46
		
47
		sysinfo.put("Classpath", mxbean.getClassPath().replaceAll(":", " : "));
48
		sysinfo.put("Boot ClassPath", mxbean.getBootClassPath().replaceAll(":", " : "));
49
		sysinfo.put("Input arguments", mxbean.getInputArguments().toString());
50
		sysinfo.put("Library Path", mxbean.getLibraryPath().replaceAll(":", " : "));
51

  
52
		sysinfo.put("SystemProperties", mxbean.getSystemProperties().toString());
53
		
54
		
55
		model.addAttribute("containerInfo", containerInfo);
56
		model.addAttribute("sysInfo", sysinfo);
57
	}
58
	
59
}
60

  
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff