code
stringlengths
3
1.18M
language
stringclasses
1 value
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.crawler; import java.nio.charset.Charset; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.util.EntityUtils; import edu.uci.ics.crawler4j.parser.ParseData; import edu.uci.ics.crawler4j.url.WebURL; /** * This class contains the data for a fetched and parsed page. * * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class Page { /** * The URL of this page. */ protected WebURL url; /** * The content of this page in binary format. */ protected byte[] contentData; /** * The ContentType of this page. * For example: "text/html; charset=UTF-8" */ protected String contentType; /** * The encoding of the content. * For example: "gzip" */ protected String contentEncoding; /** * The charset of the content. * For example: "UTF-8" */ protected String contentCharset; /** * Headers which were present in the response of the * fetch request */ protected Header[] fetchResponseHeaders; /** * The parsed data populated by parsers */ protected ParseData parseData; public Page(WebURL url) { this.url = url; } public WebURL getWebURL() { return url; } public void setWebURL(WebURL url) { this.url = url; } /** * Loads the content of this page from a fetched * HttpEntity. */ public void load(HttpEntity entity) throws Exception { contentType = null; Header type = entity.getContentType(); if (type != null) { contentType = type.getValue(); } contentEncoding = null; Header encoding = entity.getContentEncoding(); if (encoding != null) { contentEncoding = encoding.getValue(); } Charset charset = ContentType.getOrDefault(entity).getCharset(); if (charset != null) { contentCharset = charset.displayName(); } contentData = EntityUtils.toByteArray(entity); } /** * Returns headers which were present in the response of the * fetch request */ public Header[] getFetchResponseHeaders() { return fetchResponseHeaders; } public void setFetchResponseHeaders(Header[] headers) { fetchResponseHeaders = headers; } /** * Returns the parsed data generated for this page by parsers */ public ParseData getParseData() { return parseData; } public void setParseData(ParseData parseData) { this.parseData = parseData; } /** * Returns the content of this page in binary format. */ public byte[] getContentData() { return contentData; } public void setContentData(byte[] contentData) { this.contentData = contentData; } /** * Returns the ContentType of this page. * For example: "text/html; charset=UTF-8" */ public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } /** * Returns the encoding of the content. * For example: "gzip" */ public String getContentEncoding() { return contentEncoding; } public void setContentEncoding(String contentEncoding) { this.contentEncoding = contentEncoding; } /** * Returns the charset of the content. * For example: "UTF-8" */ public String getContentCharset() { return contentCharset; } public void setContentCharset(String contentCharset) { this.contentCharset = contentCharset; } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.crawler; import com.sleepycat.je.Environment; import com.sleepycat.je.EnvironmentConfig; import edu.uci.ics.crawler4j.fetcher.PageFetcher; import edu.uci.ics.crawler4j.frontier.DocIDServer; import edu.uci.ics.crawler4j.frontier.Frontier; import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer; import edu.uci.ics.crawler4j.url.URLCanonicalizer; import edu.uci.ics.crawler4j.url.WebURL; import edu.uci.ics.crawler4j.util.IO; import org.apache.log4j.Logger; import java.io.File; import java.util.ArrayList; import java.util.List; /** * The controller that manages a crawling session. This class creates the * crawler threads and monitors their progress. * * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class CrawlController extends Configurable { static final Logger logger = Logger.getLogger(CrawlController.class.getName()); /** * The 'customData' object can be used for passing custom crawl-related * configurations to different components of the crawler. */ protected Object customData; /** * Once the crawling session finishes the controller collects the local data * of the crawler threads and stores them in this List. */ protected List<Object> crawlersLocalData = new ArrayList<>(); /** * Is the crawling of this session finished? */ protected boolean finished; /** * Is the crawling session set to 'shutdown'. Crawler threads monitor this * flag and when it is set they will no longer process new pages. */ protected boolean shuttingDown; protected PageFetcher pageFetcher; protected RobotstxtServer robotstxtServer; protected Frontier frontier; protected DocIDServer docIdServer; protected final Object waitingLock = new Object(); public CrawlController(CrawlConfig config, PageFetcher pageFetcher, RobotstxtServer robotstxtServer) throws Exception { super(config); config.validate(); File folder = new File(config.getCrawlStorageFolder()); if (!folder.exists()) { if (!folder.mkdirs()) { throw new Exception("Couldn't create this folder: " + folder.getAbsolutePath()); } } boolean resumable = config.isResumableCrawling(); EnvironmentConfig envConfig = new EnvironmentConfig(); envConfig.setAllowCreate(true); envConfig.setTransactional(resumable); envConfig.setLocking(resumable); File envHome = new File(config.getCrawlStorageFolder() + "/frontier"); if (!envHome.exists()) { if (!envHome.mkdir()) { throw new Exception("Couldn't create this folder: " + envHome.getAbsolutePath()); } } if (!resumable) { IO.deleteFolderContents(envHome); } Environment env = new Environment(envHome, envConfig); docIdServer = new DocIDServer(env, config); frontier = new Frontier(env, config, docIdServer); this.pageFetcher = pageFetcher; this.robotstxtServer = robotstxtServer; finished = false; shuttingDown = false; } /** * Start the crawling session and wait for it to finish. * * @param _c * the class that implements the logic for crawler threads * @param numberOfCrawlers * the number of concurrent threads that will be contributing in * this crawling session. */ public <T extends WebCrawler> void start(final Class<T> _c, final int numberOfCrawlers) { this.start(_c, numberOfCrawlers, true); } /** * Start the crawling session and return immediately. * * @param _c * the class that implements the logic for crawler threads * @param numberOfCrawlers * the number of concurrent threads that will be contributing in * this crawling session. */ public <T extends WebCrawler> void startNonBlocking(final Class<T> _c, final int numberOfCrawlers) { this.start(_c, numberOfCrawlers, false); } protected <T extends WebCrawler> void start(final Class<T> _c, final int numberOfCrawlers, boolean isBlocking) { try { finished = false; crawlersLocalData.clear(); final List<Thread> threads = new ArrayList<>(); final List<T> crawlers = new ArrayList<>(); for (int i = 1; i <= numberOfCrawlers; i++) { T crawler = _c.newInstance(); Thread thread = new Thread(crawler, "Crawler " + i); crawler.setThread(thread); crawler.init(i, this); thread.start(); crawlers.add(crawler); threads.add(thread); logger.info("Crawler " + i + " started."); } final CrawlController controller = this; Thread monitorThread = new Thread(new Runnable() { @Override public void run() { try { synchronized (waitingLock) { while (true) { sleep(10); boolean someoneIsWorking = false; for (int i = 0; i < threads.size(); i++) { Thread thread = threads.get(i); if (!thread.isAlive()) { if (!shuttingDown) { logger.info("Thread " + i + " was dead, I'll recreate it."); T crawler = _c.newInstance(); thread = new Thread(crawler, "Crawler " + (i + 1)); threads.remove(i); threads.add(i, thread); crawler.setThread(thread); crawler.init(i + 1, controller); thread.start(); crawlers.remove(i); crawlers.add(i, crawler); } } else if (crawlers.get(i).isNotWaitingForNewURLs()) { someoneIsWorking = true; } } if (!someoneIsWorking) { // Make sure again that none of the threads // are // alive. logger.info("It looks like no thread is working, waiting for 10 seconds to make sure..."); sleep(10); someoneIsWorking = false; for (int i = 0; i < threads.size(); i++) { Thread thread = threads.get(i); if (thread.isAlive() && crawlers.get(i).isNotWaitingForNewURLs()) { someoneIsWorking = true; } } if (!someoneIsWorking) { if (!shuttingDown) { long queueLength = frontier.getQueueLength(); if (queueLength > 0) { continue; } logger.info("No thread is working and no more URLs are in queue waiting for another 10 seconds to make sure..."); sleep(10); queueLength = frontier.getQueueLength(); if (queueLength > 0) { continue; } } logger.info("All of the crawlers are stopped. Finishing the process..."); // At this step, frontier notifies the // threads that were // waiting for new URLs and they should // stop frontier.finish(); for (T crawler : crawlers) { crawler.onBeforeExit(); crawlersLocalData.add(crawler.getMyLocalData()); } logger.info("Waiting for 10 seconds before final clean up..."); sleep(10); frontier.close(); docIdServer.close(); pageFetcher.shutDown(); finished = true; waitingLock.notifyAll(); return; } } } } } catch (Exception e) { e.printStackTrace(); } } }); monitorThread.start(); if (isBlocking) { waitUntilFinish(); } } catch (Exception e) { e.printStackTrace(); } } /** * Wait until this crawling session finishes. */ public void waitUntilFinish() { while (!finished) { synchronized (waitingLock) { if (finished) { return; } try { waitingLock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } /** * Once the crawling session finishes the controller collects the local data * of the crawler threads and stores them in a List. This function returns * the reference to this list. */ public List<Object> getCrawlersLocalData() { return crawlersLocalData; } protected static void sleep(int seconds) { try { Thread.sleep(seconds * 1000); } catch (Exception ignored) { // Do nothing } } /** * Adds a new seed URL. A seed URL is a URL that is fetched by the crawler * to extract new URLs in it and follow them for crawling. * * @param pageUrl * the URL of the seed */ public void addSeed(String pageUrl) { addSeed(pageUrl, -1); } /** * Adds a new seed URL. A seed URL is a URL that is fetched by the crawler * to extract new URLs in it and follow them for crawling. You can also * specify a specific document id to be assigned to this seed URL. This * document id needs to be unique. Also, note that if you add three seeds * with document ids 1,2, and 7. Then the next URL that is found during the * crawl will get a doc id of 8. Also you need to ensure to add seeds in * increasing order of document ids. * * Specifying doc ids is mainly useful when you have had a previous crawl * and have stored the results and want to start a new crawl with seeds * which get the same document ids as the previous crawl. * * @param pageUrl * the URL of the seed * @param docId * the document id that you want to be assigned to this seed URL. * */ public void addSeed(String pageUrl, int docId) { String canonicalUrl = URLCanonicalizer.getCanonicalURL(pageUrl); if (canonicalUrl == null) { logger.error("Invalid seed URL: " + pageUrl); return; } if (docId < 0) { docId = docIdServer.getDocId(canonicalUrl); if (docId > 0) { // This URL is already seen. return; } docId = docIdServer.getNewDocID(canonicalUrl); } else { try { docIdServer.addUrlAndDocId(canonicalUrl, docId); } catch (Exception e) { logger.error("Could not add seed: " + e.getMessage()); } } WebURL webUrl = new WebURL(); webUrl.setURL(canonicalUrl); webUrl.setDocid(docId); webUrl.setDepth((short) 0); if (!robotstxtServer.allows(webUrl)) { logger.info("Robots.txt does not allow this seed: " + pageUrl); } else { frontier.schedule(webUrl); } } /** * This function can called to assign a specific document id to a url. This * feature is useful when you have had a previous crawl and have stored the * Urls and their associated document ids and want to have a new crawl which * is aware of the previously seen Urls and won't re-crawl them. * * Note that if you add three seen Urls with document ids 1,2, and 7. Then * the next URL that is found during the crawl will get a doc id of 8. Also * you need to ensure to add seen Urls in increasing order of document ids. * * @param url * the URL of the page * @param docId * the document id that you want to be assigned to this URL. * */ public void addSeenUrl(String url, int docId) { String canonicalUrl = URLCanonicalizer.getCanonicalURL(url); if (canonicalUrl == null) { logger.error("Invalid Url: " + url); return; } try { docIdServer.addUrlAndDocId(canonicalUrl, docId); } catch (Exception e) { logger.error("Could not add seen url: " + e.getMessage()); } } public PageFetcher getPageFetcher() { return pageFetcher; } public void setPageFetcher(PageFetcher pageFetcher) { this.pageFetcher = pageFetcher; } public RobotstxtServer getRobotstxtServer() { return robotstxtServer; } public void setRobotstxtServer(RobotstxtServer robotstxtServer) { this.robotstxtServer = robotstxtServer; } public Frontier getFrontier() { return frontier; } public void setFrontier(Frontier frontier) { this.frontier = frontier; } public DocIDServer getDocIdServer() { return docIdServer; } public void setDocIdServer(DocIDServer docIdServer) { this.docIdServer = docIdServer; } public Object getCustomData() { return customData; } public void setCustomData(Object customData) { this.customData = customData; } public boolean isFinished() { return this.finished; } public boolean isShuttingDown() { return shuttingDown; } /** * Set the current crawling session set to 'shutdown'. Crawler threads * monitor the shutdown flag and when it is set to true, they will no longer * process new pages. */ public void shutdown() { logger.info("Shutting down..."); this.shuttingDown = true; frontier.finish(); } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.crawler; /** * Several core components of crawler4j extend this class * to make them configurable. * * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public abstract class Configurable { protected CrawlConfig config; protected Configurable(CrawlConfig config) { this.config = config; } public CrawlConfig getConfig() { return config; } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.crawler; public class CrawlConfig { /** * The folder which will be used by crawler for storing the intermediate * crawl data. The content of this folder should not be modified manually. */ private String crawlStorageFolder; /** * If this feature is enabled, you would be able to resume a previously * stopped/crashed crawl. However, it makes crawling slightly slower */ private boolean resumableCrawling = false; /** * Maximum depth of crawling For unlimited depth this parameter should be * set to -1 */ private int maxDepthOfCrawling = -1; /** * Maximum number of pages to fetch For unlimited number of pages, this * parameter should be set to -1 */ private int maxPagesToFetch = -1; /** * user-agent string that is used for representing your crawler to web * servers. See http://en.wikipedia.org/wiki/User_agent for more details */ private String userAgentString = "crawler4j (http://code.google.com/p/crawler4j/)"; /** * Politeness delay in milliseconds (delay between sending two requests to * the same host). */ private int politenessDelay = 200; /** * Should we also crawl https pages? */ private boolean includeHttpsPages = false; /** * Should we fetch binary content such as images, audio, ...? */ private boolean includeBinaryContentInCrawling = false; /** * Maximum Connections per host */ private int maxConnectionsPerHost = 100; /** * Maximum total connections */ private int maxTotalConnections = 100; /** * Socket timeout in milliseconds */ private int socketTimeout = 20000; /** * Connection timeout in milliseconds */ private int connectionTimeout = 30000; /** * Max number of outgoing links which are processed from a page */ private int maxOutgoingLinksToFollow = 5000; /** * Max allowed size of a page. Pages larger than this size will not be * fetched. */ private int maxDownloadSize = 1048576; /** * Should we follow redirects? */ private boolean followRedirects = true; /** * If crawler should run behind a proxy, this parameter can be used for * specifying the proxy host. */ private String proxyHost = null; /** * If crawler should run behind a proxy, this parameter can be used for * specifying the proxy port. */ private int proxyPort = 80; /** * If crawler should run behind a proxy and user/pass is needed for * authentication in proxy, this parameter can be used for specifying the * username. */ private String proxyUsername = null; /** * If crawler should run behind a proxy and user/pass is needed for * authentication in proxy, this parameter can be used for specifying the * password. */ private String proxyPassword = null; public CrawlConfig() { } /** * Validates the configs specified by this instance. * * @throws Exception */ public void validate() throws Exception { if (crawlStorageFolder == null) { throw new Exception("Crawl storage folder is not set in the CrawlConfig."); } if (politenessDelay < 0) { throw new Exception("Invalid value for politeness delay: " + politenessDelay); } if (maxDepthOfCrawling < -1) { throw new Exception("Maximum crawl depth should be either a positive number or -1 for unlimited depth."); } if (maxDepthOfCrawling > Short.MAX_VALUE) { throw new Exception("Maximum value for crawl depth is " + Short.MAX_VALUE); } } public String getCrawlStorageFolder() { return crawlStorageFolder; } /** * The folder which will be used by crawler for storing the intermediate * crawl data. The content of this folder should not be modified manually. */ public void setCrawlStorageFolder(String crawlStorageFolder) { this.crawlStorageFolder = crawlStorageFolder; } public boolean isResumableCrawling() { return resumableCrawling; } /** * If this feature is enabled, you would be able to resume a previously * stopped/crashed crawl. However, it makes crawling slightly slower */ public void setResumableCrawling(boolean resumableCrawling) { this.resumableCrawling = resumableCrawling; } public int getMaxDepthOfCrawling() { return maxDepthOfCrawling; } /** * Maximum depth of crawling For unlimited depth this parameter should be * set to -1 */ public void setMaxDepthOfCrawling(int maxDepthOfCrawling) { this.maxDepthOfCrawling = maxDepthOfCrawling; } public int getMaxPagesToFetch() { return maxPagesToFetch; } /** * Maximum number of pages to fetch For unlimited number of pages, this * parameter should be set to -1 */ public void setMaxPagesToFetch(int maxPagesToFetch) { this.maxPagesToFetch = maxPagesToFetch; } public String getUserAgentString() { return userAgentString; } /** * user-agent string that is used for representing your crawler to web * servers. See http://en.wikipedia.org/wiki/User_agent for more details */ public void setUserAgentString(String userAgentString) { this.userAgentString = userAgentString; } public int getPolitenessDelay() { return politenessDelay; } /** * Politeness delay in milliseconds (delay between sending two requests to * the same host). * * @param politenessDelay * the delay in milliseconds. */ public void setPolitenessDelay(int politenessDelay) { this.politenessDelay = politenessDelay; } public boolean isIncludeHttpsPages() { return includeHttpsPages; } /** * Should we also crawl https pages? */ public void setIncludeHttpsPages(boolean includeHttpsPages) { this.includeHttpsPages = includeHttpsPages; } public boolean isIncludeBinaryContentInCrawling() { return includeBinaryContentInCrawling; } /** * Should we fetch binary content such as images, audio, ...? */ public void setIncludeBinaryContentInCrawling(boolean includeBinaryContentInCrawling) { this.includeBinaryContentInCrawling = includeBinaryContentInCrawling; } public int getMaxConnectionsPerHost() { return maxConnectionsPerHost; } /** * Maximum Connections per host */ public void setMaxConnectionsPerHost(int maxConnectionsPerHost) { this.maxConnectionsPerHost = maxConnectionsPerHost; } public int getMaxTotalConnections() { return maxTotalConnections; } /** * Maximum total connections */ public void setMaxTotalConnections(int maxTotalConnections) { this.maxTotalConnections = maxTotalConnections; } public int getSocketTimeout() { return socketTimeout; } /** * Socket timeout in milliseconds */ public void setSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; } public int getConnectionTimeout() { return connectionTimeout; } /** * Connection timeout in milliseconds */ public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } public int getMaxOutgoingLinksToFollow() { return maxOutgoingLinksToFollow; } /** * Max number of outgoing links which are processed from a page */ public void setMaxOutgoingLinksToFollow(int maxOutgoingLinksToFollow) { this.maxOutgoingLinksToFollow = maxOutgoingLinksToFollow; } public int getMaxDownloadSize() { return maxDownloadSize; } /** * Max allowed size of a page. Pages larger than this size will not be * fetched. */ public void setMaxDownloadSize(int maxDownloadSize) { this.maxDownloadSize = maxDownloadSize; } public boolean isFollowRedirects() { return followRedirects; } /** * Should we follow redirects? */ public void setFollowRedirects(boolean followRedirects) { this.followRedirects = followRedirects; } public String getProxyHost() { return proxyHost; } /** * If crawler should run behind a proxy, this parameter can be used for * specifying the proxy host. */ public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public int getProxyPort() { return proxyPort; } /** * If crawler should run behind a proxy, this parameter can be used for * specifying the proxy port. */ public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; } public String getProxyUsername() { return proxyUsername; } /** * If crawler should run behind a proxy and user/pass is needed for * authentication in proxy, this parameter can be used for specifying the * username. */ public void setProxyUsername(String proxyUsername) { this.proxyUsername = proxyUsername; } public String getProxyPassword() { return proxyPassword; } /** * If crawler should run behind a proxy and user/pass is needed for * authentication in proxy, this parameter can be used for specifying the * password. */ public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Crawl storage folder: " + getCrawlStorageFolder() + "\n"); sb.append("Resumable crawling: " + isResumableCrawling() + "\n"); sb.append("Max depth of crawl: " + getMaxDepthOfCrawling() + "\n"); sb.append("Max pages to fetch: " + getMaxPagesToFetch() + "\n"); sb.append("User agent string: " + getUserAgentString() + "\n"); sb.append("Include https pages: " + isIncludeHttpsPages() + "\n"); sb.append("Include binary content: " + isIncludeBinaryContentInCrawling() + "\n"); sb.append("Max connections per host: " + getMaxConnectionsPerHost() + "\n"); sb.append("Max total connections: " + getMaxTotalConnections() + "\n"); sb.append("Socket timeout: " + getSocketTimeout() + "\n"); sb.append("Max total connections: " + getMaxTotalConnections() + "\n"); sb.append("Max outgoing links to follow: " + getMaxOutgoingLinksToFollow() + "\n"); sb.append("Max download size: " + getMaxDownloadSize() + "\n"); sb.append("Should follow redirects?: " + isFollowRedirects() + "\n"); sb.append("Proxy host: " + getProxyHost() + "\n"); sb.append("Proxy port: " + getProxyPort() + "\n"); sb.append("Proxy username: " + getProxyUsername() + "\n"); sb.append("Proxy password: " + getProxyPassword() + "\n"); return sb.toString(); } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.crawler; import edu.uci.ics.crawler4j.fetcher.PageFetchResult; import edu.uci.ics.crawler4j.fetcher.CustomFetchStatus; import edu.uci.ics.crawler4j.fetcher.PageFetcher; import edu.uci.ics.crawler4j.frontier.DocIDServer; import edu.uci.ics.crawler4j.frontier.Frontier; import edu.uci.ics.crawler4j.parser.HtmlParseData; import edu.uci.ics.crawler4j.parser.ParseData; import edu.uci.ics.crawler4j.parser.Parser; import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer; import edu.uci.ics.crawler4j.url.WebURL; import org.apache.http.HttpStatus; import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.List; /** * WebCrawler class in the Runnable class that is executed by each crawler * thread. * * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class WebCrawler implements Runnable { protected static final Logger logger = Logger.getLogger(WebCrawler.class.getName()); /** * The id associated to the crawler thread running this instance */ protected int myId; /** * The controller instance that has created this crawler thread. This * reference to the controller can be used for getting configurations of the * current crawl or adding new seeds during runtime. */ protected CrawlController myController; /** * The thread within which this crawler instance is running. */ private Thread myThread; /** * The parser that is used by this crawler instance to parse the content of * the fetched pages. */ private Parser parser; /** * The fetcher that is used by this crawler instance to fetch the content of * pages from the web. */ private PageFetcher pageFetcher; /** * The RobotstxtServer instance that is used by this crawler instance to * determine whether the crawler is allowed to crawl the content of each * page. */ private RobotstxtServer robotstxtServer; /** * The DocIDServer that is used by this crawler instance to map each URL to * a unique docid. */ private DocIDServer docIdServer; /** * The Frontier object that manages the crawl queue. */ private Frontier frontier; /** * Is the current crawler instance waiting for new URLs? This field is * mainly used by the controller to detect whether all of the crawler * instances are waiting for new URLs and therefore there is no more work * and crawling can be stopped. */ private boolean isWaitingForNewURLs; /** * Initializes the current instance of the crawler * * @param id * the id of this crawler instance * @param crawlController * the controller that manages this crawling session */ public void init(int id, CrawlController crawlController) { this.myId = id; this.pageFetcher = crawlController.getPageFetcher(); this.robotstxtServer = crawlController.getRobotstxtServer(); this.docIdServer = crawlController.getDocIdServer(); this.frontier = crawlController.getFrontier(); this.parser = new Parser(crawlController.getConfig()); this.myController = crawlController; this.isWaitingForNewURLs = false; } /** * Get the id of the current crawler instance * * @return the id of the current crawler instance */ public int getMyId() { return myId; } public CrawlController getMyController() { return myController; } /** * This function is called just before starting the crawl by this crawler * instance. It can be used for setting up the data structures or * initializations needed by this crawler instance. */ public void onStart() { // Do nothing by default // Sub-classed can override this to add their custom functionality } /** * This function is called just before the termination of the current * crawler instance. It can be used for persisting in-memory data or other * finalization tasks. */ public void onBeforeExit() { // Do nothing by default // Sub-classed can override this to add their custom functionality } /** * This function is called once the header of a page is fetched. It can be * overwritten by sub-classes to perform custom logic for different status * codes. For example, 404 pages can be logged, etc. * * @param webUrl * @param statusCode * @param statusDescription */ protected void handlePageStatusCode(WebURL webUrl, int statusCode, String statusDescription) { // Do nothing by default // Sub-classed can override this to add their custom functionality } /** * This function is called if the content of a url could not be fetched. * * @param webUrl */ protected void onContentFetchError(WebURL webUrl) { // Do nothing by default // Sub-classed can override this to add their custom functionality } /** * This function is called if there has been an error in parsing the * content. * * @param webUrl */ protected void onParseError(WebURL webUrl) { // Do nothing by default // Sub-classed can override this to add their custom functionality } /** * The CrawlController instance that has created this crawler instance will * call this function just before terminating this crawler thread. Classes * that extend WebCrawler can override this function to pass their local * data to their controller. The controller then puts these local data in a * List that can then be used for processing the local data of crawlers (if * needed). */ public Object getMyLocalData() { return null; } public void run() { onStart(); while (true) { List<WebURL> assignedURLs = new ArrayList<>(50); isWaitingForNewURLs = true; frontier.getNextURLs(50, assignedURLs); isWaitingForNewURLs = false; if (assignedURLs.size() == 0) { if (frontier.isFinished()) { return; } try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } else { for (WebURL curURL : assignedURLs) { if (curURL != null) { processPage(curURL); frontier.setProcessed(curURL); } if (myController.isShuttingDown()) { logger.info("Exiting because of controller shutdown."); return; } } } } } /** * Classes that extends WebCrawler can overwrite this function to tell the * crawler whether the given url should be crawled or not. The following * implementation indicates that all urls should be included in the crawl. * * @param url * the url which we are interested to know whether it should be * included in the crawl or not. * @return if the url should be included in the crawl it returns true, * otherwise false is returned. */ public boolean shouldVisit(WebURL url) { return true; } /** * Classes that extends WebCrawler can overwrite this function to process * the content of the fetched and parsed page. * * @param page * the page object that is just fetched and parsed. */ public void visit(Page page) { // Do nothing by default // Sub-classed can override this to add their custom functionality } private void processPage(WebURL curURL) { if (curURL == null) { return; } PageFetchResult fetchResult = null; try { fetchResult = pageFetcher.fetchHeader(curURL); int statusCode = fetchResult.getStatusCode(); handlePageStatusCode(curURL, statusCode, CustomFetchStatus.getStatusDescription(statusCode)); if (statusCode != HttpStatus.SC_OK) { if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { if (myController.getConfig().isFollowRedirects()) { String movedToUrl = fetchResult.getMovedToUrl(); if (movedToUrl == null) { return; } int newDocId = docIdServer.getDocId(movedToUrl); if (newDocId > 0) { // Redirect page is already seen return; } WebURL webURL = new WebURL(); webURL.setURL(movedToUrl); webURL.setParentDocid(curURL.getParentDocid()); webURL.setParentUrl(curURL.getParentUrl()); webURL.setDepth(curURL.getDepth()); webURL.setDocid(-1); webURL.setAnchor(curURL.getAnchor()); if (shouldVisit(webURL) && robotstxtServer.allows(webURL)) { webURL.setDocid(docIdServer.getNewDocID(movedToUrl)); frontier.schedule(webURL); } } } else if (fetchResult.getStatusCode() == CustomFetchStatus.PageTooBig) { logger.info("Skipping a page which was bigger than max allowed size: " + curURL.getURL()); } return; } if (!curURL.getURL().equals(fetchResult.getFetchedUrl())) { if (docIdServer.isSeenBefore(fetchResult.getFetchedUrl())) { // Redirect page is already seen return; } curURL.setURL(fetchResult.getFetchedUrl()); curURL.setDocid(docIdServer.getNewDocID(fetchResult.getFetchedUrl())); } Page page = new Page(curURL); int docid = curURL.getDocid(); if (!fetchResult.fetchContent(page)) { onContentFetchError(curURL); return; } if (!parser.parse(page, curURL.getURL())) { onParseError(curURL); return; } ParseData parseData = page.getParseData(); if (parseData instanceof HtmlParseData) { HtmlParseData htmlParseData = (HtmlParseData) parseData; List<WebURL> toSchedule = new ArrayList<>(); int maxCrawlDepth = myController.getConfig().getMaxDepthOfCrawling(); for (WebURL webURL : htmlParseData.getOutgoingUrls()) { webURL.setParentDocid(docid); webURL.setParentUrl(curURL.getURL()); int newdocid = docIdServer.getDocId(webURL.getURL()); if (newdocid > 0) { // This is not the first time that this Url is // visited. So, we set the depth to a negative // number. webURL.setDepth((short) -1); webURL.setDocid(newdocid); } else { webURL.setDocid(-1); webURL.setDepth((short) (curURL.getDepth() + 1)); if (maxCrawlDepth == -1 || curURL.getDepth() < maxCrawlDepth) { if (shouldVisit(webURL) && robotstxtServer.allows(webURL)) { webURL.setDocid(docIdServer.getNewDocID(webURL.getURL())); toSchedule.add(webURL); } } } } frontier.scheduleAll(toSchedule); } try { visit(page); } catch (Exception e) { logger.error("Exception while running the visit method. Message: '" + e.getMessage() + "' at " + e.getStackTrace()[0]); } } catch (Exception e) { logger.error(e.getMessage() + ", while processing: " + curURL.getURL()); } finally { if (fetchResult != null) { fetchResult.discardContentIfNotConsumed(); } } } public Thread getThread() { return myThread; } public void setThread(Thread myThread) { this.myThread = myThread; } public boolean isNotWaitingForNewURLs() { return !isWaitingForNewURLs; } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.util; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class Util { public static byte[] long2ByteArray(long l) { byte[] array = new byte[8]; int i, shift; for(i = 0, shift = 56; i < 8; i++, shift -= 8) { array[i] = (byte)(0xFF & (l >> shift)); } return array; } public static byte[] int2ByteArray(int value) { byte[] b = new byte[4]; for (int i = 0; i < 4; i++) { int offset = (3 - i) * 8; b[i] = (byte) ((value >>> offset) & 0xFF); } return b; } public static void putIntInByteArray(int value, byte[] buf, int offset) { for (int i = 0; i < 4; i++) { int valueOffset = (3 - i) * 8; buf[offset + i] = (byte) ((value >>> valueOffset) & 0xFF); } } public static int byteArray2Int(byte[] b) { int value = 0; for (int i = 0; i < 4; i++) { int shift = (4 - 1 - i) * 8; value += (b[i] & 0x000000FF) << shift; } return value; } public static long byteArray2Long(byte[] b) { int value = 0; for (int i = 0; i < 8; i++) { int shift = (8 - 1 - i) * 8; value += (b[i] & 0x000000FF) << shift; } return value; } public static boolean hasBinaryContent(String contentType) { if (contentType != null) { String typeStr = contentType.toLowerCase(); if (typeStr.contains("image") || typeStr.contains("audio") || typeStr.contains("video") || typeStr.contains("application")) { return true; } } return false; } public static boolean hasPlainTextContent(String contentType) { if (contentType != null) { String typeStr = contentType.toLowerCase(); if (typeStr.contains("text/plain")) { return true; } } return false; } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.util; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class IO { public static boolean deleteFolder(File folder) { return deleteFolderContents(folder) && folder.delete(); } public static boolean deleteFolderContents(File folder) { System.out.println("Deleting content of: " + folder.getAbsolutePath()); File[] files = folder.listFiles(); for (File file : files) { if (file.isFile()) { if (!file.delete()) { return false; } } else { if (!deleteFolder(file)) { return false; } } } return true; } public static void writeBytesToFile(byte[] bytes, String destination) { try { FileChannel fc = new FileOutputStream(destination).getChannel(); fc.write(ByteBuffer.wrap(bytes)); fc.close(); } catch (Exception e) { e.printStackTrace(); } } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.robotstxt; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.http.HttpStatus; import edu.uci.ics.crawler4j.crawler.Page; import edu.uci.ics.crawler4j.fetcher.PageFetchResult; import edu.uci.ics.crawler4j.fetcher.PageFetcher; import edu.uci.ics.crawler4j.url.WebURL; import edu.uci.ics.crawler4j.util.Util; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class RobotstxtServer { protected RobotstxtConfig config; protected final Map<String, HostDirectives> host2directivesCache = new HashMap<>(); protected PageFetcher pageFetcher; public RobotstxtServer(RobotstxtConfig config, PageFetcher pageFetcher) { this.config = config; this.pageFetcher = pageFetcher; } private static String getHost(URL url) { return url.getHost().toLowerCase(); } public boolean allows(WebURL webURL) { if (!config.isEnabled()) { return true; } try { URL url = new URL(webURL.getURL()); String host = getHost(url); String path = url.getPath(); HostDirectives directives = host2directivesCache.get(host); if (directives != null && directives.needsRefetch()) { synchronized (host2directivesCache) { host2directivesCache.remove(host); directives = null; } } if (directives == null) { directives = fetchDirectives(url); } return directives.allows(path); } catch (MalformedURLException e) { e.printStackTrace(); } return true; } private HostDirectives fetchDirectives(URL url) { WebURL robotsTxtUrl = new WebURL(); String host = getHost(url); String port = (url.getPort() == url.getDefaultPort() || url.getPort() == -1) ? "" : ":" + url.getPort(); robotsTxtUrl.setURL("http://" + host + port + "/robots.txt"); HostDirectives directives = null; PageFetchResult fetchResult = null; try { fetchResult = pageFetcher.fetchHeader(robotsTxtUrl); if (fetchResult.getStatusCode() == HttpStatus.SC_OK) { Page page = new Page(robotsTxtUrl); fetchResult.fetchContent(page); if (Util.hasPlainTextContent(page.getContentType())) { try { String content; if (page.getContentCharset() == null) { content = new String(page.getContentData()); } else { content = new String(page.getContentData(), page.getContentCharset()); } directives = RobotstxtParser.parse(content, config.getUserAgentName()); } catch (Exception e) { e.printStackTrace(); } } } } finally { if (fetchResult != null) { fetchResult.discardContentIfNotConsumed(); } } if (directives == null) { // We still need to have this object to keep track of the time we // fetched it directives = new HostDirectives(); } synchronized (host2directivesCache) { if (host2directivesCache.size() == config.getCacheSize()) { String minHost = null; long minAccessTime = Long.MAX_VALUE; for (Entry<String, HostDirectives> entry : host2directivesCache.entrySet()) { if (entry.getValue().getLastAccessTime() < minAccessTime) { minAccessTime = entry.getValue().getLastAccessTime(); minHost = entry.getKey(); } } host2directivesCache.remove(minHost); } host2directivesCache.put(host, directives); } return directives; } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.robotstxt; import java.util.StringTokenizer; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class RobotstxtParser { private static final String PATTERNS_USERAGENT = "(?i)^User-agent:.*"; private static final String PATTERNS_DISALLOW = "(?i)Disallow:.*"; private static final String PATTERNS_ALLOW = "(?i)Allow:.*"; private static final int PATTERNS_USERAGENT_LENGTH = 11; private static final int PATTERNS_DISALLOW_LENGTH = 9; private static final int PATTERNS_ALLOW_LENGTH = 6; public static HostDirectives parse(String content, String myUserAgent) { HostDirectives directives = null; boolean inMatchingUserAgent = false; StringTokenizer st = new StringTokenizer(content, "\n"); while (st.hasMoreTokens()) { String line = st.nextToken(); int commentIndex = line.indexOf("#"); if (commentIndex > -1) { line = line.substring(0, commentIndex); } // remove any html markup line = line.replaceAll("<[^>]+>", ""); line = line.trim(); if (line.length() == 0) { continue; } if (line.matches(PATTERNS_USERAGENT)) { String ua = line.substring(PATTERNS_USERAGENT_LENGTH).trim().toLowerCase(); if (ua.equals("*") || ua.contains(myUserAgent)) { inMatchingUserAgent = true; } else { inMatchingUserAgent = false; } } else if (line.matches(PATTERNS_DISALLOW)) { if (!inMatchingUserAgent) { continue; } String path = line.substring(PATTERNS_DISALLOW_LENGTH).trim(); if (path.endsWith("*")) { path = path.substring(0, path.length() - 1); } path = path.trim(); if (path.length() > 0) { if (directives == null) { directives = new HostDirectives(); } directives.addDisallow(path); } } else if (line.matches(PATTERNS_ALLOW)) { if (!inMatchingUserAgent) { continue; } String path = line.substring(PATTERNS_ALLOW_LENGTH).trim(); if (path.endsWith("*")) { path = path.substring(0, path.length() - 1); } path = path.trim(); if (directives == null) { directives = new HostDirectives(); } directives.addAllow(path); } } return directives; } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.robotstxt; import java.util.SortedSet; import java.util.TreeSet; public class RuleSet extends TreeSet<String> { private static final long serialVersionUID = 1L; @Override public boolean add(String str) { SortedSet<String> sub = headSet(str); if (!sub.isEmpty() && str.startsWith(sub.last())) { // no need to add; prefix is already present return false; } boolean retVal = super.add(str); sub = tailSet(str + "\0"); while (!sub.isEmpty() && sub.first().startsWith(str)) { // remove redundant entries sub.remove(sub.first()); } return retVal; } public boolean containsPrefixOf(String s) { SortedSet<String> sub = headSet(s); // because redundant prefixes have been eliminated, // only a test against last item in headSet is necessary if (!sub.isEmpty() && s.startsWith(sub.last())) { return true; // prefix substring exists } // might still exist exactly (headSet does not contain boundary) return contains(s); } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.robotstxt; public class RobotstxtConfig { /** * Should the crawler obey Robots.txt protocol? More info on Robots.txt is * available at http://www.robotstxt.org/ */ private boolean enabled = true; /** * user-agent name that will be used to determine whether some servers have * specific rules for this agent name. */ private String userAgentName = "crawler4j"; /** * The maximum number of hosts for which their robots.txt is cached. */ private int cacheSize = 500; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getUserAgentName() { return userAgentName; } public void setUserAgentName(String userAgentName) { this.userAgentName = userAgentName; } public int getCacheSize() { return cacheSize; } public void setCacheSize(int cacheSize) { this.cacheSize = cacheSize; } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.robotstxt; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class HostDirectives { // If we fetched the directives for this host more than // 24 hours, we have to re-fetch it. private static final long EXPIRATION_DELAY = 24 * 60 * 1000L; private RuleSet disallows = new RuleSet(); private RuleSet allows = new RuleSet(); private long timeFetched; private long timeLastAccessed; public HostDirectives() { timeFetched = System.currentTimeMillis(); } public boolean needsRefetch() { return (System.currentTimeMillis() - timeFetched > EXPIRATION_DELAY); } public boolean allows(String path) { timeLastAccessed = System.currentTimeMillis(); return !disallows.containsPrefixOf(path) || allows.containsPrefixOf(path); } public void addDisallow(String path) { disallows.add(path); } public void addAllow(String path) { allows.add(path); } public long getLastAccessTime() { return timeLastAccessed; } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.frontier; import com.sleepycat.je.*; import edu.uci.ics.crawler4j.url.WebURL; import edu.uci.ics.crawler4j.util.Util; import java.util.ArrayList; import java.util.List; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class WorkQueues { protected Database urlsDB = null; protected Environment env; protected boolean resumable; protected WebURLTupleBinding webURLBinding; protected final Object mutex = new Object(); public WorkQueues(Environment env, String dbName, boolean resumable) throws DatabaseException { this.env = env; this.resumable = resumable; DatabaseConfig dbConfig = new DatabaseConfig(); dbConfig.setAllowCreate(true); dbConfig.setTransactional(resumable); dbConfig.setDeferredWrite(!resumable); urlsDB = env.openDatabase(null, dbName, dbConfig); webURLBinding = new WebURLTupleBinding(); } public List<WebURL> get(int max) throws DatabaseException { synchronized (mutex) { int matches = 0; List<WebURL> results = new ArrayList<>(max); Cursor cursor = null; OperationStatus result; DatabaseEntry key = new DatabaseEntry(); DatabaseEntry value = new DatabaseEntry(); Transaction txn; if (resumable) { txn = env.beginTransaction(null, null); } else { txn = null; } try { cursor = urlsDB.openCursor(txn, null); result = cursor.getFirst(key, value, null); while (matches < max && result == OperationStatus.SUCCESS) { if (value.getData().length > 0) { results.add(webURLBinding.entryToObject(value)); matches++; } result = cursor.getNext(key, value, null); } } catch (DatabaseException e) { if (txn != null) { txn.abort(); txn = null; } throw e; } finally { if (cursor != null) { cursor.close(); } if (txn != null) { txn.commit(); } } return results; } } public void delete(int count) throws DatabaseException { synchronized (mutex) { int matches = 0; Cursor cursor = null; OperationStatus result; DatabaseEntry key = new DatabaseEntry(); DatabaseEntry value = new DatabaseEntry(); Transaction txn; if (resumable) { txn = env.beginTransaction(null, null); } else { txn = null; } try { cursor = urlsDB.openCursor(txn, null); result = cursor.getFirst(key, value, null); while (matches < count && result == OperationStatus.SUCCESS) { cursor.delete(); matches++; result = cursor.getNext(key, value, null); } } catch (DatabaseException e) { if (txn != null) { txn.abort(); txn = null; } throw e; } finally { if (cursor != null) { cursor.close(); } if (txn != null) { txn.commit(); } } } } /* * The key that is used for storing URLs determines the order * they are crawled. Lower key values results in earlier crawling. * Here our keys are 6 bytes. The first byte comes from the URL priority. * The second byte comes from depth of crawl at which this URL is first found. * The rest of the 4 bytes come from the docid of the URL. As a result, * URLs with lower priority numbers will be crawled earlier. If priority * numbers are the same, those found at lower depths will be crawled earlier. * If depth is also equal, those found earlier (therefore, smaller docid) will * be crawled earlier. */ protected DatabaseEntry getDatabaseEntryKey(WebURL url) { byte[] keyData = new byte[6]; keyData[0] = url.getPriority(); keyData[1] = (url.getDepth() > Byte.MAX_VALUE ? Byte.MAX_VALUE : (byte) url.getDepth()); Util.putIntInByteArray(url.getDocid(), keyData, 2); return new DatabaseEntry(keyData); } public void put(WebURL url) throws DatabaseException { DatabaseEntry value = new DatabaseEntry(); webURLBinding.objectToEntry(url, value); Transaction txn; if (resumable) { txn = env.beginTransaction(null, null); } else { txn = null; } urlsDB.put(txn, getDatabaseEntryKey(url), value); if (resumable) { if (txn != null) { txn.commit(); } } } public long getLength() { try { return urlsDB.count(); } catch (Exception e) { e.printStackTrace(); } return -1; } public void sync() { if (resumable) { return; } if (urlsDB == null) { return; } try { urlsDB.sync(); } catch (DatabaseException e) { e.printStackTrace(); } } public void close() { try { urlsDB.close(); } catch (DatabaseException e) { e.printStackTrace(); } } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.frontier; import org.apache.log4j.Logger; import com.sleepycat.je.Cursor; import com.sleepycat.je.DatabaseEntry; import com.sleepycat.je.DatabaseException; import com.sleepycat.je.Environment; import com.sleepycat.je.OperationStatus; import com.sleepycat.je.Transaction; import edu.uci.ics.crawler4j.url.WebURL; /** * This class maintains the list of pages which are * assigned to crawlers but are not yet processed. * It is used for resuming a previous crawl. * * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class InProcessPagesDB extends WorkQueues { private static final Logger logger = Logger.getLogger(InProcessPagesDB.class.getName()); public InProcessPagesDB(Environment env) throws DatabaseException { super(env, "InProcessPagesDB", true); long docCount = getLength(); if (docCount > 0) { logger.info("Loaded " + docCount + " URLs that have been in process in the previous crawl."); } } public boolean removeURL(WebURL webUrl) { synchronized (mutex) { try { DatabaseEntry key = getDatabaseEntryKey(webUrl); Cursor cursor = null; OperationStatus result; DatabaseEntry value = new DatabaseEntry(); Transaction txn = env.beginTransaction(null, null); try { cursor = urlsDB.openCursor(txn, null); result = cursor.getSearchKey(key, value, null); if (result == OperationStatus.SUCCESS) { result = cursor.delete(); if (result == OperationStatus.SUCCESS) { return true; } } } catch (DatabaseException e) { if (txn != null) { txn.abort(); txn = null; } throw e; } finally { if (cursor != null) { cursor.close(); } if (txn != null) { txn.commit(); } } } catch (Exception e) { e.printStackTrace(); } } return false; } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.frontier; import com.sleepycat.bind.tuple.TupleBinding; import com.sleepycat.bind.tuple.TupleInput; import com.sleepycat.bind.tuple.TupleOutput; import edu.uci.ics.crawler4j.url.WebURL; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class WebURLTupleBinding extends TupleBinding<WebURL> { @Override public WebURL entryToObject(TupleInput input) { WebURL webURL = new WebURL(); webURL.setURL(input.readString()); webURL.setDocid(input.readInt()); webURL.setParentDocid(input.readInt()); webURL.setParentUrl(input.readString()); webURL.setDepth(input.readShort()); webURL.setPriority(input.readByte()); webURL.setAnchor(input.readString()); return webURL; } @Override public void objectToEntry(WebURL url, TupleOutput output) { output.writeString(url.getURL()); output.writeInt(url.getDocid()); output.writeInt(url.getParentDocid()); output.writeString(url.getParentUrl()); output.writeShort(url.getDepth()); output.writeByte(url.getPriority()); output.writeString(url.getAnchor()); } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.frontier; import org.apache.log4j.Logger; import com.sleepycat.je.*; import edu.uci.ics.crawler4j.crawler.Configurable; import edu.uci.ics.crawler4j.crawler.CrawlConfig; import edu.uci.ics.crawler4j.util.Util; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class DocIDServer extends Configurable { protected static final Logger logger = Logger.getLogger(DocIDServer.class.getName()); protected Database docIDsDB = null; protected final Object mutex = new Object(); protected int lastDocID; public DocIDServer(Environment env, CrawlConfig config) throws DatabaseException { super(config); DatabaseConfig dbConfig = new DatabaseConfig(); dbConfig.setAllowCreate(true); dbConfig.setTransactional(config.isResumableCrawling()); dbConfig.setDeferredWrite(!config.isResumableCrawling()); docIDsDB = env.openDatabase(null, "DocIDs", dbConfig); if (config.isResumableCrawling()) { int docCount = getDocCount(); if (docCount > 0) { logger.info("Loaded " + docCount + " URLs that had been detected in previous crawl."); lastDocID = docCount; } } else { lastDocID = 0; } } /** * Returns the docid of an already seen url. * * @param url the URL for which the docid is returned. * @return the docid of the url if it is seen before. Otherwise -1 is returned. */ public int getDocId(String url) { synchronized (mutex) { if (docIDsDB == null) { return -1; } OperationStatus result; DatabaseEntry value = new DatabaseEntry(); try { DatabaseEntry key = new DatabaseEntry(url.getBytes()); result = docIDsDB.get(null, key, value, null); if (result == OperationStatus.SUCCESS && value.getData().length > 0) { return Util.byteArray2Int(value.getData()); } } catch (Exception e) { e.printStackTrace(); } return -1; } } public int getNewDocID(String url) { synchronized (mutex) { try { // Make sure that we have not already assigned a docid for this URL int docid = getDocId(url); if (docid > 0) { return docid; } lastDocID++; docIDsDB.put(null, new DatabaseEntry(url.getBytes()), new DatabaseEntry(Util.int2ByteArray(lastDocID))); return lastDocID; } catch (Exception e) { e.printStackTrace(); } return -1; } } public void addUrlAndDocId(String url, int docId) throws Exception { synchronized (mutex) { if (docId <= lastDocID) { throw new Exception("Requested doc id: " + docId + " is not larger than: " + lastDocID); } // Make sure that we have not already assigned a docid for this URL int prevDocid = getDocId(url); if (prevDocid > 0) { if (prevDocid == docId) { return; } throw new Exception("Doc id: " + prevDocid + " is already assigned to URL: " + url); } docIDsDB.put(null, new DatabaseEntry(url.getBytes()), new DatabaseEntry(Util.int2ByteArray(docId))); lastDocID = docId; } } public boolean isSeenBefore(String url) { return getDocId(url) != -1; } public int getDocCount() { try { return (int) docIDsDB.count(); } catch (DatabaseException e) { e.printStackTrace(); } return -1; } public void sync() { if (config.isResumableCrawling()) { return; } if (docIDsDB == null) { return; } try { docIDsDB.sync(); } catch (DatabaseException e) { e.printStackTrace(); } } public void close() { try { docIDsDB.close(); } catch (DatabaseException e) { e.printStackTrace(); } } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.frontier; import com.sleepycat.je.*; import edu.uci.ics.crawler4j.crawler.Configurable; import edu.uci.ics.crawler4j.crawler.CrawlConfig; import edu.uci.ics.crawler4j.util.Util; import java.util.HashMap; import java.util.Map; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class Counters extends Configurable { public class ReservedCounterNames { public final static String SCHEDULED_PAGES = "Scheduled-Pages"; public final static String PROCESSED_PAGES = "Processed-Pages"; } protected Database statisticsDB = null; protected Environment env; protected final Object mutex = new Object(); protected Map<String, Long> counterValues; public Counters(Environment env, CrawlConfig config) throws DatabaseException { super(config); this.env = env; this.counterValues = new HashMap<>(); /* * When crawling is set to be resumable, we have to keep the statistics * in a transactional database to make sure they are not lost if crawler * is crashed or terminated unexpectedly. */ if (config.isResumableCrawling()) { DatabaseConfig dbConfig = new DatabaseConfig(); dbConfig.setAllowCreate(true); dbConfig.setTransactional(true); dbConfig.setDeferredWrite(false); statisticsDB = env.openDatabase(null, "Statistics", dbConfig); OperationStatus result; DatabaseEntry key = new DatabaseEntry(); DatabaseEntry value = new DatabaseEntry(); Transaction tnx = env.beginTransaction(null, null); Cursor cursor = statisticsDB.openCursor(tnx, null); result = cursor.getFirst(key, value, null); while (result == OperationStatus.SUCCESS) { if (value.getData().length > 0) { String name = new String(key.getData()); long counterValue = Util.byteArray2Long(value.getData()); counterValues.put(name, new Long(counterValue)); } result = cursor.getNext(key, value, null); } cursor.close(); tnx.commit(); } } public long getValue(String name) { synchronized (mutex) { Long value = counterValues.get(name); if (value == null) { return 0; } return value.longValue(); } } public void setValue(String name, long value) { synchronized (mutex) { try { counterValues.put(name, new Long(value)); if (statisticsDB != null) { Transaction txn = env.beginTransaction(null, null); statisticsDB.put(txn, new DatabaseEntry(name.getBytes()), new DatabaseEntry(Util.long2ByteArray(value))); txn.commit(); } } catch (Exception e) { e.printStackTrace(); } } } public void increment(String name) { increment(name, 1); } public void increment(String name, long addition) { synchronized (mutex) { long prevValue = getValue(name); setValue(name, prevValue + addition); } } public void sync() { if (config.isResumableCrawling()) { return; } if (statisticsDB == null) { return; } try { statisticsDB.sync(); } catch (DatabaseException e) { e.printStackTrace(); } } public void close() { try { if (statisticsDB != null) { statisticsDB.close(); } } catch (DatabaseException e) { e.printStackTrace(); } } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.frontier; import com.sleepycat.je.DatabaseException; import com.sleepycat.je.Environment; import edu.uci.ics.crawler4j.crawler.Configurable; import edu.uci.ics.crawler4j.crawler.CrawlConfig; import edu.uci.ics.crawler4j.frontier.Counters.ReservedCounterNames; import edu.uci.ics.crawler4j.url.WebURL; import org.apache.log4j.Logger; import java.util.List; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class Frontier extends Configurable { protected static final Logger logger = Logger.getLogger(Frontier.class.getName()); protected WorkQueues workQueues; protected InProcessPagesDB inProcessPages; protected final Object mutex = new Object(); protected final Object waitingList = new Object(); protected boolean isFinished = false; protected long scheduledPages; protected DocIDServer docIdServer; protected Counters counters; public Frontier(Environment env, CrawlConfig config, DocIDServer docIdServer) { super(config); this.counters = new Counters(env, config); this.docIdServer = docIdServer; try { workQueues = new WorkQueues(env, "PendingURLsDB", config.isResumableCrawling()); if (config.isResumableCrawling()) { scheduledPages = counters.getValue(ReservedCounterNames.SCHEDULED_PAGES); inProcessPages = new InProcessPagesDB(env); long numPreviouslyInProcessPages = inProcessPages.getLength(); if (numPreviouslyInProcessPages > 0) { logger.info("Rescheduling " + numPreviouslyInProcessPages + " URLs from previous crawl."); scheduledPages -= numPreviouslyInProcessPages; while (true) { List<WebURL> urls = inProcessPages.get(100); if (urls.size() == 0) { break; } scheduleAll(urls); inProcessPages.delete(urls.size()); } } } else { inProcessPages = null; scheduledPages = 0; } } catch (DatabaseException e) { logger.error("Error while initializing the Frontier: " + e.getMessage()); workQueues = null; } } public void scheduleAll(List<WebURL> urls) { int maxPagesToFetch = config.getMaxPagesToFetch(); synchronized (mutex) { int newScheduledPage = 0; for (WebURL url : urls) { if (maxPagesToFetch > 0 && (scheduledPages + newScheduledPage) >= maxPagesToFetch) { break; } try { workQueues.put(url); newScheduledPage++; } catch (DatabaseException e) { logger.error("Error while puting the url in the work queue."); } } if (newScheduledPage > 0) { scheduledPages += newScheduledPage; counters.increment(Counters.ReservedCounterNames.SCHEDULED_PAGES, newScheduledPage); } synchronized (waitingList) { waitingList.notifyAll(); } } } public void schedule(WebURL url) { int maxPagesToFetch = config.getMaxPagesToFetch(); synchronized (mutex) { try { if (maxPagesToFetch < 0 || scheduledPages < maxPagesToFetch) { workQueues.put(url); scheduledPages++; counters.increment(Counters.ReservedCounterNames.SCHEDULED_PAGES); } } catch (DatabaseException e) { logger.error("Error while puting the url in the work queue."); } } } public void getNextURLs(int max, List<WebURL> result) { while (true) { synchronized (mutex) { if (isFinished) { return; } try { List<WebURL> curResults = workQueues.get(max); workQueues.delete(curResults.size()); if (inProcessPages != null) { for (WebURL curPage : curResults) { inProcessPages.put(curPage); } } result.addAll(curResults); } catch (DatabaseException e) { logger.error("Error while getting next urls: " + e.getMessage()); e.printStackTrace(); } if (result.size() > 0) { return; } } try { synchronized (waitingList) { waitingList.wait(); } } catch (InterruptedException ignored) { // Do nothing } if (isFinished) { return; } } } public void setProcessed(WebURL webURL) { counters.increment(ReservedCounterNames.PROCESSED_PAGES); if (inProcessPages != null) { if (!inProcessPages.removeURL(webURL)) { logger.warn("Could not remove: " + webURL.getURL() + " from list of processed pages."); } } } public long getQueueLength() { return workQueues.getLength(); } public long getNumberOfAssignedPages() { return inProcessPages.getLength(); } public long getNumberOfProcessedPages() { return counters.getValue(ReservedCounterNames.PROCESSED_PAGES); } public void sync() { workQueues.sync(); docIdServer.sync(); counters.sync(); } public boolean isFinished() { return isFinished; } public void close() { sync(); workQueues.close(); counters.close(); } public void finish() { isFinished = true; synchronized (waitingList) { waitingList.notifyAll(); } } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.parser; public class BinaryParseData implements ParseData { private static BinaryParseData instance = new BinaryParseData(); public static BinaryParseData getInstance() { return instance; } @Override public String toString() { return "[Binary parse data can not be dumped as string]"; } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.parser; import edu.uci.ics.crawler4j.url.WebURL; import java.util.List; public class HtmlParseData implements ParseData { private String html; private String text; private String title; private List<WebURL> outgoingUrls; public String getHtml() { return html; } public void setHtml(String html) { this.html = html; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public List<WebURL> getOutgoingUrls() { return outgoingUrls; } public void setOutgoingUrls(List<WebURL> outgoingUrls) { this.outgoingUrls = outgoingUrls; } @Override public String toString() { return text; } }
Java
package edu.uci.ics.crawler4j.parser; public class ExtractedUrlAnchorPair { private String href; private String anchor; public String getHref() { return href; } public void setHref(String href) { this.href = href; } public String getAnchor() { return anchor; } public void setAnchor(String anchor) { this.anchor = anchor; } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.parser; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.apache.tika.metadata.DublinCore; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.html.HtmlParser; import edu.uci.ics.crawler4j.crawler.Configurable; import edu.uci.ics.crawler4j.crawler.CrawlConfig; import edu.uci.ics.crawler4j.crawler.Page; import edu.uci.ics.crawler4j.url.URLCanonicalizer; import edu.uci.ics.crawler4j.url.WebURL; import edu.uci.ics.crawler4j.util.Util; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class Parser extends Configurable { protected static final Logger logger = Logger.getLogger(Parser.class.getName()); private HtmlParser htmlParser; private ParseContext parseContext; public Parser(CrawlConfig config) { super(config); htmlParser = new HtmlParser(); parseContext = new ParseContext(); } public boolean parse(Page page, String contextURL) { if (Util.hasBinaryContent(page.getContentType())) { if (!config.isIncludeBinaryContentInCrawling()) { return false; } page.setParseData(BinaryParseData.getInstance()); return true; } else if (Util.hasPlainTextContent(page.getContentType())) { try { TextParseData parseData = new TextParseData(); if (page.getContentCharset() == null) { parseData.setTextContent(new String(page.getContentData())); } else { parseData.setTextContent(new String(page.getContentData(), page.getContentCharset())); } page.setParseData(parseData); return true; } catch (Exception e) { logger.error(e.getMessage() + ", while parsing: " + page.getWebURL().getURL()); } return false; } Metadata metadata = new Metadata(); HtmlContentHandler contentHandler = new HtmlContentHandler(); InputStream inputStream = null; try { inputStream = new ByteArrayInputStream(page.getContentData()); htmlParser.parse(inputStream, contentHandler, metadata, parseContext); } catch (Exception e) { logger.error(e.getMessage() + ", while parsing: " + page.getWebURL().getURL()); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { logger.error(e.getMessage() + ", while parsing: " + page.getWebURL().getURL()); } } if (page.getContentCharset() == null) { page.setContentCharset(metadata.get("Content-Encoding")); } HtmlParseData parseData = new HtmlParseData(); parseData.setText(contentHandler.getBodyText().trim()); parseData.setTitle(metadata.get(DublinCore.TITLE)); List<WebURL> outgoingUrls = new ArrayList<>(); String baseURL = contentHandler.getBaseUrl(); if (baseURL != null) { contextURL = baseURL; } int urlCount = 0; for (ExtractedUrlAnchorPair urlAnchorPair : contentHandler.getOutgoingUrls()) { String href = urlAnchorPair.getHref(); href = href.trim(); if (href.length() == 0) { continue; } String hrefWithoutProtocol = href.toLowerCase(); if (href.startsWith("http://")) { hrefWithoutProtocol = href.substring(7); } if (!hrefWithoutProtocol.contains("javascript:") && !hrefWithoutProtocol.contains("mailto:") && !hrefWithoutProtocol.contains("@")) { String url = URLCanonicalizer.getCanonicalURL(href, contextURL); if (url != null) { WebURL webURL = new WebURL(); webURL.setURL(url); webURL.setAnchor(urlAnchorPair.getAnchor()); outgoingUrls.add(webURL); urlCount++; if (urlCount > config.getMaxOutgoingLinksToFollow()) { break; } } } } parseData.setOutgoingUrls(outgoingUrls); try { if (page.getContentCharset() == null) { parseData.setHtml(new String(page.getContentData())); } else { parseData.setHtml(new String(page.getContentData(), page.getContentCharset())); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); return false; } page.setParseData(parseData); return true; } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.parser; public class TextParseData implements ParseData { private String textContent; public String getTextContent() { return textContent; } public void setTextContent(String textContent) { this.textContent = textContent; } @Override public String toString() { return textContent; } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.parser; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class HtmlContentHandler extends DefaultHandler { private final int MAX_ANCHOR_LENGTH = 100; private enum Element { A, AREA, LINK, IFRAME, FRAME, EMBED, IMG, BASE, META, BODY } private static class HtmlFactory { private static Map<String, Element> name2Element; static { name2Element = new HashMap<>(); for (Element element : Element.values()) { name2Element.put(element.toString().toLowerCase(), element); } } public static Element getElement(String name) { return name2Element.get(name); } } private String base; private String metaRefresh; private String metaLocation; private boolean isWithinBodyElement; private StringBuilder bodyText; private List<ExtractedUrlAnchorPair> outgoingUrls; private ExtractedUrlAnchorPair curUrl = null; private boolean anchorFlag = false; private StringBuilder anchorText = new StringBuilder(); public HtmlContentHandler() { isWithinBodyElement = false; bodyText = new StringBuilder(); outgoingUrls = new ArrayList<>(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { Element element = HtmlFactory.getElement(localName); if (element == Element.A || element == Element.AREA || element == Element.LINK) { String href = attributes.getValue("href"); if (href != null) { anchorFlag = true; curUrl = new ExtractedUrlAnchorPair(); curUrl.setHref(href); outgoingUrls.add(curUrl); } return; } if (element == Element.IMG) { String imgSrc = attributes.getValue("src"); if (imgSrc != null) { curUrl = new ExtractedUrlAnchorPair(); curUrl.setHref(imgSrc); outgoingUrls.add(curUrl); } return; } if (element == Element.IFRAME || element == Element.FRAME || element == Element.EMBED) { String src = attributes.getValue("src"); if (src != null) { curUrl = new ExtractedUrlAnchorPair(); curUrl.setHref(src); outgoingUrls.add(curUrl); } return; } if (element == Element.BASE) { if (base != null) { // We only consider the first occurrence of the // Base element. String href = attributes.getValue("href"); if (href != null) { base = href; } } return; } if (element == Element.META) { String equiv = attributes.getValue("http-equiv"); String content = attributes.getValue("content"); if (equiv != null && content != null) { equiv = equiv.toLowerCase(); // http-equiv="refresh" content="0;URL=http://foo.bar/..." if (equiv.equals("refresh") && (metaRefresh == null)) { int pos = content.toLowerCase().indexOf("url="); if (pos != -1) { metaRefresh = content.substring(pos + 4); } curUrl = new ExtractedUrlAnchorPair(); curUrl.setHref(metaRefresh); outgoingUrls.add(curUrl); } // http-equiv="location" content="http://foo.bar/..." if (equiv.equals("location") && (metaLocation == null)) { metaLocation = content; curUrl = new ExtractedUrlAnchorPair(); curUrl.setHref(metaRefresh); outgoingUrls.add(curUrl); } } return; } if (element == Element.BODY) { isWithinBodyElement = true; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { Element element = HtmlFactory.getElement(localName); if (element == Element.A || element == Element.AREA || element == Element.LINK) { anchorFlag = false; if (curUrl != null) { String anchor = anchorText.toString().replaceAll("\n", " ").replaceAll("\t", " ").trim(); if (!anchor.isEmpty()) { if (anchor.length() > MAX_ANCHOR_LENGTH) { anchor = anchor.substring(0, MAX_ANCHOR_LENGTH) + "..."; } curUrl.setAnchor(anchor); } anchorText.delete(0, anchorText.length()); } curUrl = null; } if (element == Element.BODY) { isWithinBodyElement = false; } } @Override public void characters(char ch[], int start, int length) throws SAXException { if (isWithinBodyElement) { bodyText.append(ch, start, length); if (anchorFlag) { anchorText.append(new String(ch, start, length)); } } } public String getBodyText() { return bodyText.toString(); } public List<ExtractedUrlAnchorPair> getOutgoingUrls() { return outgoingUrls; } public String getBaseUrl() { return base; } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.parser; public interface ParseData { @Override public String toString(); }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.fetcher; import java.util.concurrent.TimeUnit; import org.apache.http.impl.conn.PoolingClientConnectionManager; public class IdleConnectionMonitorThread extends Thread { private final PoolingClientConnectionManager connMgr; private volatile boolean shutdown; public IdleConnectionMonitorThread(PoolingClientConnectionManager connMgr) { super("Connection Manager"); this.connMgr = connMgr; } @Override public void run() { try { while (!shutdown) { synchronized (this) { wait(5000); // Close expired connections connMgr.closeExpiredConnections(); // Optionally, close connections // that have been idle longer than 30 sec connMgr.closeIdleConnections(30, TimeUnit.SECONDS); } } } catch (InterruptedException ex) { // terminate } } public void shutdown() { shutdown = true; synchronized (this) { notifyAll(); } } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"; you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.fetcher; import org.apache.http.HttpStatus; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class CustomFetchStatus { public static final int PageTooBig = 1001; public static final int FatalTransportError = 1005; public static final int UnknownError = 1006; public static String getStatusDescription(int code) { switch (code) { case HttpStatus.SC_OK: return "OK"; case HttpStatus.SC_CREATED: return "Created"; case HttpStatus.SC_ACCEPTED: return "Accepted"; case HttpStatus.SC_NO_CONTENT: return "No Content"; case HttpStatus.SC_MOVED_PERMANENTLY: return "Moved Permanently"; case HttpStatus.SC_MOVED_TEMPORARILY: return "Moved Temporarily"; case HttpStatus.SC_NOT_MODIFIED: return "Not Modified"; case HttpStatus.SC_BAD_REQUEST: return "Bad Request"; case HttpStatus.SC_UNAUTHORIZED: return "Unauthorized"; case HttpStatus.SC_FORBIDDEN: return "Forbidden"; case HttpStatus.SC_NOT_FOUND: return "Not Found"; case HttpStatus.SC_INTERNAL_SERVER_ERROR: return "Internal Server Error"; case HttpStatus.SC_NOT_IMPLEMENTED: return "Not Implemented"; case HttpStatus.SC_BAD_GATEWAY: return "Bad Gateway"; case HttpStatus.SC_SERVICE_UNAVAILABLE: return "Service Unavailable"; case HttpStatus.SC_CONTINUE: return "Continue"; case HttpStatus.SC_TEMPORARY_REDIRECT: return "Temporary Redirect"; case HttpStatus.SC_METHOD_NOT_ALLOWED: return "Method Not Allowed"; case HttpStatus.SC_CONFLICT: return "Conflict"; case HttpStatus.SC_PRECONDITION_FAILED: return "Precondition Failed"; case HttpStatus.SC_REQUEST_TOO_LONG: return "Request Too Long"; case HttpStatus.SC_REQUEST_URI_TOO_LONG: return "Request-URI Too Long"; case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE: return "Unsupported Media Type"; case HttpStatus.SC_MULTIPLE_CHOICES: return "Multiple Choices"; case HttpStatus.SC_SEE_OTHER: return "See Other"; case HttpStatus.SC_USE_PROXY: return "Use Proxy"; case HttpStatus.SC_PAYMENT_REQUIRED: return "Payment Required"; case HttpStatus.SC_NOT_ACCEPTABLE: return "Not Acceptable"; case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED: return "Proxy Authentication Required"; case HttpStatus.SC_REQUEST_TIMEOUT: return "Request Timeout"; case PageTooBig: return "Page size was too big"; case FatalTransportError: return "Fatal transport error"; case UnknownError: return "Unknown error"; default: return "(" + code + ")"; } } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.fetcher; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.zip.GZIPInputStream; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.CookiePolicy; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParamBean; import org.apache.http.protocol.HttpContext; import org.apache.log4j.Logger; import edu.uci.ics.crawler4j.crawler.Configurable; import edu.uci.ics.crawler4j.crawler.CrawlConfig; import edu.uci.ics.crawler4j.url.URLCanonicalizer; import edu.uci.ics.crawler4j.url.WebURL; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class PageFetcher extends Configurable { protected static final Logger logger = Logger.getLogger(PageFetcher.class); protected PoolingClientConnectionManager connectionManager; protected DefaultHttpClient httpClient; protected final Object mutex = new Object(); protected long lastFetchTime = 0; protected IdleConnectionMonitorThread connectionMonitorThread = null; public PageFetcher(CrawlConfig config) { super(config); HttpParams params = new BasicHttpParams(); HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params); paramsBean.setVersion(HttpVersion.HTTP_1_1); paramsBean.setContentCharset("UTF-8"); paramsBean.setUseExpectContinue(false); params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString()); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout()); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout()); params.setBooleanParameter("http.protocol.handle-redirects", false); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); if (config.isIncludeHttpsPages()) { schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); } connectionManager = new PoolingClientConnectionManager(schemeRegistry); connectionManager.setMaxTotal(config.getMaxTotalConnections()); connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost()); httpClient = new DefaultHttpClient(connectionManager, params); if (config.getProxyHost() != null) { if (config.getProxyUsername() != null) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(config.getProxyHost(), config.getProxyPort()), new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword())); } HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort()); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); Header contentEncoding = entity.getContentEncoding(); if (contentEncoding != null) { HeaderElement[] codecs = contentEncoding.getElements(); for (HeaderElement codec : codecs) { if (codec.getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } }); if (connectionMonitorThread == null) { connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager); } connectionMonitorThread.start(); } public PageFetchResult fetchHeader(WebURL webUrl) { PageFetchResult fetchResult = new PageFetchResult(); String toFetchURL = webUrl.getURL(); HttpGet get = null; try { get = new HttpGet(toFetchURL); synchronized (mutex) { long now = (new Date()).getTime(); if (now - lastFetchTime < config.getPolitenessDelay()) { Thread.sleep(config.getPolitenessDelay() - (now - lastFetchTime)); } lastFetchTime = (new Date()).getTime(); } get.addHeader("Accept-Encoding", "gzip"); HttpResponse response = httpClient.execute(get); fetchResult.setEntity(response.getEntity()); fetchResult.setResponseHeaders(response.getAllHeaders()); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { if (statusCode != HttpStatus.SC_NOT_FOUND) { if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { Header header = response.getFirstHeader("Location"); if (header != null) { String movedToUrl = header.getValue(); movedToUrl = URLCanonicalizer.getCanonicalURL(movedToUrl, toFetchURL); fetchResult.setMovedToUrl(movedToUrl); } fetchResult.setStatusCode(statusCode); return fetchResult; } logger.info("Failed: " + response.getStatusLine().toString() + ", while fetching " + toFetchURL); } fetchResult.setStatusCode(response.getStatusLine().getStatusCode()); return fetchResult; } fetchResult.setFetchedUrl(toFetchURL); String uri = get.getURI().toString(); if (!uri.equals(toFetchURL)) { if (!URLCanonicalizer.getCanonicalURL(uri).equals(toFetchURL)) { fetchResult.setFetchedUrl(uri); } } if (fetchResult.getEntity() != null) { long size = fetchResult.getEntity().getContentLength(); if (size == -1) { Header length = response.getLastHeader("Content-Length"); if (length == null) { length = response.getLastHeader("Content-length"); } if (length != null) { size = Integer.parseInt(length.getValue()); } else { size = -1; } } if (size > config.getMaxDownloadSize()) { fetchResult.setStatusCode(CustomFetchStatus.PageTooBig); get.abort(); return fetchResult; } fetchResult.setStatusCode(HttpStatus.SC_OK); return fetchResult; } get.abort(); } catch (IOException e) { logger.error("Fatal transport error: " + e.getMessage() + " while fetching " + toFetchURL + " (link found in doc #" + webUrl.getParentDocid() + ")"); fetchResult.setStatusCode(CustomFetchStatus.FatalTransportError); return fetchResult; } catch (IllegalStateException e) { // ignoring exceptions that occur because of not registering https // and other schemes } catch (Exception e) { if (e.getMessage() == null) { logger.error("Error while fetching " + webUrl.getURL()); } else { logger.error(e.getMessage() + " while fetching " + webUrl.getURL()); } } finally { try { if (fetchResult.getEntity() == null && get != null) { get.abort(); } } catch (Exception e) { e.printStackTrace(); } } fetchResult.setStatusCode(CustomFetchStatus.UnknownError); return fetchResult; } public synchronized void shutDown() { if (connectionMonitorThread != null) { connectionManager.shutdown(); connectionMonitorThread.shutdown(); } } public HttpClient getHttpClient() { return httpClient; } private static class GzipDecompressingEntity extends HttpEntityWrapper { public GzipDecompressingEntity(final HttpEntity entity) { super(entity); } @Override public InputStream getContent() throws IOException, IllegalStateException { // the wrapped entity's getContent() decides about repeatability InputStream wrappedin = wrappedEntity.getContent(); return new GZIPInputStream(wrappedin); } @Override public long getContentLength() { // length of ungzipped content is not known return -1; } } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.fetcher; import java.io.EOFException; import java.io.IOException; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; import edu.uci.ics.crawler4j.crawler.Page; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class PageFetchResult { protected static final Logger logger = Logger.getLogger(PageFetchResult.class); protected int statusCode; protected HttpEntity entity = null; protected Header[] responseHeaders = null; protected String fetchedUrl = null; protected String movedToUrl = null; public int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } public HttpEntity getEntity() { return entity; } public void setEntity(HttpEntity entity) { this.entity = entity; } public Header[] getResponseHeaders() { return responseHeaders; } public void setResponseHeaders(Header[] responseHeaders) { this.responseHeaders = responseHeaders; } public String getFetchedUrl() { return fetchedUrl; } public void setFetchedUrl(String fetchedUrl) { this.fetchedUrl = fetchedUrl; } public boolean fetchContent(Page page) { try { page.load(entity); page.setFetchResponseHeaders(responseHeaders); return true; } catch (Exception e) { logger.info("Exception while fetching content for: " + page.getWebURL().getURL() + " [" + e.getMessage() + "]"); } return false; } public void discardContentIfNotConsumed() { try { if (entity != null) { EntityUtils.consume(entity); } } catch (EOFException e) { // We can ignore this exception. It can happen on compressed streams // which are not repeatable } catch (IOException e) { // We can ignore this exception. It can happen if the stream is // closed. } catch (Exception e) { e.printStackTrace(); } } public String getMovedToUrl() { return movedToUrl; } public void setMovedToUrl(String movedToUrl) { this.movedToUrl = movedToUrl; } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.url; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; /** * See http://en.wikipedia.org/wiki/URL_normalization for a reference Note: some * parts of the code are adapted from: http://stackoverflow.com/a/4057470/405418 * * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class URLCanonicalizer { public static String getCanonicalURL(String url) { return getCanonicalURL(url, null); } public static String getCanonicalURL(String href, String context) { try { URL canonicalURL = new URL(UrlResolver.resolveUrl(context == null ? "" : context, href)); String host = canonicalURL.getHost().toLowerCase(); if (host == "") { // This is an invalid Url. return null; } String path = canonicalURL.getPath(); /* * Normalize: no empty segments (i.e., "//"), no segments equal to * ".", and no segments equal to ".." that are preceded by a segment * not equal to "..". */ path = new URI(path).normalize().toString(); /* * Convert '//' -> '/' */ int idx = path.indexOf("//"); while (idx >= 0) { path = path.replace("//", "/"); idx = path.indexOf("//"); } /* * Drop starting '/../' */ while (path.startsWith("/../")) { path = path.substring(3); } /* * Trim */ path = path.trim(); final SortedMap<String, String> params = createParameterMap(canonicalURL.getQuery()); final String queryString; if (params != null && params.size() > 0) { String canonicalParams = canonicalize(params); queryString = (canonicalParams.isEmpty() ? "" : "?" + canonicalParams); } else { queryString = ""; } /* * Add starting slash if needed */ if (path.length() == 0) { path = "/" + path; } /* * Drop default port: example.com:80 -> example.com */ int port = canonicalURL.getPort(); if (port == canonicalURL.getDefaultPort()) { port = -1; } String protocol = canonicalURL.getProtocol().toLowerCase(); String pathAndQueryString = normalizePath(path) + queryString; URL result = new URL(protocol, host, port, pathAndQueryString); return result.toExternalForm(); } catch (MalformedURLException ex) { return null; } catch (URISyntaxException ex) { return null; } } /** * Takes a query string, separates the constituent name-value pairs, and * stores them in a SortedMap ordered by lexicographical order. * * @return Null if there is no query string. */ private static SortedMap<String, String> createParameterMap(final String queryString) { if (queryString == null || queryString.isEmpty()) { return null; } final String[] pairs = queryString.split("&"); final Map<String, String> params = new HashMap<>(pairs.length); for (final String pair : pairs) { if (pair.length() == 0) { continue; } String[] tokens = pair.split("=", 2); switch (tokens.length) { case 1: if (pair.charAt(0) == '=') { params.put("", tokens[0]); } else { params.put(tokens[0], ""); } break; case 2: params.put(tokens[0], tokens[1]); break; } } return new TreeMap<>(params); } /** * Canonicalize the query string. * * @param sortedParamMap * Parameter name-value pairs in lexicographical order. * @return Canonical form of query string. */ private static String canonicalize(final SortedMap<String, String> sortedParamMap) { if (sortedParamMap == null || sortedParamMap.isEmpty()) { return ""; } final StringBuffer sb = new StringBuffer(100); for (Map.Entry<String, String> pair : sortedParamMap.entrySet()) { final String key = pair.getKey().toLowerCase(); if (key.equals("jsessionid") || key.equals("phpsessid") || key.equals("aspsessionid")) { continue; } if (sb.length() > 0) { sb.append('&'); } sb.append(percentEncodeRfc3986(pair.getKey())); if (!pair.getValue().isEmpty()) { sb.append('='); sb.append(percentEncodeRfc3986(pair.getValue())); } } return sb.toString(); } /** * Percent-encode values according the RFC 3986. The built-in Java * URLEncoder does not encode according to the RFC, so we make the extra * replacements. * * @param string * Decoded string. * @return Encoded string per RFC 3986. */ private static String percentEncodeRfc3986(String string) { try { string = string.replace("+", "%2B"); string = URLDecoder.decode(string, "UTF-8"); string = URLEncoder.encode(string, "UTF-8"); return string.replace("+", "%20").replace("*", "%2A").replace("%7E", "~"); } catch (Exception e) { return string; } } private static String normalizePath(final String path) { return path.replace("%7E", "~").replace(" ", "%20"); } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.url; import java.io.Serializable; import com.sleepycat.persist.model.Entity; import com.sleepycat.persist.model.PrimaryKey; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ @Entity public class WebURL implements Serializable { private static final long serialVersionUID = 1L; @PrimaryKey private String url; private int docid; private int parentDocid; private String parentUrl; private short depth; private String domain; private String subDomain; private String path; private String anchor; private byte priority; /** * Returns the unique document id assigned to this Url. */ public int getDocid() { return docid; } public void setDocid(int docid) { this.docid = docid; } @Override public int hashCode() { return url.hashCode(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WebURL otherUrl = (WebURL) o; return url != null && url.equals(otherUrl.getURL()); } @Override public String toString() { return url; } /** * Returns the Url string */ public String getURL() { return url; } public void setURL(String url) { this.url = url; int domainStartIdx = url.indexOf("//") + 2; int domainEndIdx = url.indexOf('/', domainStartIdx); domain = url.substring(domainStartIdx, domainEndIdx); subDomain = ""; String[] parts = domain.split("\\."); if (parts.length > 2) { domain = parts[parts.length - 2] + "." + parts[parts.length - 1]; int limit = 2; if (TLDList.getInstance().contains(domain)) { domain = parts[parts.length - 3] + "." + domain; limit = 3; } for (int i = 0; i < parts.length - limit; i++) { if (subDomain.length() > 0) { subDomain += "."; } subDomain += parts[i]; } } path = url.substring(domainEndIdx); int pathEndIdx = path.indexOf('?'); if (pathEndIdx >= 0) { path = path.substring(0, pathEndIdx); } } /** * Returns the unique document id of the parent page. The parent page is the * page in which the Url of this page is first observed. */ public int getParentDocid() { return parentDocid; } public void setParentDocid(int parentDocid) { this.parentDocid = parentDocid; } /** * Returns the url of the parent page. The parent page is the page in which * the Url of this page is first observed. */ public String getParentUrl() { return parentUrl; } public void setParentUrl(String parentUrl) { this.parentUrl = parentUrl; } /** * Returns the crawl depth at which this Url is first observed. Seed Urls * are at depth 0. Urls that are extracted from seed Urls are at depth 1, * etc. */ public short getDepth() { return depth; } public void setDepth(short depth) { this.depth = depth; } /** * Returns the domain of this Url. For 'http://www.example.com/sample.htm', * domain will be 'example.com' */ public String getDomain() { return domain; } public String getSubDomain() { return subDomain; } /** * Returns the path of this Url. For 'http://www.example.com/sample.htm', * domain will be 'sample.htm' */ public String getPath() { return path; } public void setPath(String path) { this.path = path; } /** * Returns the anchor string. For example, in <a href="example.com">A sample anchor</a> * the anchor string is 'A sample anchor' */ public String getAnchor() { return anchor; } public void setAnchor(String anchor) { this.anchor = anchor; } /** * Returns the priority for crawling this URL. * A lower number results in higher priority. */ public byte getPriority() { return priority; } public void setPriority(byte priority) { this.priority = priority; } }
Java
/** * This class is adopted from Htmlunit with the following copyright: * * Copyright (c) 2002-2012 Gargoyle Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.url; public final class UrlResolver { /** * Resolves a given relative URL against a base URL. See * <a href="http://www.faqs.org/rfcs/rfc1808.html">RFC1808</a> * Section 4 for more details. * * @param baseUrl The base URL in which to resolve the specification. * @param relativeUrl The relative URL to resolve against the base URL. * @return the resolved specification. */ public static String resolveUrl(final String baseUrl, final String relativeUrl) { if (baseUrl == null) { throw new IllegalArgumentException("Base URL must not be null"); } if (relativeUrl == null) { throw new IllegalArgumentException("Relative URL must not be null"); } final Url url = resolveUrl(parseUrl(baseUrl.trim()), relativeUrl.trim()); return url.toString(); } /** * Returns the index within the specified string of the first occurrence of * the specified search character. * * @param s the string to search * @param searchChar the character to search for * @param beginIndex the index at which to start the search * @param endIndex the index at which to stop the search * @return the index of the first occurrence of the character in the string or <tt>-1</tt> */ private static int indexOf(final String s, final char searchChar, final int beginIndex, final int endIndex) { for (int i = beginIndex; i < endIndex; i++) { if (s.charAt(i) == searchChar) { return i; } } return -1; } /** * Parses a given specification using the algorithm depicted in * <a href="http://www.faqs.org/rfcs/rfc1808.html">RFC1808</a>: * * Section 2.4: Parsing a URL * * An accepted method for parsing URLs is useful to clarify the * generic-RL syntax of Section 2.2 and to describe the algorithm for * resolving relative URLs presented in Section 4. This section * describes the parsing rules for breaking down a URL (relative or * absolute) into the component parts described in Section 2.1. The * rules assume that the URL has already been separated from any * surrounding text and copied to a "parse string". The rules are * listed in the order in which they would be applied by the parser. * * @param spec The specification to parse. * @return the parsed specification. */ private static Url parseUrl(final String spec) { final Url url = new Url(); int startIndex = 0; int endIndex = spec.length(); // Section 2.4.1: Parsing the Fragment Identifier // // If the parse string contains a crosshatch "#" character, then the // substring after the first (left-most) crosshatch "#" and up to the // end of the parse string is the <fragment> identifier. If the // crosshatch is the last character, or no crosshatch is present, then // the fragment identifier is empty. The matched substring, including // the crosshatch character, is removed from the parse string before // continuing. // // Note that the fragment identifier is not considered part of the URL. // However, since it is often attached to the URL, parsers must be able // to recognize and set aside fragment identifiers as part of the // process. final int crosshatchIndex = indexOf(spec, '#', startIndex, endIndex); if (crosshatchIndex >= 0) { url.fragment_ = spec.substring(crosshatchIndex + 1, endIndex); endIndex = crosshatchIndex; } // Section 2.4.2: Parsing the Scheme // // If the parse string contains a colon ":" after the first character // and before any characters not allowed as part of a scheme name (i.e., // any not an alphanumeric, plus "+", period ".", or hyphen "-"), the // <scheme> of the URL is the substring of characters up to but not // including the first colon. These characters and the colon are then // removed from the parse string before continuing. final int colonIndex = indexOf(spec, ':', startIndex, endIndex); if (colonIndex > 0) { final String scheme = spec.substring(startIndex, colonIndex); if (isValidScheme(scheme)) { url.scheme_ = scheme; startIndex = colonIndex + 1; } } // Section 2.4.3: Parsing the Network Location/Login // // If the parse string begins with a double-slash "//", then the // substring of characters after the double-slash and up to, but not // including, the next slash "/" character is the network location/login // (<net_loc>) of the URL. If no trailing slash "/" is present, the // entire remaining parse string is assigned to <net_loc>. The double- // slash and <net_loc> are removed from the parse string before // continuing. // // Note: We also accept a question mark "?" or a semicolon ";" character as // delimiters for the network location/login (<net_loc>) of the URL. final int locationStartIndex; int locationEndIndex; if (spec.startsWith("//", startIndex)) { locationStartIndex = startIndex + 2; locationEndIndex = indexOf(spec, '/', locationStartIndex, endIndex); if (locationEndIndex >= 0) { startIndex = locationEndIndex; } } else { locationStartIndex = -1; locationEndIndex = -1; } // Section 2.4.4: Parsing the Query Information // // If the parse string contains a question mark "?" character, then the // substring after the first (left-most) question mark "?" and up to the // end of the parse string is the <query> information. If the question // mark is the last character, or no question mark is present, then the // query information is empty. The matched substring, including the // question mark character, is removed from the parse string before // continuing. final int questionMarkIndex = indexOf(spec, '?', startIndex, endIndex); if (questionMarkIndex >= 0) { if ((locationStartIndex >= 0) && (locationEndIndex < 0)) { // The substring of characters after the double-slash and up to, but not // including, the question mark "?" character is the network location/login // (<net_loc>) of the URL. locationEndIndex = questionMarkIndex; startIndex = questionMarkIndex; } url.query_ = spec.substring(questionMarkIndex + 1, endIndex); endIndex = questionMarkIndex; } // Section 2.4.5: Parsing the Parameters // // If the parse string contains a semicolon ";" character, then the // substring after the first (left-most) semicolon ";" and up to the end // of the parse string is the parameters (<params>). If the semicolon // is the last character, or no semicolon is present, then <params> is // empty. The matched substring, including the semicolon character, is // removed from the parse string before continuing. final int semicolonIndex = indexOf(spec, ';', startIndex, endIndex); if (semicolonIndex >= 0) { if ((locationStartIndex >= 0) && (locationEndIndex < 0)) { // The substring of characters after the double-slash and up to, but not // including, the semicolon ";" character is the network location/login // (<net_loc>) of the URL. locationEndIndex = semicolonIndex; startIndex = semicolonIndex; } url.parameters_ = spec.substring(semicolonIndex + 1, endIndex); endIndex = semicolonIndex; } // Section 2.4.6: Parsing the Path // // After the above steps, all that is left of the parse string is the // URL <path> and the slash "/" that may precede it. Even though the // initial slash is not part of the URL path, the parser must remember // whether or not it was present so that later processes can // differentiate between relative and absolute paths. Often this is // done by simply storing the preceding slash along with the path. if ((locationStartIndex >= 0) && (locationEndIndex < 0)) { // The entire remaining parse string is assigned to the network // location/login (<net_loc>) of the URL. locationEndIndex = endIndex; } else if (startIndex < endIndex) { url.path_ = spec.substring(startIndex, endIndex); } // Set the network location/login (<net_loc>) of the URL. if ((locationStartIndex >= 0) && (locationEndIndex >= 0)) { url.location_ = spec.substring(locationStartIndex, locationEndIndex); } return url; } /* * Returns true if specified string is a valid scheme name. */ private static boolean isValidScheme(final String scheme) { final int length = scheme.length(); if (length < 1) { return false; } char c = scheme.charAt(0); if (!Character.isLetter(c)) { return false; } for (int i = 1; i < length; i++) { c = scheme.charAt(i); if (!Character.isLetterOrDigit(c) && c != '.' && c != '+' && c != '-') { return false; } } return true; } /** * Resolves a given relative URL against a base URL using the algorithm * depicted in <a href="http://www.faqs.org/rfcs/rfc1808.html">RFC1808</a>: * * Section 4: Resolving Relative URLs * * This section describes an example algorithm for resolving URLs within * a context in which the URLs may be relative, such that the result is * always a URL in absolute form. Although this algorithm cannot * guarantee that the resulting URL will equal that intended by the * original author, it does guarantee that any valid URL (relative or * absolute) can be consistently transformed to an absolute form given a * valid base URL. * * @param baseUrl The base URL in which to resolve the specification. * @param relativeUrl The relative URL to resolve against the base URL. * @return the resolved specification. */ private static Url resolveUrl(final Url baseUrl, final String relativeUrl) { final Url url = parseUrl(relativeUrl); // Step 1: The base URL is established according to the rules of // Section 3. If the base URL is the empty string (unknown), // the embedded URL is interpreted as an absolute URL and // we are done. if (baseUrl == null) { return url; } // Step 2: Both the base and embedded URLs are parsed into their // component parts as described in Section 2.4. // a) If the embedded URL is entirely empty, it inherits the // entire base URL (i.e., is set equal to the base URL) // and we are done. if (relativeUrl.length() == 0) { return new Url(baseUrl); } // b) If the embedded URL starts with a scheme name, it is // interpreted as an absolute URL and we are done. if (url.scheme_ != null) { return url; } // c) Otherwise, the embedded URL inherits the scheme of // the base URL. url.scheme_ = baseUrl.scheme_; // Step 3: If the embedded URL's <net_loc> is non-empty, we skip to // Step 7. Otherwise, the embedded URL inherits the <net_loc> // (if any) of the base URL. if (url.location_ != null) { return url; } url.location_ = baseUrl.location_; // Step 4: If the embedded URL path is preceded by a slash "/", the // path is not relative and we skip to Step 7. if ((url.path_ != null) && ((url.path_.length() > 0) && ('/' == url.path_.charAt(0)))) { url.path_ = removeLeadingSlashPoints(url.path_); return url; } // Step 5: If the embedded URL path is empty (and not preceded by a // slash), then the embedded URL inherits the base URL path, // and if (url.path_ == null) { url.path_ = baseUrl.path_; // a) if the embedded URL's <params> is non-empty, we skip to // step 7; otherwise, it inherits the <params> of the base // URL (if any) and if (url.parameters_ != null) { return url; } url.parameters_ = baseUrl.parameters_; // b) if the embedded URL's <query> is non-empty, we skip to // step 7; otherwise, it inherits the <query> of the base // URL (if any) and we skip to step 7. if (url.query_ != null) { return url; } url.query_ = baseUrl.query_; return url; } // Step 6: The last segment of the base URL's path (anything // following the rightmost slash "/", or the entire path if no // slash is present) is removed and the embedded URL's path is // appended in its place. The following operations are // then applied, in order, to the new path: final String basePath = baseUrl.path_; String path = ""; if (basePath != null) { final int lastSlashIndex = basePath.lastIndexOf('/'); if (lastSlashIndex >= 0) { path = basePath.substring(0, lastSlashIndex + 1); } } else { path = "/"; } path = path.concat(url.path_); // a) All occurrences of "./", where "." is a complete path // segment, are removed. int pathSegmentIndex; while ((pathSegmentIndex = path.indexOf("/./")) >= 0) { path = path.substring(0, pathSegmentIndex + 1).concat(path.substring(pathSegmentIndex + 3)); } // b) If the path ends with "." as a complete path segment, // that "." is removed. if (path.endsWith("/.")) { path = path.substring(0, path.length() - 1); } // c) All occurrences of "<segment>/../", where <segment> is a // complete path segment not equal to "..", are removed. // Removal of these path segments is performed iteratively, // removing the leftmost matching pattern on each iteration, // until no matching pattern remains. while ((pathSegmentIndex = path.indexOf("/../")) > 0) { final String pathSegment = path.substring(0, pathSegmentIndex); final int slashIndex = pathSegment.lastIndexOf('/'); if (slashIndex < 0) { continue; } if (!"..".equals(pathSegment.substring(slashIndex))) { path = path.substring(0, slashIndex + 1).concat(path.substring(pathSegmentIndex + 4)); } } // d) If the path ends with "<segment>/..", where <segment> is a // complete path segment not equal to "..", that // "<segment>/.." is removed. if (path.endsWith("/..")) { final String pathSegment = path.substring(0, path.length() - 3); final int slashIndex = pathSegment.lastIndexOf('/'); if (slashIndex >= 0) { path = path.substring(0, slashIndex + 1); } } path = removeLeadingSlashPoints(path); url.path_ = path; // Step 7: The resulting URL components, including any inherited from // the base URL, are recombined to give the absolute form of // the embedded URL. return url; } /** * "/.." at the beginning should be removed as browsers do (not in RFC) */ private static String removeLeadingSlashPoints(String path) { while (path.startsWith("/..")) { path = path.substring(3); } return path; } /** * Class <tt>Url</tt> represents a Uniform Resource Locator. * * @author Martin Tamme */ private static class Url { String scheme_; String location_; String path_; String parameters_; String query_; String fragment_; /** * Creates a <tt>Url</tt> object. */ public Url() { } /** * Creates a <tt>Url</tt> object from the specified * <tt>Url</tt> object. * * @param url a <tt>Url</tt> object. */ public Url(final Url url) { scheme_ = url.scheme_; location_ = url.location_; path_ = url.path_; parameters_ = url.parameters_; query_ = url.query_; fragment_ = url.fragment_; } /** * Returns a string representation of the <tt>Url</tt> object. * * @return a string representation of the <tt>Url</tt> object. */ @Override public String toString() { final StringBuilder sb = new StringBuilder(); if (scheme_ != null) { sb.append(scheme_); sb.append(':'); } if (location_ != null) { sb.append("//"); sb.append(location_); } if (path_ != null) { sb.append(path_); } if (parameters_ != null) { sb.append(';'); sb.append(parameters_); } if (query_ != null) { sb.append('?'); sb.append(query_); } if (fragment_ != null) { sb.append('#'); sb.append(fragment_); } return sb.toString(); } } }
Java
package edu.uci.ics.crawler4j.url; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class TLDList { private final String tldNamesFileName = "tld-names.txt"; private Set<String> tldSet = new HashSet<>(); private static TLDList instance = new TLDList(); private TLDList() { try { InputStream stream = this.getClass().getClassLoader().getResourceAsStream(tldNamesFileName); if (stream == null) { System.err.println("Couldn't find " + tldNamesFileName); System.exit(-1); } BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.isEmpty() || line.startsWith("//")) { continue; } tldSet.add(line); } reader.close(); } catch (Exception e) { e.printStackTrace(); } } public static TLDList getInstance() { return instance; } public boolean contains(String str) { return tldSet.contains(str); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * frmAsigarSeccion.java * * Created on 16/02/2011, 04:11:50 PM */ package Principal; import Clases.Seccion; import java.awt.Frame; import javax.swing.JOptionPane; public class frmAsigarSeccion extends javax.swing.JFrame { /** Creates new form frmAsigarSeccion */ public frmAsigarSeccion() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" // desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); txtNumSec = new javax.swing.JTextField(); bAceptar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setAlwaysOnTop(true); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); getContentPane().setLayout(null); jLabel1.setText("Ingrese Numero de Seccion"); getContentPane().add(jLabel1); jLabel1.setBounds(100, 30, 180, 40); txtNumSec.setHorizontalAlignment(javax.swing.JTextField.CENTER); txtNumSec.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtNumSecKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txtNumSecKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtNumSecKeyTyped(evt); } }); getContentPane().add(txtNumSec); txtNumSec.setBounds(110, 80, 120, 40); bAceptar.setText("Aceptar"); bAceptar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bAceptarActionPerformed(evt); } }); getContentPane().add(bAceptar); bAceptar.setBounds(120, 140, 100, 30); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit() .getScreenSize(); setBounds((screenSize.width - 361) / 2, (screenSize.height - 281) / 2, 361, 281); }// </editor-fold>//GEN-END:initComponents private void bAceptarActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bAceptarActionPerformed // TODO add your handling code here: if (txtNumSec.getText().equals("")) { JOptionPane.showMessageDialog(new Frame(), "Ingrese Numero de Sección"); } else { frmInicial.seccion.setNumeroSeccion(txtNumSec.getName()); JOptionPane.showMessageDialog(new Frame(), "Seccion Creada"); dispose(); } }// GEN-LAST:event_bAceptarActionPerformed private void txtNumSecKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_txtNumSecKeyPressed }// GEN-LAST:event_txtNumSecKeyPressed private void txtNumSecKeyTyped(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_txtNumSecKeyTyped // TODO add your handling code here: }// GEN-LAST:event_txtNumSecKeyTyped private void txtNumSecKeyReleased(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_txtNumSecKeyReleased // TODO add your handling code here: char c; c = evt.getKeyChar(); if (!(c < '0' || c > '9')) { evt.consume();// ignora el caracter digitado } else { JOptionPane.showMessageDialog(new Frame(), "Solo numeros", "Error", JOptionPane.INFORMATION_MESSAGE); } }// GEN-LAST:event_txtNumSecKeyReleased /** * @param args * the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new frmAsigarSeccion().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bAceptar; private javax.swing.JLabel jLabel1; private javax.swing.JTextField txtNumSec; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * frmAsigProfe.java * * Created on 16/02/2011, 04:38:41 PM */ package Principal; import java.awt.Frame; import javax.swing.JOptionPane; import Clases.Profesor; import Clases.Seccion; /** * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI * Builder, which is free for non-commercial use. If Jigloo is being used * commercially (ie, by a corporation, company or business for any purpose * whatever) then you should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. Use of Jigloo implies * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR * ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class frmAsigProfe extends javax.swing.JFrame { { // Set Look & Feel try { javax.swing.UIManager .setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel"); } catch (Exception e) { e.printStackTrace(); } } public frmAsigProfe() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" // desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); txtTitulo = new javax.swing.JTextField(); txtApellido = new javax.swing.JTextField(); txtNombre = new javax.swing.JTextField(); txtCedula = new javax.swing.JTextField(); bAgregar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setAlwaysOnTop(true); getContentPane().setLayout(null); jLabel1.setText("Cedula"); getContentPane().add(jLabel1); jLabel1.setBounds(162, 77, 70, 20); jLabel2.setText("Nombre"); getContentPane().add(jLabel2); jLabel2.setBounds(155, 127, 70, 20); jLabel3.setText("Apellido"); getContentPane().add(jLabel3); jLabel3.setBounds(154, 173, 88, 20); jLabel4.setText("Titulo Acedemico"); getContentPane().add(jLabel4); jLabel4.setBounds(91, 217, 145, 20); jLabel5.setText("Registro de Profesor"); getContentPane().add(jLabel5); jLabel5.setBounds(208, 20, 134, 15); jLabel5.setBackground(new java.awt.Color(255, 255, 255)); getContentPane().add(txtTitulo); txtTitulo.setBounds(221, 218, 170, 20); txtApellido.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtApellidoActionPerformed(evt); } }); getContentPane().add(txtApellido); txtApellido.setBounds(221, 174, 170, 20); getContentPane().add(txtNombre); txtNombre.setBounds(221, 128, 170, 20); txtCedula.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtCedulaActionPerformed(evt); } }); getContentPane().add(txtCedula); txtCedula.setBounds(221, 78, 170, 20); bAgregar.setText("Agregar y salir"); bAgregar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bAgregarActionPerformed(evt); } }); getContentPane().add(bAgregar); bAgregar.setBounds(170, 290, 130, 50); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit() .getScreenSize(); setBounds((screenSize.width - 489) / 2, (screenSize.height - 405) / 2, 489, 405); }// </editor-fold>//GEN-END:initComponents private void bAgregarActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bAgregarActionPerformed // TODO add your handling code here: if (!txtCedula.getText().isEmpty() && !txtNombre.getText().isEmpty() && !txtApellido.getText().isEmpty() && !txtTitulo.getText().isEmpty()) { frmInicial.profesor = new Profesor(txtNombre.getText(), txtApellido.getText(), txtCedula.getText(), txtTitulo.getText()); // sec.AsignarProfesor(profe); frmInicial.seccion.AsignarProfesor(frmInicial.profesor); JOptionPane.showMessageDialog(new Frame(), "Profesor Asignado"); dispose(); } else { JOptionPane.showMessageDialog(new Frame(), "Hay campos en blanco, por favor verifique"); } }// GEN-LAST:event_bAgregarActionPerformed private void txtApellidoActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_txtApellidoActionPerformed // TODO add your handling code here: }// GEN-LAST:event_txtApellidoActionPerformed private void txtCedulaActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_txtCedulaActionPerformed // TODO add your handling code here: }// GEN-LAST:event_txtCedulaActionPerformed /** * @param args * the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new frmAsigProfe().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bAgregar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JTextField txtApellido; private javax.swing.JTextField txtCedula; private javax.swing.JTextField txtNombre; private javax.swing.JTextField txtTitulo; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* Nicolas D'Amelio C.I. 19.637.704 Daniel Santeliz C.I. 19.696.020 Nellymer Montero C.I. 20.926.114 Leandro Oliva C.I.20.187.193 */ /* Nicolas D'Amelio C.I. 19.637.704 Daniel Santeliz C.I. 19.696.020 Nellymer Montero C.I. 20.926.114 Leandro Oliva C.I.20.187.193 */ package Principal; /* Nicolas D'Amelio C.I. 19.637.704 Daniel Santeliz C.I. 19.696.020 Nellymer Montero C.I. 20.926.114 Leandro Oliva C.I.20.187.193 */ import Clases.Estudiante; import Clases.Profesor; import Clases.Seccion; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { /** * @param args * the command line arguments */ public static void main(String[] args) throws IOException { int opcion = 0; boolean validarSeccion = false; boolean validarProfesor = false; boolean validarInscritos = false; boolean validarPruebas = false; boolean continuar = true; BufferedReader tecla = new BufferedReader(new InputStreamReader( System.in)); Seccion seccion = null; Profesor profesor; do { System.out .println("==========================================================="); System.out .println("================== Menu de Opciones ====================="); System.out .println(" 1- Crear Seccion (puede hacerse 1 vez)"); System.out .println(" 2- Asignar Profesor a la seccion (puede hacerse 1 vez)"); System.out .println(" 3- Inscribir Estudiante "); System.out .println(" 4- Retirar Estudiante "); System.out .println(" 5- Buscar Estudiante "); System.out .println(" 6- Aplicar Evaluaciones (puede hacerse 1 vez)"); System.out .println(" 7- Listar Estudiantes ordenado por Cedula "); System.out .println(" 8- Listar Estudiantes ordenado por Nota Final "); System.out .println(" 9- Listar Estudiantes Aprobados "); System.out .println(" 10- Listar Estudiantes Aplazados "); System.out .println(" 11- Promedio "); System.out .println(" 12- Salir "); System.out .println("==========================================================="); System.out .println("================== Presione un numero segun la opcion======"); while (continuar) { try { opcion = Integer.parseInt(tecla.readLine()); break; } catch (NumberFormatException e) { System.out .println("Error, Selecione un numero en el rango por favor"); } } switch (opcion) { case 1: { if (validarSeccion == false) { String numeroSeccion = ""; validarSeccion = true; System.out.println("Ingrese el numero de la Seccion:"); while (continuar) { try { numeroSeccion = tecla.readLine(); break; } catch (NumberFormatException e) { System.out .println("Error, numero invalido, intente de nuevo"); } } seccion = new Seccion(numeroSeccion); } else { System.out .println("Seccion creada, pase al siguiente paso"); } tecla.readLine(); } break; case 2: { if (validarProfesor == false) { String nombre, apellido, titulo, cedula; System.out .println("Ingrese los siguientes datos para el profesor: "); System.out .println("==============================================="); System.out.println("Nombre: "); nombre = tecla.readLine(); System.out.println("Apellido"); apellido = tecla.readLine(); System.out.println("cedula: "); cedula = tecla.readLine(); System.out.println("Titulo Academico:"); titulo = tecla.readLine(); validarProfesor = true; profesor = new Profesor(nombre, apellido, cedula, titulo); seccion.AsignarProfesor(profesor); } else { System.out .println("Profesor asignado, pase al siguiente paso"); } tecla.readLine(); } break; case 3: { if (validarSeccion == true) { validarInscritos = true; String nombre, apellido, cedula; String resp = "s"; while (resp.toLowerCase().equals("s")) { System.out .println("Ingrese los siguientes datos para el Estudiante: "); System.out .println("================================================ "); System.out.println("cedula: "); cedula = tecla.readLine(); System.out.println("nombre: "); nombre = tecla.readLine(); System.out.println("apellido: "); apellido = tecla.readLine(); Estudiante estudiante = new Estudiante(nombre, apellido, cedula); seccion.InscribirEstrudiante(estudiante); System.out .println("Desea incribir otro Estudiante s o n"); resp = tecla.readLine(); } } else { System.out .println("Error, debe crear seccion y asignar profesor."); tecla.readLine(); } } break; case 4: { if (validarInscritos) { String cedula; System.out .println("cedula del Estudiante q desea retirar: "); cedula = tecla.readLine(); seccion.RetirarEstudiante(cedula); } else { System.out .println("No existen estudiantes inscritos o cedula no existe"); } tecla.readLine(); } break; case 5: { if (validarInscritos) { String cedula; Estudiante estudiante; System.out .println("cedula del Estudiante q desea buscar: "); cedula = tecla.readLine(); seccion.BuscarEstudiante(cedula); } else { System.out .println("No existen estudiantes inscritos o cedula no existe"); } tecla.readLine(); } break; case 6: { if (validarInscritos) { if (validarPruebas == false) { validarPruebas = true; seccion.AplicarEvaluaciones(); } else { System.out .println("Las evaluaciones ya fueron aplicadas, seguir al siguiente paso"); } } else { System.out .println("No hay estudiantes inscritos, verifique si se salto pasos anteriores"); } tecla.readLine(); } break; case 7: { if (validarInscritos) { seccion.ListarEstudiantesCedula(); } else { System.out .println("No hay estudiantes inscritos, verifique si se salto pasos anteriores"); } tecla.readLine(); } break; case 8: { if (validarPruebas) { seccion.ListarEstudiantesNota(); } else { System.out .println("Debe aplicar las evaluaciones para emitir un listdo, por favor verifique"); } tecla.readLine(); } break; case 9: { if (validarPruebas) { seccion.ListarAprobados(); } else { System.out .println("Debe aplicar las evaluaciones para emitir un listdo, por favor verifique"); } tecla.readLine(); } break; case 10: { if (validarPruebas) { seccion.ListarReprobados(); } else { System.out .println("Debe aplicar las evaluaciones para emitir un listdo, por favor verifique"); } tecla.readLine(); } break; case 11: { if (validarPruebas) { seccion.ListaPromedio(); } else { System.out .println("Debe aplicar las evaluaciones para emitir un listdo, por favor verifique"); } tecla.readLine(); } break; } } while (opcion != 12); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * frmInicial.java * * Created on 16/02/2011, 04:00:19 PM */ /* */ package Principal; /* Nicolas D'Amelio C.I. 19.637.704 Daniel Santeliz C.I. 19.696.020 Nellymer Montero C.I. 20.926.114 Leandro Oliva C.I.20.187.193 */ import Clases.*; import java.awt.Frame; import javax.swing.JButton; import javax.swing.JOptionPane; /** * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI * Builder, which is free for non-commercial use. If Jigloo is being used * commercially (ie, by a corporation, company or business for any purpose * whatever) then you should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. Use of Jigloo implies * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR * ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class frmInicial extends javax.swing.JFrame { static Seccion seccion = new Seccion(); static Profesor profesor; static Estudiante estudiante; /** Creates new form frmInicial */ public frmInicial() { initComponents(); bAsigProfe.setVisible(false); bInscEstu.setVisible(false); btnAplicarEvaluaciones.setVisible(false); btnAplicarEvaluaciones.setVisible(false); btnPromedio.setVisible(false); btnListado.setVisible(false); labelPromedio.setVisible(false); txtPromedio.setVisible(false); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" // <editor-fold defaultstate="collapsed" // desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { bAsigSeccion = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); bAsigProfe = new javax.swing.JButton(); bInscEstu = new javax.swing.JButton(); btnAplicarEvaluaciones = new javax.swing.JButton(); btnListado = new javax.swing.JButton(); btnPromedio = new javax.swing.JButton(); txtPromedio = new javax.swing.JTextField(); labelPromedio = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); bAsigSeccion.setText("Asignar Seccion"); bAsigSeccion.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bAsigSeccionActionPerformed(evt); } }); getContentPane().add(bAsigSeccion); bAsigSeccion.setBounds(210, 60, 160, 49); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Menu de opciones"); getContentPane().add(jLabel1); jLabel1.setBounds(180, 20, 220, 14); bAsigProfe.setText("Asignar Profesor"); bAsigProfe.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bAsigProfeActionPerformed(evt); } }); getContentPane().add(bAsigProfe); bAsigProfe.setBounds(210, 60, 160, 50); bInscEstu.setText("Inscribir Estudiantes"); bInscEstu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bInscEstuActionPerformed(evt); } }); getContentPane().add(bInscEstu); bInscEstu.setBounds(210, 60, 160, 50); btnAplicarEvaluaciones.setText("Aplicar Evaluaciones"); btnAplicarEvaluaciones .addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAplicarEvaluacionesActionPerformed(evt); } }); getContentPane().add(btnAplicarEvaluaciones); btnAplicarEvaluaciones.setBounds(210, 110, 160, 49); btnListado.setText("Listado Estudiantes"); btnListado.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnListadoActionPerformed(evt); } }); getContentPane().add(btnListado); btnListado.setBounds(210, 60, 160, 50); btnPromedio.setText("Promedio de notas"); btnPromedio.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPromedioActionPerformed(evt); } }); getContentPane().add(btnPromedio); btnPromedio.setBounds(210, 160, 160, 50); txtPromedio.setEditable(false); txtPromedio.setHorizontalAlignment(javax.swing.JTextField.CENTER); getContentPane().add(txtPromedio); txtPromedio.setBounds(330, 230, 140, 40); labelPromedio.setText("EL promedio de notas es:"); getContentPane().add(labelPromedio); labelPromedio.setBounds(190, 230, 150, 50); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit() .getScreenSize(); setBounds((screenSize.width - 616) / 2, (screenSize.height - 438) / 2, 616, 438); }// </editor-fold>//GEN-END:initComponents private void bAsigSeccionActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bAsigSeccionActionPerformed // TODO add your handling code here: frmAsigarSeccion as = new frmAsigarSeccion(); as.show(); bAsigSeccion.setVisible(false); bAsigProfe.setVisible(true); }// GEN-LAST:event_bAsigSeccionActionPerformed private void bAsigProfeActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bAsigProfeActionPerformed // TODO add your handling code here: // System.out.println(seccion.getNumeroSeccion()); frmAsigProfe ap = new frmAsigProfe(); ap.show(); bAsigProfe.setVisible(false); bInscEstu.setVisible(true); btnAplicarEvaluaciones.setVisible(true); }// GEN-LAST:event_bAsigProfeActionPerformed private void bInscEstuActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bInscEstuActionPerformed // TODO add your handling code here: frmInscribir ie = new frmInscribir(); ie.show(); bInscEstu.setVisible(true); btnAplicarEvaluaciones.setVisible(true); }// GEN-LAST:event_bInscEstuActionPerformed private void btnAplicarEvaluacionesActionPerformed( java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnAplicarEvaluacionesActionPerformed // TODO add your handling code here: if (seccion.getEstudiantes().size() > 0) { seccion.AplicarEvaluaciones(); JOptionPane.showMessageDialog(new Frame(), "Las evaluaciones fueron aplicadas exitosamente"); btnListado.setVisible(true); btnAplicarEvaluaciones.setVisible(false); btnPromedio.setVisible(true); bInscEstu.setVisible(false); } else { JOptionPane .showMessageDialog(new Frame(), "No hay estudiantes inscritos, no se puede realizar evaluaciones"); } }// GEN-LAST:event_btnAplicarEvaluacionesActionPerformed private void btnListadoActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnListadoActionPerformed // TODO add your handling code here: frmListados listado = new frmListados(); listado.show(); }// GEN-LAST:event_btnListadoActionPerformed private void btnPromedioActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnPromedioActionPerformed // TODO add your handling code here: labelPromedio.setVisible(true); txtPromedio.setVisible(true); txtPromedio.setText(String.valueOf(seccion.ListaPromedio())); }// GEN-LAST:event_btnPromedioActionPerformed /** * @param args * the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new frmInicial().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bAsigProfe; private javax.swing.JButton bAsigSeccion; private javax.swing.JButton bInscEstu; private javax.swing.JButton btnAplicarEvaluaciones; private javax.swing.JButton btnListado; private javax.swing.JButton btnPromedio; private javax.swing.JLabel jLabel1; private javax.swing.JLabel labelPromedio; private javax.swing.JTextField txtPromedio; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * frmListados.java * * Created on 20/02/2011, 08:56:32 AM */ package Principal; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class frmListados extends javax.swing.JFrame { /** Creates new form frmListados */ public frmListados() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); tabla = new javax.swing.JTable(); btnListarCedula = new javax.swing.JButton(); btnNotaFinal = new javax.swing.JButton(); btnAprobados = new javax.swing.JButton(); btnReprobados = new javax.swing.JButton(); btnSalir = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(null); tabla.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Nombre", "Apellido", "Cedula", "Nota Final" } )); jScrollPane1.setViewportView(tabla); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(10, 10, 510, 300); btnListarCedula.setText("Ordenar por Cedula"); btnListarCedula.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnListarCedulaActionPerformed(evt); } }); getContentPane().add(btnListarCedula); btnListarCedula.setBounds(20, 330, 150, 40); btnNotaFinal.setText("Ordenar por Nota Final"); btnNotaFinal.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNotaFinalActionPerformed(evt); } }); getContentPane().add(btnNotaFinal); btnNotaFinal.setBounds(190, 330, 180, 40); btnAprobados.setText("Aprobados"); btnAprobados.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAprobadosActionPerformed(evt); } }); getContentPane().add(btnAprobados); btnAprobados.setBounds(20, 380, 150, 40); btnReprobados.setText("Reprobados"); btnReprobados.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnReprobadosActionPerformed(evt); } }); getContentPane().add(btnReprobados); btnReprobados.setBounds(190, 380, 180, 40); btnSalir.setText("Salir"); btnSalir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSalirActionPerformed(evt); } }); getContentPane().add(btnSalir); btnSalir.setBounds(390, 330, 120, 40); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-546)/2, (screenSize.height-476)/2, 546, 476); }// </editor-fold>//GEN-END:initComponents private void btnListarCedulaActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnListarCedulaActionPerformed // TODO add your handling code here: for (int e = 0; e < frmInicial.seccion.getEstudiantes().size(); e++) { tabla.setValueAt("", e, 0); tabla.setValueAt("", e, 1); tabla.setValueAt("", e, 2); tabla.setValueAt("", e, 3); } frmInicial.seccion.ListarEstudiantesCedula(); for (int i = 0; i < frmInicial.seccion.getEstudiantes().size(); i++) { tabla.setValueAt(frmInicial.seccion.getEstudiantes().elementAt(i) .getNombre(), i, 0); tabla.setValueAt(frmInicial.seccion.getEstudiantes().elementAt(i) .getApellido(), i, 1); tabla.setValueAt(frmInicial.seccion.getEstudiantes().elementAt(i) .getCedula(), i, 2); tabla.setValueAt(frmInicial.seccion.getEstudiantes().elementAt(i) .getNotaFinal(), i, 3); } }// GEN-LAST:event_btnListarCedulaActionPerformed private void btnNotaFinalActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnNotaFinalActionPerformed // TODO add your handling code here: for (int e = 0; e < frmInicial.seccion.getEstudiantes().size(); e++) { tabla.setValueAt("", e, 0); tabla.setValueAt("", e, 1); tabla.setValueAt("", e, 2); tabla.setValueAt("", e, 3); } frmInicial.seccion.ListarEstudiantesNota(); for (int i = 0; i < frmInicial.seccion.getEstudiantes().size(); i++) { tabla.setValueAt(frmInicial.seccion.getEstudiantes().elementAt(i) .getNombre(), i, 0); tabla.setValueAt(frmInicial.seccion.getEstudiantes().elementAt(i) .getApellido(), i, 1); tabla.setValueAt(frmInicial.seccion.getEstudiantes().elementAt(i) .getCedula(), i, 2); tabla.setValueAt(frmInicial.seccion.getEstudiantes().elementAt(i) .getNotaFinal(), i, 3); } }// GEN-LAST:event_btnNotaFinalActionPerformed private void btnAprobadosActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnAprobadosActionPerformed // TODO add your handling code here: for (int e = 0; e < frmInicial.seccion.getEstudiantes().size(); e++) { tabla.setValueAt("", e, 0); tabla.setValueAt("", e, 1); tabla.setValueAt("", e, 2); tabla.setValueAt("", e, 3); } frmInicial.seccion.ListarAprobados(); int indice = 0; for (int i = 0; i < frmInicial.seccion.getEstudiantes().size(); i++) { if (frmInicial.seccion.getEstudiantes().elementAt(i).getNotaFinal() > 10) { tabla.setValueAt( frmInicial.seccion.getEstudiantes().elementAt(i) .getNombre(), indice, 0); tabla.setValueAt( frmInicial.seccion.getEstudiantes().elementAt(i) .getApellido(), indice, 1); tabla.setValueAt( frmInicial.seccion.getEstudiantes().elementAt(i) .getCedula(), indice, 2); tabla.setValueAt( frmInicial.seccion.getEstudiantes().elementAt(i) .getNotaFinal(), indice, 3); indice++; } } }// GEN-LAST:event_btnAprobadosActionPerformed private void btnReprobadosActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnReprobadosActionPerformed // TODO add your handling code here: for (int e = 0; e < frmInicial.seccion.getEstudiantes().size(); e++) { tabla.setValueAt("", e, 0); tabla.setValueAt("", e, 1); tabla.setValueAt("", e, 2); tabla.setValueAt("", e, 3); } frmInicial.seccion.ListarReprobados(); int indice = 0; for (int i = 0; i < frmInicial.seccion.getEstudiantes().size(); i++) { if (frmInicial.seccion.getEstudiantes().elementAt(i).getNotaFinal() < 10) { tabla.setValueAt( frmInicial.seccion.getEstudiantes().elementAt(i) .getNombre(), indice, 0); tabla.setValueAt( frmInicial.seccion.getEstudiantes().elementAt(i) .getApellido(), indice, 1); tabla.setValueAt( frmInicial.seccion.getEstudiantes().elementAt(i) .getCedula(), indice, 2); tabla.setValueAt( frmInicial.seccion.getEstudiantes().elementAt(i) .getNotaFinal(), indice, 3); indice++; } } }// GEN-LAST:event_btnReprobadosActionPerformed private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnSalirActionPerformed // TODO add your handling code here: dispose(); }// GEN-LAST:event_btnSalirActionPerformed /** * @param args * the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new frmListados().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAprobados; private javax.swing.JButton btnListarCedula; private javax.swing.JButton btnNotaFinal; private javax.swing.JButton btnReprobados; private javax.swing.JButton btnSalir; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable tabla; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * frmInscribir.java * * Created on 17/02/2011, 10:08:26 AM */ package Principal; import Clases.Estudiante; import Clases.Seccion; import java.awt.Frame; import javax.swing.JOptionPane; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class frmInscribir extends javax.swing.JFrame { /** Creates new form frmInscribir */ public frmInscribir() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" // desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); txtCedula = new javax.swing.JTextField(); txtNombre = new javax.swing.JTextField(); txtApellido = new javax.swing.JTextField(); bInscribir = new javax.swing.JButton(); bCancelar = new javax.swing.JButton(); bSalir = new javax.swing.JButton(); bRetirar = new javax.swing.JButton(); bBuscar = new javax.swing.JButton(); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object[][] { { null, null, null, null }, { null, null, null, null }, { null, null, null, null }, { null, null, null, null } }, new String[] { "Title 1", "Title 2", "Title 3", "Title 4" })); jScrollPane1.setViewportView(jTable1); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Registro de Alumnos"); jLabel2.setText("Nombre:"); jLabel3.setText("Apellido:"); jLabel4.setText("Cédula:"); txtCedula.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtCedulaActionPerformed(evt); } }); txtApellido.setText(" "); bInscribir.setText("Inscribir"); bInscribir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bInscribirActionPerformed(evt); } }); bCancelar.setText("Cancelar"); bCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bCancelarActionPerformed(evt); } }); bSalir.setText("Salir"); bSalir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bSalirActionPerformed(evt); } }); bRetirar.setText("Retirar"); bRetirar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bRetirarActionPerformed(evt); } }); bBuscar.setText("Buscar"); bBuscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bBuscarActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout( getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addGap(100, 100, 100) .addComponent( jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup( layout.createSequentialGroup() .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addGap(38, 38, 38) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.TRAILING) .addComponent( jLabel2) .addComponent( jLabel3) .addComponent( jLabel4, javax.swing.GroupLayout.Alignment.LEADING))) .addGroup( layout.createSequentialGroup() .addGap(54, 54, 54) .addComponent( bInscribir))) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addComponent( bCancelar) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( bRetirar) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( bSalir)) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent( txtNombre, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE) .addGroup( layout.createSequentialGroup() .addComponent( txtCedula, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent( bBuscar)) .addComponent( txtApellido))))) .addContainerGap(64, Short.MAX_VALUE))); layout.setVerticalGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addGap(29, 29, 29) .addComponent(jLabel1) .addGap(39, 39, 39) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent( txtCedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(bBuscar)) .addGap(30, 30, 30) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent( txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent( txtApellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(39, 39, 39) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(bInscribir) .addComponent(bCancelar) .addComponent(bRetirar) .addComponent(bSalir)) .addContainerGap(37, Short.MAX_VALUE))); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit() .getScreenSize(); this.setBounds(0, 0, 423, 329); }// </editor-fold>//GEN-END:initComponents private void txtCedulaActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_txtCedulaActionPerformed // TODO add your handling code here: }// GEN-LAST:event_txtCedulaActionPerformed private void bSalirActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bSalirActionPerformed // TODO add your handling code here: dispose(); }// GEN-LAST:event_bSalirActionPerformed private void bInscribirActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bInscribirActionPerformed // TODO add your handling code here: Estudiante estudiante; if (!txtCedula.getText().isEmpty() && !txtNombre.getText().isEmpty() && !txtApellido.getText().isEmpty()) { estudiante = new Estudiante(txtNombre.getText(), txtApellido.getText(), txtCedula.getText()); frmInicial.seccion.InscribirEstrudiante(estudiante); txtApellido.setText(""); txtCedula.setText(""); txtNombre.setText(""); } else { JOptionPane.showMessageDialog(new Frame(), "Hay campos en blanco, por favor verifique"); } }// GEN-LAST:event_bInscribirActionPerformed private void bBuscarActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bBuscarActionPerformed // TODO add your handling code here: int existe = 0; if (!txtCedula.getText().equals("")) { txtNombre.setText(""); txtApellido.setText(""); existe = frmInicial.seccion.BuscarEstudiante(txtCedula.getText()); System.out.println(existe); if (existe >= 0) { txtNombre.setText(frmInicial.seccion.getEstudiantes() .elementAt(existe).getNombre()); txtApellido.setText(frmInicial.seccion.getEstudiantes() .elementAt(existe).getApellido()); } } else { JOptionPane.showMessageDialog(new Frame(), "Introduzca una cedula"); } }// GEN-LAST:event_bBuscarActionPerformed private void bCancelarActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bCancelarActionPerformed // TODO add your handling code here: txtApellido.setText(""); txtCedula.setText(""); txtNombre.setText(""); }// GEN-LAST:event_bCancelarActionPerformed private void bRetirarActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bRetirarActionPerformed // TODO add your handling code here: if (!txtCedula.getText().equals("")) { txtNombre.setText(""); txtApellido.setText(""); frmInicial.seccion.RetirarEstudiante(txtCedula.getText()); txtCedula.setText(""); } else { JOptionPane.showMessageDialog(new Frame(), "Introduzca una cedula"); } }// GEN-LAST:event_bRetirarActionPerformed /** * @param args * the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new frmInscribir().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bBuscar; private javax.swing.JButton bCancelar; private javax.swing.JButton bInscribir; private javax.swing.JButton bRetirar; private javax.swing.JButton bSalir; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField txtApellido; private javax.swing.JTextField txtCedula; private javax.swing.JTextField txtNombre; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Clases; import java.util.ArrayList; import java.util.Vector; public class Profesor implements EvaluarEstudiantes { private String cedula, nombre, apellido, tituloAcademico; public Profesor(String nombre, String apellido, String cedula, String tituloAcademico) { this.cedula = cedula; this.nombre = nombre; this.apellido = apellido; this.tituloAcademico = tituloAcademico; } public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } public String getCedula() { return cedula; } public void setCedula(String cedula) { this.cedula = cedula; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getTituloAcademico() { return tituloAcademico; } public void setTituloAcademico(String tituloAcademico) { this.tituloAcademico = tituloAcademico; } public void EvaluarEstudiantes(Vector<Estudiante> estudiantes) { int acumulador; for (int i = 0; i < estudiantes.size(); i++) { acumulador = (estudiantes.elementAt(i).getNota1() + estudiantes.elementAt(i).getNota2() + estudiantes .elementAt(i).getNota3()) / 3; estudiantes.get(i).setNotaFinal(acumulador); if (acumulador < 10) { estudiantes.get(i).setEstado("Reprobado"); } else { estudiantes.get(i).setEstado("Aprobado"); } } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Clases; public interface PresentarEvaluaciones { public void PresentarEvaluacion(); }
Java
package Clases; import java.util.Random; public class Estudiante implements PresentarEvaluaciones{ private String cedula,nombre,apellido,estado; private int nota1,nota2,nota3,notaFinal; public Estudiante(String nombre,String apellido,String cedula) { this.nombre = nombre; this.apellido = apellido; this.cedula = cedula; } public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } public String getCedula() { return cedula; } public void setCedula(String cedula) { this.cedula = cedula; } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public int getNota1() { return nota1; } public void setNota1(int nota1) { this.nota1 = nota1; } public int getNota2() { return nota2; } public void setNota2(int nota2) { this.nota2 = nota2; } public int getNota3() { return nota3; } public void setNota3(int nota3) { this.nota3 = nota3; } public int getNotaFinal() { return notaFinal; } public void setNotaFinal(int notaFinal) { this.notaFinal = notaFinal; } public void PresentarEvaluacion() { Random r = new Random(); int acumulador; System.out.println("Alumno: "+nombre+" "+ apellido) ; System.out.println("Presentando . . ") ; nota1 = r.nextInt(21); System.out.println("Nota 1: "+ nota1); nota2 = r.nextInt(21); System.out.println("Nota 2: "+ nota2); nota3 = r.nextInt(21); System.out.println("Nota 3: "+ nota3); acumulador = (nota1 + nota2 + nota3)/3; if (acumulador< 10) { System.out.println("Reprobado"); } else { System.out.println("Aprobado"); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Clases; import java.util.Vector; public interface EvaluarEstudiantes { public void EvaluarEstudiantes(Vector<Estudiante> estudiante); }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Clases; import java.awt.Frame; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Collections; import java.util.Vector; import javax.swing.JOptionPane; public class Seccion { String numeroSeccion; Profesor profesor; Vector<Estudiante> estudiantes; public Vector<Estudiante> getEstudiantes() { return estudiantes; } public void setEstudiantes(Vector<Estudiante> estudiantes) { this.estudiantes = estudiantes; } public Profesor getProfesor() { return profesor; } public void setProfesor(Profesor profesor) { this.profesor = profesor; } public Seccion(String numeroSeccion) { this.numeroSeccion = numeroSeccion; } public Seccion() { estudiantes = new Vector<Estudiante>(); } public void AsignarProfesor(Profesor profesor) { this.profesor = profesor; System.out.println("Profesor asignado a la seccion:"); System.out.println("==============================="); System.out.println(); System.out.println("Nombre: " + profesor.getNombre()); System.out.println("Apellido:" + profesor.getApellido()); } public void InscribirEstrudiante(Estudiante estudiante) { boolean existe; existe = false; for (int i = 0; i < estudiantes.size(); i++) { if (estudiantes.elementAt(i).getCedula() .equals(estudiante.getCedula())) { existe = true; break; } } if (existe == false) { estudiantes.add(estudiante); JOptionPane.showMessageDialog(new Frame(), "Estudiante Inscrito Correctamente"); } else { JOptionPane.showMessageDialog(new Frame(), "Estudiante ya Existe"); } } public void RetirarEstudiante(String cedula) { boolean existe; existe = false; for (int i = 0; i < estudiantes.size(); i++) { if (estudiantes.elementAt(i).getCedula().equals(cedula)) { estudiantes.remove(i); JOptionPane.showMessageDialog(new Frame(), "Estudiante removido con exito"); existe = true; break; } } if (existe == false) { JOptionPane.showMessageDialog(new Frame(), "El estudiante no pudo ser removido porque no existe"); } } public int BuscarEstudiante(String cedula) { boolean existe; existe = false; int i; for (i = 0; i < estudiantes.size(); i++) { if (estudiantes.get(i).getCedula().equals(cedula)) { System.out.println("Resultado de la busqueda del estudiante"); System.out.println("======================================="); System.out.println("nombre: " + estudiantes.get(i).getNombre() + " " + estudiantes.get(i).getApellido()); existe = true; break; } } if (existe == false) { JOptionPane.showMessageDialog(new Frame(), "Estudiante no existe"); return -1; } return i; } public void AplicarEvaluaciones() { for (int i = 0; i < estudiantes.size(); i++) { estudiantes.get(i).PresentarEvaluacion(); } profesor.EvaluarEstudiantes(estudiantes); System.out.println("Los estudiantes han presentado exitosamente"); } public void ListarEstudiantesCedula() { int numeroi; int numeroj; for (int i = 0; i < estudiantes.size() - 1; ++i) { for (int j = i + 1; j < estudiantes.size(); ++j) { numeroi = Integer .parseInt(estudiantes.elementAt(i).getCedula()); numeroj = Integer .parseInt(estudiantes.elementAt(j).getCedula()); if (numeroi > numeroj) { Collections.swap(estudiantes, i, j); } } } FileWriter fichero = null; PrintWriter pw = null; try { fichero = new FileWriter("ListarCedula.txt"); pw = new PrintWriter(fichero); pw.println("Listado de persona ordenados por cedula"); pw.println("======================================="); pw.println(""); pw.println("Nombre Apellido Cedula"); for (int i = 0; i < estudiantes.size(); i++) { pw.println(estudiantes.elementAt(i).getNombre() + " " + estudiantes.elementAt(i).getApellido() + " " + estudiantes.elementAt(i).getCedula()); } } catch (Exception e) { e.printStackTrace(); } finally { try { // Nuevamente aprovechamos el finally para // asegurarnos que se cierra el fichero. if (null != fichero) { fichero.close(); } } catch (Exception e2) { e2.printStackTrace(); } } } public void ListarEstudiantesNota() { int numeroi; int numeroj; for (int i = 0; i < estudiantes.size() - 1; ++i) { for (int j = i + 1; j < estudiantes.size(); ++j) { numeroi = estudiantes.elementAt(i).getNotaFinal(); numeroj = estudiantes.elementAt(j).getNotaFinal(); if (numeroi > numeroj) { Collections.swap(estudiantes, i, j); } } } FileWriter fichero = null; PrintWriter pw = null; try { fichero = new FileWriter("ListarNotaFinal.txt"); pw = new PrintWriter(fichero); pw.println("Listado de persona ordenados por Nota final"); pw.println("======================================="); pw.println(""); pw.println("Nombre Apellido Cedula Nota Final"); for (int i = 0; i < estudiantes.size(); i++) { pw.println(estudiantes.elementAt(i).getNombre() + " " + estudiantes.elementAt(i).getApellido() + " " + estudiantes.elementAt(i).getCedula() + " " + estudiantes.elementAt(i).getNotaFinal()); } } catch (Exception e) { e.printStackTrace(); } finally { try { // Nuevamente aprovechamos el finally para // asegurarnos que se cierra el fichero. if (null != fichero) { fichero.close(); } } catch (Exception e2) { e2.printStackTrace(); } } } public void ListarAprobados() { FileWriter fichero = null; PrintWriter pw = null; try { fichero = new FileWriter("ListaAprobados.txt"); pw = new PrintWriter(fichero); pw.println("Listado de persona Aprobados"); pw.println("======================================="); pw.println(""); pw.println("Nombre Apellido Cedula Nota Final"); for (int i = 0; i < estudiantes.size(); i++) { if (estudiantes.elementAt(i).getNotaFinal() >= 10) { pw.println(estudiantes.elementAt(i).getNombre() + " " + estudiantes.elementAt(i).getApellido() + " " + estudiantes.elementAt(i).getCedula() + " " + estudiantes.elementAt(i).getNotaFinal()); } } } catch (Exception e) { e.printStackTrace(); } finally { try { // Nuevamente aprovechamos el finally para // asegurarnos que se cierra el fichero. if (null != fichero) { fichero.close(); } } catch (Exception e2) { e2.printStackTrace(); } } } public void ListarReprobados() { FileWriter fichero = null; PrintWriter pw = null; try { fichero = new FileWriter("ListaReprobados.txt"); pw = new PrintWriter(fichero); pw.println("Listado de persona Reprobados"); pw.println("======================================="); pw.println(""); pw.println("Nombre Apellido Cedula Nota Final"); for (int i = 0; i < estudiantes.size(); i++) { if (estudiantes.elementAt(i).getNotaFinal() < 10) { pw.println(estudiantes.elementAt(i).getNombre() + " " + estudiantes.elementAt(i).getApellido() + " " + estudiantes.elementAt(i).getCedula() + " " + estudiantes.elementAt(i).getNotaFinal()); } } } catch (Exception e) { e.printStackTrace(); } finally { try { // Nuevamente aprovechamos el finally para // asegurarnos que se cierra el fichero. if (null != fichero) { fichero.close(); } } catch (Exception e2) { e2.printStackTrace(); } } } public String getNumeroSeccion() { return numeroSeccion; } public void setNumeroSeccion(String numeroSeccion) { this.numeroSeccion = numeroSeccion; } public float ListaPromedio() { int acumulador; acumulador = 0; FileWriter fichero = null; PrintWriter pw = null; try { fichero = new FileWriter("Promedio.txt"); pw = new PrintWriter(fichero); pw.println("Promedio de notas"); pw.println("======================================="); pw.println(""); acumulador = 0; for (int i = 0; i < estudiantes.size(); i++) { acumulador += estudiantes.elementAt(i).getNotaFinal(); } acumulador = acumulador / estudiantes.size(); pw.println(acumulador); } catch (Exception e) { e.printStackTrace(); } finally { try { // Nuevamente aprovechamos el finally para // asegurarnos que se cierra el fichero. if (null != fichero) { fichero.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return acumulador; } } // llave de fin
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.browse.BrowseEngine; import org.dspace.browse.BrowseException; import org.dspace.browse.BrowseIndex; import org.dspace.browse.BrowseInfo; import org.dspace.browse.BrowserScope; import org.dspace.sort.SortOption; import org.dspace.sort.SortException; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.core.LogManager; /** * Servlet for browsing through indices, as they are defined in * the configuration. This class can take a wide variety of inputs from * the user interface: * * - type: the type of browse (index name) being performed * - order: (ASC | DESC) the direction for result sorting * - value: A specific value to find items around. For example the author name or subject * - month: integer specification of the month of a date browse * - year: integer specification of the year of a date browse * - starts_with: string value at which to start browsing * - vfocus: start browsing with a value of this string * - focus: integer id of the item at which to start browsing * - rpp: integer number of results per page to display * - sort_by: integer specification of the field to search on * - etal: integer number to limit multiple value items specified in config to * * @author Richard Jones * @version $Revision: 5845 $ */ public abstract class AbstractBrowserServlet extends DSpaceServlet { /** log4j category */ private static Logger log = Logger.getLogger(AbstractBrowserServlet.class); public AbstractBrowserServlet() { super(); } /** * Create a BrowserScope from the current request * * @param context The database context * @param request The servlet request * @param response The servlet response * @return A BrowserScope for the current parameters * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ protected BrowserScope getBrowserScopeForRequest(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { try { // first, lift all the stuff out of the request that we might need String type = request.getParameter("type"); String order = request.getParameter("order"); String value = request.getParameter("value"); String valueLang = request.getParameter("value_lang"); String month = request.getParameter("month"); String year = request.getParameter("year"); String startsWith = request.getParameter("starts_with"); String valueFocus = request.getParameter("vfocus"); String valueFocusLang = request.getParameter("vfocus_lang"); String authority = request.getParameter("authority"); int focus = UIUtil.getIntParameter(request, "focus"); int offset = UIUtil.getIntParameter(request, "offset"); int resultsperpage = UIUtil.getIntParameter(request, "rpp"); int sortBy = UIUtil.getIntParameter(request, "sort_by"); int etAl = UIUtil.getIntParameter(request, "etal"); // get the community or collection location for the browse request // Note that we are only interested in getting the "smallest" container, // so if we find a collection, we don't bother looking up the community Collection collection = null; Community community = null; collection = UIUtil.getCollectionLocation(request); if (collection == null) { community = UIUtil.getCommunityLocation(request); } // process the input, performing some inline validation BrowseIndex bi = null; if (type != null && !"".equals(type)) { bi = BrowseIndex.getBrowseIndex(type); } if (bi == null) { if (sortBy > 0) { bi = BrowseIndex.getBrowseIndex(SortOption.getSortOption(sortBy)); } else { bi = BrowseIndex.getBrowseIndex(SortOption.getDefaultSortOption()); } } // If we don't have a sort column if (bi != null && sortBy == -1) { // Get the default one SortOption so = bi.getSortOption(); if (so != null) { sortBy = so.getNumber(); } } else if (bi != null && bi.isItemIndex() && !bi.isInternalIndex()) { // If a default sort option is specified by the index, but it isn't // the same as sort option requested, attempt to find an index that // is configured to use that sort by default // This is so that we can then highlight the correct option in the navigation SortOption bso = bi.getSortOption(); SortOption so = SortOption.getSortOption(sortBy); if ( bso != null && bso.equals(so)) { BrowseIndex newBi = BrowseIndex.getBrowseIndex(so); if (newBi != null) { bi = newBi; type = bi.getName(); } } } if (order == null && bi != null) { order = bi.getDefaultOrder(); } // If the offset is invalid, reset to 0 if (offset < 0) { offset = 0; } // if no resultsperpage set, default to 20 if (resultsperpage < 0) { resultsperpage = 20; } // if year and perhaps month have been selected, we translate these into "startsWith" // if startsWith has already been defined then it is overwritten if (year != null && !"".equals(year) && !"-1".equals(year)) { startsWith = year; if ((month != null) && !"-1".equals(month) && !"".equals(month)) { // subtract 1 from the month, so the match works appropriately if ("ASC".equals(order)) { month = Integer.toString((Integer.parseInt(month) - 1)); } // They've selected a month as well if (month.length() == 1) { // Ensure double-digit month number month = "0" + month; } startsWith = year + "-" + month; if ("ASC".equals(order)) { startsWith = startsWith + "-32"; } } } // determine which level of the browse we are at: 0 for top, 1 for second int level = 0; if (value != null || authority != null) { level = 1; } // if sortBy is still not set, set it to 0, which is default to use the primary index value if (sortBy == -1) { sortBy = 0; } // figure out the setting for author list truncation if (etAl == -1) // there is no limit, or the UI says to use the default { int limitLine = ConfigurationManager.getIntProperty("webui.browse.author-limit"); if (limitLine != 0) { etAl = limitLine; } } else // if the user has set a limit { if (etAl == 0) // 0 is the user setting for unlimited { etAl = -1; // but -1 is the application setting for unlimited } } // log the request String comHandle = "n/a"; if (community != null) { comHandle = community.getHandle(); } String colHandle = "n/a"; if (collection != null) { colHandle = collection.getHandle(); } String arguments = "type=" + type + ",order=" + order + ",value=" + value + ",month=" + month + ",year=" + year + ",starts_with=" + startsWith + ",vfocus=" + valueFocus + ",focus=" + focus + ",rpp=" + resultsperpage + ",sort_by=" + sortBy + ",community=" + comHandle + ",collection=" + colHandle + ",level=" + level + ",etal=" + etAl; log.info(LogManager.getHeader(context, "browse", arguments)); // set up a BrowseScope and start loading the values into it BrowserScope scope = new BrowserScope(context); scope.setBrowseIndex(bi); scope.setOrder(order); scope.setFilterValue(value != null?value:authority); scope.setFilterValueLang(valueLang); scope.setJumpToItem(focus); scope.setJumpToValue(valueFocus); scope.setJumpToValueLang(valueFocusLang); scope.setStartsWith(startsWith); scope.setOffset(offset); scope.setResultsPerPage(resultsperpage); scope.setSortBy(sortBy); scope.setBrowseLevel(level); scope.setEtAl(etAl); scope.setAuthorityValue(authority); // assign the scope of either Community or Collection if necessary if (community != null) { scope.setBrowseContainer(community); } else if (collection != null) { scope.setBrowseContainer(collection); } // For second level browses on metadata indexes, we need to adjust the default sorting if (bi != null && bi.isMetadataIndex() && scope.isSecondLevel() && scope.getSortBy() <= 0) { scope.setSortBy(1); } return scope; } catch (SortException se) { log.error("caught exception: ", se); throw new ServletException(se); } catch (BrowseException e) { log.error("caught exception: ", e); throw new ServletException(e); } } /** * Do the usual DSpace GET method. You will notice that browse does not currently * respond to POST requests. */ protected void processBrowse(Context context, BrowserScope scope, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { try { BrowseIndex bi = scope.getBrowseIndex(); // now start up a browse engine and get it to do the work for us BrowseEngine be = new BrowseEngine(context); BrowseInfo binfo = be.browse(scope); request.setAttribute("browse.info", binfo); if (AuthorizeManager.isAdmin(context)) { // Set a variable to create admin buttons request.setAttribute("admin_button", Boolean.TRUE); } if (binfo.hasResults()) { if (bi.isMetadataIndex() && !scope.isSecondLevel()) { showSinglePage(context, request, response); } else { showFullPage(context, request, response); } } else { showNoResultsPage(context, request, response); } } catch (BrowseException e) { log.error("caught exception: ", e); throw new ServletException(e); } } /** * Display the error page * * @param context * @param request * @param response * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ protected abstract void showError(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException; /** * Display the No Results page * * @param context * @param request * @param response * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ protected abstract void showNoResultsPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException; /** * Display the single page. This is the page which lists just the single values of a * metadata browse, not individual items. Single values are links through to all the items * that match that metadata value * * @param context * @param request * @param response * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ protected abstract void showSinglePage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException; protected abstract void showFullPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException; }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.util.List; import java.sql.SQLException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import org.dspace.authorize.AuthorizeException; import org.apache.log4j.Logger; import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.eperson.Group; import org.dspace.content.DSpaceObject; import org.dspace.handle.HandleManager; import org.dspace.statistics.Dataset; import org.dspace.statistics.content.DatasetDSpaceObjectGenerator; import org.dspace.statistics.content.DatasetTimeGenerator; import org.dspace.statistics.content.DatasetTypeGenerator; import org.dspace.statistics.content.StatisticsDataVisits; import org.dspace.statistics.content.StatisticsListing; import org.dspace.statistics.content.StatisticsTable; import org.dspace.app.webui.components.StatisticsBean; import org.dspace.app.webui.util.JSPManager; /** * * * @author Kim Shepherd * @version $Revision: 4386 $ */ public class DisplayStatisticsServlet extends DSpaceServlet { /** log4j logger */ private static Logger log = Logger.getLogger(DisplayStatisticsServlet.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // is the statistics data publically viewable? boolean privatereport = ConfigurationManager.getBooleanProperty("statistics.item.authorization.admin"); // is the user a member of the Administrator (1) group? boolean admin = Group.isMember(context, 1); if (!privatereport || admin) { displayStatistics(context, request, response); } else { throw new AuthorizeException(); } } protected void displayStatistics(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String handle = request.getParameter("handle"); DSpaceObject dso = HandleManager.resolveToObject(context, handle); if(dso == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); JSPManager.showJSP(request, response, "/error/404.jsp"); return; } boolean isItem = false; StatisticsBean statsVisits = new StatisticsBean(); StatisticsBean statsMonthlyVisits = new StatisticsBean(); StatisticsBean statsFileDownloads = new StatisticsBean(); StatisticsBean statsCountryVisits = new StatisticsBean(); StatisticsBean statsCityVisits = new StatisticsBean(); try { StatisticsListing statListing = new StatisticsListing( new StatisticsDataVisits(dso)); statListing.setTitle("Total Visits"); statListing.setId("list1"); DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator(); dsoAxis.addDsoChild(dso.getType(), 10, false, -1); statListing.addDatasetGenerator(dsoAxis); Dataset dataset = statListing.getDataset(context); dataset = statListing.getDataset(); if (dataset == null) { dataset = statListing.getDataset(context); } if (dataset != null) { String[][] matrix = dataset.getMatrixFormatted(); List<String> colLabels = dataset.getColLabels(); List<String> rowLabels = dataset.getRowLabels(); statsVisits.setMatrix(matrix); statsVisits.setColLabels(colLabels); statsVisits.setRowLabels(rowLabels); } } catch (Exception e) { log.error( "Error occured while creating statistics for dso with ID: " + dso.getID() + " and type " + dso.getType() + " and handle: " + dso.getHandle(), e); } try { StatisticsTable statisticsTable = new StatisticsTable(new StatisticsDataVisits(dso)); statisticsTable.setTitle("Total Visits Per Month"); statisticsTable.setId("tab1"); DatasetTimeGenerator timeAxis = new DatasetTimeGenerator(); timeAxis.setDateInterval("month", "-6", "+1"); statisticsTable.addDatasetGenerator(timeAxis); DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator(); dsoAxis.addDsoChild(dso.getType(), 10, false, -1); statisticsTable.addDatasetGenerator(dsoAxis); Dataset dataset = statisticsTable.getDataset(context); dataset = statisticsTable.getDataset(); if (dataset == null) { dataset = statisticsTable.getDataset(context); } if (dataset != null) { String[][] matrix = dataset.getMatrixFormatted(); List<String> colLabels = dataset.getColLabels(); List<String> rowLabels = dataset.getRowLabels(); statsMonthlyVisits.setMatrix(matrix); statsMonthlyVisits.setColLabels(colLabels); statsMonthlyVisits.setRowLabels(rowLabels); } } catch (Exception e) { log.error( "Error occured while creating statistics for dso with ID: " + dso.getID() + " and type " + dso.getType() + " and handle: " + dso.getHandle(), e); } if(dso instanceof org.dspace.content.Item) { isItem = true; try { StatisticsListing statisticsTable = new StatisticsListing(new StatisticsDataVisits(dso)); statisticsTable.setTitle("File Downloads"); statisticsTable.setId("tab1"); DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator(); dsoAxis.addDsoChild(Constants.BITSTREAM, 10, false, -1); statisticsTable.addDatasetGenerator(dsoAxis); Dataset dataset = statisticsTable.getDataset(context); dataset = statisticsTable.getDataset(); if (dataset == null) { dataset = statisticsTable.getDataset(context); } if (dataset != null) { String[][] matrix = dataset.getMatrixFormatted(); List<String> colLabels = dataset.getColLabels(); List<String> rowLabels = dataset.getRowLabels(); statsFileDownloads.setMatrix(matrix); statsFileDownloads.setColLabels(colLabels); statsFileDownloads.setRowLabels(rowLabels); } } catch (Exception e) { log.error( "Error occured while creating statistics for dso with ID: " + dso.getID() + " and type " + dso.getType() + " and handle: " + dso.getHandle(), e); } } try { StatisticsListing statisticsTable = new StatisticsListing(new StatisticsDataVisits(dso)); statisticsTable.setTitle("Top country views"); statisticsTable.setId("tab1"); DatasetTypeGenerator typeAxis = new DatasetTypeGenerator(); typeAxis.setType("countryCode"); typeAxis.setMax(10); statisticsTable.addDatasetGenerator(typeAxis); Dataset dataset = statisticsTable.getDataset(context); dataset = statisticsTable.getDataset(); if (dataset == null) { dataset = statisticsTable.getDataset(context); } if (dataset != null) { String[][] matrix = dataset.getMatrixFormatted(); List<String> colLabels = dataset.getColLabels(); List<String> rowLabels = dataset.getRowLabels(); statsCountryVisits.setMatrix(matrix); statsCountryVisits.setColLabels(colLabels); statsCountryVisits.setRowLabels(rowLabels); } } catch (Exception e) { log.error( "Error occured while creating statistics for dso with ID: " + dso.getID() + " and type " + dso.getType() + " and handle: " + dso.getHandle(), e); } try { StatisticsListing statisticsTable = new StatisticsListing(new StatisticsDataVisits(dso)); statisticsTable.setTitle("Top city views"); statisticsTable.setId("tab1"); DatasetTypeGenerator typeAxis = new DatasetTypeGenerator(); typeAxis.setType("city"); typeAxis.setMax(10); statisticsTable.addDatasetGenerator(typeAxis); Dataset dataset = statisticsTable.getDataset(context); dataset = statisticsTable.getDataset(); if (dataset == null) { dataset = statisticsTable.getDataset(context); } if (dataset != null) { String[][] matrix = dataset.getMatrixFormatted(); List<String> colLabels = dataset.getColLabels(); List<String> rowLabels = dataset.getRowLabels(); statsCityVisits.setMatrix(matrix); statsCityVisits.setColLabels(colLabels); statsCityVisits.setRowLabels(rowLabels); } } catch (Exception e) { log.error( "Error occured while creating statistics for dso with ID: " + dso.getID() + " and type " + dso.getType() + " and handle: " + dso.getHandle(), e); } request.setAttribute("statsVisits", statsVisits); request.setAttribute("statsMonthlyVisits", statsMonthlyVisits); request.setAttribute("statsFileDownloads", statsFileDownloads); request.setAttribute("statsCountryVisits",statsCountryVisits); request.setAttribute("statsCityVisits", statsCityVisits); request.setAttribute("isItem", isItem); JSPManager.showJSP(request, response, "display-statistics.jsp"); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.dspace.app.webui.util.JSPManager; import org.dspace.authorize.AuthorizeException; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.eperson.EPerson; /** * Servlet for handling editing user profiles * * @author Robert Tansley * @version $Revision: 5845 $ */ public class EditProfileServlet extends DSpaceServlet { /** Logger */ private static Logger log = Logger.getLogger(EditProfileServlet.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // A GET displays the edit profile form. We assume the authentication // filter means we have a user. log.info(LogManager.getHeader(context, "view_profile", "")); request.setAttribute("eperson", context.getCurrentUser()); JSPManager.showJSP(request, response, "/register/edit-profile.jsp"); } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Get the user - authentication should have happened EPerson eperson = context.getCurrentUser(); // Find out if they're trying to set a new password boolean settingPassword = false; if (!eperson.getRequireCertificate() && !StringUtils.isEmpty(request.getParameter("password"))) { settingPassword = true; } // Set the user profile info boolean ok = updateUserProfile(eperson, request); if (!ok) { request.setAttribute("missing.fields", Boolean.TRUE); } if (ok && settingPassword) { // They want to set a new password. ok = confirmAndSetPassword(eperson, request); if (!ok) { request.setAttribute("password.problem", Boolean.TRUE); } } if (ok) { // Update the DB log.info(LogManager.getHeader(context, "edit_profile", "password_changed=" + settingPassword)); eperson.update(); // Show confirmation request.setAttribute("password.updated", Boolean.valueOf(settingPassword)); JSPManager.showJSP(request, response, "/register/profile-updated.jsp"); context.complete(); } else { log.info(LogManager.getHeader(context, "view_profile", "problem=true")); request.setAttribute("eperson", eperson); JSPManager.showJSP(request, response, "/register/edit-profile.jsp"); } } /** * Update a user's profile information with the information in the given * request. This assumes that authentication has occurred. This method * doesn't write the changes to the database (i.e. doesn't call update.) * * @param eperson * the e-person * @param request * the request to get values from * * @return true if the user supplied all the required information, false if * they left something out. */ public static boolean updateUserProfile(EPerson eperson, HttpServletRequest request) { // Get the parameters from the form String lastName = request.getParameter("last_name"); String firstName = request.getParameter("first_name"); String phone = request.getParameter("phone"); String language = request.getParameter("language"); // Update the eperson eperson.setFirstName(firstName); eperson.setLastName(lastName); eperson.setMetadata("phone", phone); eperson.setLanguage(language); // Check all required fields are there return (!StringUtils.isEmpty(lastName) && !StringUtils.isEmpty(firstName)); } /** * Set an eperson's password, if the passwords they typed match and are * acceptible. If all goes well and the password is set, null is returned. * Otherwise the problem is returned as a String. * * @param eperson * the eperson to set the new password for * @param request * the request containing the new password * * @return true if everything went OK, or false */ public static boolean confirmAndSetPassword(EPerson eperson, HttpServletRequest request) { // Get the passwords String password = request.getParameter("password"); String passwordConfirm = request.getParameter("password_confirm"); // Check it's there and long enough if ((password == null) || (password.length() < 6)) { return false; } // Check the two passwords entered match if (!password.equals(passwordConfirm)) { return false; } // Everything OK so far, change the password eperson.setPassword(password); return true; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; /** * Servlet for handling an internal server error * * @author Robert Tansley * @version $Revision: 5845 $ */ public class InternalErrorServlet extends HttpServlet { /* * We don't extend DSpaceServlet in case it's context creation etc. that * caused the problem! */ /** log4j category */ private static Logger log = Logger.getLogger(InternalErrorServlet.class); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the exception that occurred, if any Throwable t = (Throwable) request .getAttribute("javax.servlet.error.exception"); String logInfo = UIUtil.getRequestLogInfo(request); // Log the error. Since we don't have a context, we need to // build the info "by hand" String logMessage = ":session_id=" + request.getSession().getId() + ":internal_error:" + logInfo; log.warn(logMessage, t); // Now we try and mail the designated user, if any UIUtil.sendAlert(request, (Exception) t); JSPManager.showJSP(request, response, "/error/internal.jsp"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.authorize.AuthorizeException; import org.dspace.core.Context; import org.dspace.core.LogManager; /** * Simple servlet for open URL support. Presently, simply extracts terms from * open URL and redirects to search. * * @author Robert Tansley * @version $Revision: 5845 $ */ public class OpenURLServlet extends DSpaceServlet { /** Logger */ private static Logger log = Logger.getLogger(OpenURLServlet.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String query = ""; // Extract open URL terms. Note: assume no repetition String title = request.getParameter("title"); String authorFirst = request.getParameter("aufirst"); String authorLast = request.getParameter("aulast"); String logInfo = ""; if (title != null) { query = query + " " + title; logInfo = logInfo + "title=\"" + title + "\","; } if (authorFirst != null) { query = query + " " + authorFirst; logInfo = logInfo + "aufirst=\"" + authorFirst + "\","; } if (authorLast != null) { query = query + " " + authorLast; logInfo = logInfo + "aulast=\"" + authorLast + "\","; } log.info(LogManager.getHeader(context, "openURL", logInfo + "dspacequery=" + query)); response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/simple-search?query=" + query)); } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Same as a GET doDSGet(context, request, response); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.net.InetAddress; import java.sql.SQLException; import java.util.Date; import javax.mail.MessagingException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.commons.validator.EmailValidator; import org.dspace.app.webui.util.JSPManager; import org.dspace.authorize.AuthorizeException; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.core.Email; import org.dspace.core.I18nUtil; import org.dspace.core.LogManager; import org.dspace.eperson.EPerson; /** * Servlet for handling user feedback * * @author Peter Breton * @author Robert Tansley * @version $Revision: 5845 $ */ public class FeedbackServlet extends DSpaceServlet { /** log4j category */ private static Logger log = Logger.getLogger(FeedbackServlet.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Obtain information from request // The page where the user came from String fromPage = request.getHeader("Referer"); // Prevent spammers and splogbots from poisoning the feedback page String host = ConfigurationManager.getProperty("dspace.hostname"); String basicHost = ""; if (host.equals("localhost") || host.equals("127.0.0.1") || host.equals(InetAddress.getLocalHost().getHostAddress())) { basicHost = host; } else { // cut off all but the hostname, to cover cases where more than one URL // arrives at the installation; e.g. presence or absence of "www" int lastDot = host.lastIndexOf('.'); basicHost = host.substring(host.substring(0, lastDot).lastIndexOf(".")); } if (fromPage == null || fromPage.indexOf(basicHost) == -1) { throw new AuthorizeException(); } // The email address they provided String formEmail = request.getParameter("email"); // Browser String userAgent = request.getHeader("User-Agent"); // Session id String sessionID = request.getSession().getId(); // User email from context EPerson currentUser = context.getCurrentUser(); String authEmail = null; if (currentUser != null) { authEmail = currentUser.getEmail(); } // Has the user just posted their feedback? if (request.getParameter("submit") != null) { EmailValidator ev = EmailValidator.getInstance(); String feedback = request.getParameter("feedback"); // Check all data is there if ((formEmail == null) || formEmail.equals("") || (feedback == null) || feedback.equals("") || !ev.isValid(formEmail)) { log.info(LogManager.getHeader(context, "show_feedback_form", "problem=true")); request.setAttribute("feedback.problem", Boolean.TRUE); JSPManager.showJSP(request, response, "/feedback/form.jsp"); return; } // All data is there, send the email try { Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "feedback")); email.addRecipient(ConfigurationManager .getProperty("feedback.recipient")); email.addArgument(new Date()); // Date email.addArgument(formEmail); // Email email.addArgument(authEmail); // Logged in as email.addArgument(fromPage); // Referring page email.addArgument(userAgent); // User agent email.addArgument(sessionID); // Session ID email.addArgument(feedback); // The feedback itself // Replying to feedback will reply to email on form email.setReplyTo(formEmail); email.send(); log.info(LogManager.getHeader(context, "sent_feedback", "from=" + formEmail)); JSPManager.showJSP(request, response, "/feedback/acknowledge.jsp"); } catch (MessagingException me) { log.warn(LogManager.getHeader(context, "error_mailing_feedback", ""), me); JSPManager.showInternalError(request, response); } } else { // Display feedback form log.info(LogManager.getHeader(context, "show_feedback_form", "problem=false")); request.setAttribute("authenticated.email", authEmail); JSPManager.showJSP(request, response, "/feedback/form.jsp"); } } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Treat as a GET doDSGet(context, request, response); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.*; import java.sql.SQLException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.dspace.app.bulkedit.MetadataImportInvalidHeadingException; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.FileUploadRequest; import org.dspace.app.bulkedit.MetadataImport; import org.dspace.app.bulkedit.DSpaceCSV; import org.dspace.app.bulkedit.BulkEditChange; import org.dspace.authorize.AuthorizeException; import org.dspace.core.*; /** * Servlet to import metadata as CSV (comma separated values) * * @author Stuart Lewis */ public class MetadataImportServlet extends DSpaceServlet { /** Upload limit */ private int limit; /** log4j category */ private static Logger log = Logger.getLogger(MetadataImportServlet.class); /** * Initalise the servlet */ public void init() { // Set the lmimt to the number of items that may be changed in one go, default to 20 limit = ConfigurationManager.getIntProperty("bulkedit.gui-item-limit", 20); log.debug("Setting bulk edit limit to " + limit + " items"); } /** * Respond to a post request for metadata bulk importing via csv * * @param context a DSpace Context object * @param request the HTTP request * @param response the HTTP response * * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // First, see if we have a multipart request (uploading a metadata file) String contentType = request.getContentType(); HttpSession session = request.getSession(true); if ((contentType != null) && (contentType.indexOf("multipart/form-data") != -1)) { // Process the file uploaded try { // Get the changes log.info(LogManager.getHeader(context, "metadataimport", "loading file")); List<BulkEditChange> changes = processUpload(context, request); log.debug(LogManager.getHeader(context, "metadataimport", changes.size() + " items with changes identified")); // Were there any changes detected? if (changes.size() != 0) { request.setAttribute("changes", changes); request.setAttribute("changed", false); // Is the user allowed to make this many changes? if (changes.size() <= limit) { request.setAttribute("allow", true); } else { request.setAttribute("allow", false); session.removeAttribute("csv"); log.info(LogManager.getHeader(context, "metadataimport", "too many changes: " + changes.size() + " (" + limit + " allowed)")); } JSPManager.showJSP(request, response, "/dspace-admin/metadataimport-showchanges.jsp"); } else { request.setAttribute("message", "No changes detected"); JSPManager.showJSP(request, response, "/dspace-admin/metadataimport.jsp"); } } catch (MetadataImportInvalidHeadingException mihe) { request.setAttribute("message", mihe.getBadHeader()); request.setAttribute("badheading", mihe.getType()); log.info(LogManager.getHeader(context, "metadataimport", "Error encountered while looking for changes: " + mihe.getMessage())); JSPManager.showJSP(request, response, "/dspace-admin/metadataimport-error.jsp"); } catch (Exception e) { request.setAttribute("message", e.getMessage()); log.info(LogManager.getHeader(context, "metadataimport", "Error encountered while looking for changes: " + e.getMessage())); JSPManager.showJSP(request, response, "/dspace-admin/metadataimport-error.jsp"); } } else if ("confirm".equals(request.getParameter("type"))) { // Get the csv lines from the session DSpaceCSV csv = (DSpaceCSV)session.getAttribute("csv"); // Make the changes try { MetadataImport mImport = new MetadataImport(context, csv.getCSVLines()); List<BulkEditChange> changes = mImport.runImport(true, false, false, false); // Commit the changes context.commit(); log.debug(LogManager.getHeader(context, "metadataimport", changes.size() + " items changed")); // Blank out the session data session.removeAttribute("csv"); request.setAttribute("changes", changes); request.setAttribute("changed", true); request.setAttribute("allow", true); JSPManager.showJSP(request, response, "/dspace-admin/metadataimport-showchanges.jsp"); } catch (Exception e) { request.setAttribute("message", e.getMessage()); log.debug(LogManager.getHeader(context, "metadataimport", "Error encountered while making changes: " + e.getMessage())); JSPManager.showJSP(request, response, "/dspace-admin/metadataimport-error.jsp"); } } else if ("cancel".equals(request.getParameter("type"))) { // Blank out the session data session.removeAttribute("csv"); request.setAttribute("message", "Changes cancelled. No items have been modified."); log.debug(LogManager.getHeader(context, "metadataimport", "Changes cancelled")); JSPManager.showJSP(request, response, "/dspace-admin/metadataimport.jsp"); } else { // Show the upload screen JSPManager.showJSP(request, response, "/dspace-admin/metadataimport.jsp"); } } /** * GET request is only ever used to show the upload form * * @param context * a DSpace Context object * @param request * the HTTP request * @param response * the HTTP response * * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Show the upload screen JSPManager.showJSP(request, response, "/dspace-admin/metadataimport.jsp"); } /** * Process the uploaded file. * * @param context The DSpace Context * @param request The request object * @return The response object * @throws Exception Thrown if an error occurs */ private List<BulkEditChange> processUpload(Context context, HttpServletRequest request) throws Exception { // Wrap multipart request to get the submission info FileUploadRequest wrapper = new FileUploadRequest(request); File f = wrapper.getFile("file"); // Run the import DSpaceCSV csv = new DSpaceCSV(f, context); MetadataImport mImport = new MetadataImport(context, csv.getCSVLines()); List<BulkEditChange> changes = mImport.runImport(false, false, false, false); // Store the csv lines in the session HttpSession session = request.getSession(true); session.setAttribute("csv", csv); // Remove temp file if (!f.delete()) { log.error("Unable to delete upload file"); } // Return the changes return changes; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.JSPManager; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.core.Context; import org.dspace.core.LogManager; /** * Servlet for listing communities (and collections within them) * * @author Robert Tansley * @version $Revision: 5845 $ */ public class CommunityListServlet extends DSpaceServlet { /** log4j category */ private static Logger log = Logger.getLogger(CommunityListServlet.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { log.info(LogManager.getHeader(context, "view_community_list", "")); // This will map community IDs to arrays of collections Map<Integer, Collection[]> colMap = new HashMap<Integer, Collection[]>(); // This will map communityIDs to arrays of sub-communities Map<Integer, Community[]> commMap = new HashMap<Integer, Community[]>(); Community[] communities = Community.findAllTop(context); for (int com = 0; com < communities.length; com++) { Integer comID = Integer.valueOf(communities[com].getID()); // Find collections in community Collection[] colls = communities[com].getCollections(); colMap.put(comID, colls); // Find subcommunties in community Community[] comms = communities[com].getSubcommunities(); commMap.put(comID, comms); } // can they admin communities? if (AuthorizeManager.isAdmin(context)) { // set a variable to create an edit button request.setAttribute("admin_button", Boolean.TRUE); } request.setAttribute("communities", communities); request.setAttribute("collections.map", colMap); request.setAttribute("subcommunities.map", commMap); JSPManager.showJSP(request, response, "/community-list.jsp"); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import com.sun.mail.smtp.SMTPAddressFailedException; import org.apache.log4j.Logger; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authenticate.AuthenticationManager; import org.dspace.authorize.AuthorizeException; import org.dspace.core.*; import org.dspace.eperson.AccountManager; import org.dspace.eperson.EPerson; import javax.mail.MessagingException; import javax.mail.internet.AddressException; import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.SQLException; import java.util.Hashtable; /** * Servlet for handling user registration and forgotten passwords. * <P> * This servlet handles both forgotten passwords and initial registration of * users. Which it handles depends on the initialisation parameter "register" - * if it's "true", it is treated as an initial registration and the user is * asked to input their personal information. * <P> * The sequence of events is this: The user clicks on "register" or "I forgot my * password." This servlet then displays the relevant "enter your e-mail" form. * An e-mail address is POSTed back, and if this is valid, a token is created * and e-mailed, otherwise an error is displayed, with another "enter your * e-mail" form. * <P> * When the user clicks on the token URL mailed to them, this servlet receives a * GET with the token as the parameter "KEY". If this is a valid token, the * servlet then displays the "edit profile" or "edit password" screen as * appropriate. */ public class RegisterServlet extends DSpaceServlet { /** Logger */ private static Logger log = Logger.getLogger(RegisterServlet.class); /** The "enter e-mail" step */ public static final int ENTER_EMAIL_PAGE = 1; /** The "enter personal info" page, for a registering user */ public static final int PERSONAL_INFO_PAGE = 2; /** The simple "enter new password" page, for user who's forgotten p/w */ public static final int NEW_PASSWORD_PAGE = 3; /** true = registering users, false = forgotten passwords */ private boolean registering; /** ldap is enabled */ private boolean ldap_enabled; public void init() { registering = getInitParameter("register").equalsIgnoreCase("true"); ldap_enabled = ConfigurationManager.getBooleanProperty("ldap.enable"); } protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { /* * Respond to GETs. A simple GET with no parameters will display the * relevant "type in your e-mail" form. A GET with a "token" parameter * will go to the "enter personal info" or "enter new password" page as * appropriate. */ // Get the token String token = request.getParameter("token"); if (token == null) { // Simple "enter your e-mail" page if (registering) { // Registering a new user if (ldap_enabled) { JSPManager.showJSP(request, response, "/register/new-ldap-user.jsp"); } JSPManager.showJSP(request, response, "/register/new-user.jsp"); } else { // User forgot their password JSPManager.showJSP(request, response, "/register/forgot-password.jsp"); } } else { // We have a token. Find out who the it's for String email = AccountManager.getEmail(context, token); EPerson eperson = null; if (email != null) { eperson = EPerson.findByEmail(context, email); } // Both forms need an EPerson object (if any) request.setAttribute("eperson", eperson); // And the token request.setAttribute("token", token); if (registering && (email != null)) { // Indicate if user can set password boolean setPassword = AuthenticationManager.allowSetPassword(context, request, email); request.setAttribute("set.password", Boolean.valueOf(setPassword)); // Forward to "personal info page" JSPManager.showJSP(request, response, "/register/registration-form.jsp"); } else if (!registering && (eperson != null)) { // Token relates to user who's forgotten password JSPManager.showJSP(request, response, "/register/new-password.jsp"); } else { // Duff token! JSPManager.showJSP(request, response, "/register/invalid-token.jsp"); return; } } } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { /* * POSTs are the result of entering an e-mail in the "forgot my * password" or "new user" forms, or the "enter profile information" or * "enter new password" forms. */ // First get the step int step = UIUtil.getIntParameter(request, "step"); switch (step) { case ENTER_EMAIL_PAGE: processEnterEmail(context, request, response); break; case PERSONAL_INFO_PAGE: processPersonalInfo(context, request, response); break; case NEW_PASSWORD_PAGE: processNewPassword(context, request, response); break; default: log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); } } /** * Process information from the "enter e-mail" page. If the e-mail * corresponds to a valid user of the system, a token is generated and sent * to that user. * * @param context * current DSpace context * @param request * current servlet request object * @param response * current servlet response object */ private void processEnterEmail(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String email = request.getParameter("email"); if (email == null || email.length() > 64) { // Malformed request or entered value is too long. email = ""; } else { email = email.toLowerCase().trim(); } String netid = request.getParameter("netid"); String password = request.getParameter("password"); EPerson eperson = EPerson.findByEmail(context, email); EPerson eperson2 = null; if (netid!=null) { eperson2 = EPerson.findByNetid(context, netid.toLowerCase()); } try { if (registering) { // If an already-active user is trying to register, inform them so if ((eperson != null && eperson.canLogIn()) || (eperson2 != null && eperson2.canLogIn())) { log.info(LogManager.getHeader(context, "already_registered", "email=" + email)); JSPManager.showJSP(request, response, "/register/already-registered.jsp"); } else { // Find out from site authenticator whether this email can // self-register boolean canRegister = AuthenticationManager.canSelfRegister(context, request, email); if (canRegister) { //-- registering by email if ((!ldap_enabled)||(netid==null)||(netid.trim().equals(""))) { // OK to register. Send token. log.info(LogManager.getHeader(context, "sendtoken_register", "email=" + email)); try { AccountManager.sendRegistrationInfo(context, email); } catch (javax.mail.SendFailedException e) { if (e.getNextException() instanceof SMTPAddressFailedException) { // If we reach here, the email is email is invalid for the SMTP server (i.e. fbotelho). log.info(LogManager.getHeader(context, "invalid_email", "email=" + email)); request.setAttribute("retry", Boolean.TRUE); JSPManager.showJSP(request, response, "/register/new-user.jsp"); return; } else { throw e; } } JSPManager.showJSP(request, response, "/register/registration-sent.jsp"); // Context needs completing to write registration data context.complete(); } //-- registering by netid else { //--------- START LDAP AUTH SECTION ------------- if (password!=null && !password.equals("")) { String ldap_provider_url = ConfigurationManager.getProperty("ldap.provider_url"); String ldap_id_field = ConfigurationManager.getProperty("ldap.id_field"); String ldap_search_context = ConfigurationManager.getProperty("ldap.search_context"); // Set up environment for creating initial context Hashtable env = new Hashtable(11); env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(javax.naming.Context.PROVIDER_URL, ldap_provider_url); // Authenticate env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "simple"); env.put(javax.naming.Context.SECURITY_PRINCIPAL, ldap_id_field+"="+netid+","+ldap_search_context); env.put(javax.naming.Context.SECURITY_CREDENTIALS, password); try { // Create initial context DirContext ctx = new InitialDirContext(env); // Close the context when we're done ctx.close(); } catch (NamingException e) { // If we reach here, supplied email/password was duff. log.info(LogManager.getHeader(context, "failed_login", "netid=" + netid + e)); JSPManager.showJSP(request, response, "/login/ldap-incorrect.jsp"); return; } } //--------- END LDAP AUTH SECTION ------------- // Forward to "personal info page" JSPManager.showJSP(request, response, "/register/registration-form.jsp"); } } else { JSPManager.showJSP(request, response, "/register/cannot-register.jsp"); } } } else { if (eperson == null) { // Invalid email address log.info(LogManager.getHeader(context, "unknown_email", "email=" + email)); request.setAttribute("retry", Boolean.TRUE); JSPManager.showJSP(request, response, "/register/forgot-password.jsp"); } else if (!eperson.canLogIn()) { // Can't give new password to inactive user log.info(LogManager.getHeader(context, "unregistered_forgot_password", "email=" + email)); JSPManager.showJSP(request, response, "/register/inactive-account.jsp"); } else if (eperson.getRequireCertificate() && !registering) { // User that requires certificate can't get password log.info(LogManager.getHeader(context, "certificate_user_forgot_password", "email=" + email)); JSPManager.showJSP(request, response, "/error/require-certificate.jsp"); } else { // OK to send forgot pw token. log.info(LogManager.getHeader(context, "sendtoken_forgotpw", "email=" + email)); AccountManager.sendForgotPasswordInfo(context, email); JSPManager.showJSP(request, response, "/register/password-token-sent.jsp"); // Context needs completing to write registration data context.complete(); } } } catch (AddressException ae) { // Malformed e-mail address log.info(LogManager.getHeader(context, "bad_email", "email=" + email)); request.setAttribute("retry", Boolean.TRUE); if (registering) { if (ldap_enabled) { JSPManager.showJSP(request, response, "/register/new-ldap-user.jsp"); } else { JSPManager.showJSP(request, response, "/register/new-user.jsp"); } } else { JSPManager.showJSP(request, response, "/register/forgot-password.jsp"); } } catch (MessagingException me) { // Some other mailing error log.info(LogManager.getHeader(context, "error_emailing", "email=" + email), me); JSPManager.showInternalError(request, response); } } /** * Process information from "Personal information page" * * @param context * current DSpace context * @param request * current servlet request object * @param response * current servlet response object */ private void processPersonalInfo(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Get the token String token = request.getParameter("token"); // Get the email address String email = AccountManager.getEmail(context, token); String netid = request.getParameter("netid"); if ((netid!=null)&&(email==null)) { email = request.getParameter("email"); } // If the token isn't valid, show an error if (email == null && netid==null) { log.info(LogManager.getHeader(context, "invalid_token", "token=" + token)); // Invalid token JSPManager .showJSP(request, response, "/register/invalid-token.jsp"); return; } // If the token is valid, we create an eperson record if need be EPerson eperson = null; if (email!=null) { eperson = EPerson.findByEmail(context, email); } EPerson eperson2 = null; if (netid!=null) { eperson2 = EPerson.findByNetid(context, netid.toLowerCase()); } if (eperson2 !=null) { eperson = eperson2; } if (eperson == null) { // Need to create new eperson // FIXME: TEMPORARILY need to turn off authentication, as usually // only site admins can create e-people context.setIgnoreAuthorization(true); eperson = EPerson.create(context); eperson.setEmail(email); if (netid!=null) { eperson.setNetid(netid.toLowerCase()); } eperson.update(); context.setIgnoreAuthorization(false); } // Now set the current user of the context // to the user associated with the token, so they can update their // info context.setCurrentUser(eperson); // Set the user profile info boolean infoOK = EditProfileServlet.updateUserProfile(eperson, request); eperson.setCanLogIn(true); eperson.setSelfRegistered(true); // Give site auth a chance to set/override appropriate fields AuthenticationManager.initEPerson(context, request, eperson); // If the user set a password, make sure it's OK boolean passwordOK = true; if (!eperson.getRequireCertificate() && netid==null && AuthenticationManager.allowSetPassword(context, request, eperson.getEmail())) { passwordOK = EditProfileServlet.confirmAndSetPassword(eperson, request); } if (infoOK && passwordOK) { // All registered OK. log.info(LogManager.getHeader(context, "usedtoken_register", "email=" + eperson.getEmail())); // delete the token if (token!=null) { AccountManager.deleteToken(context, token); } // Update user record eperson.update(); request.setAttribute("eperson", eperson); JSPManager.showJSP(request, response, "/register/registered.jsp"); context.complete(); } else { request.setAttribute("token", token); request.setAttribute("eperson", eperson); request.setAttribute("netid", netid); request.setAttribute("missing.fields", Boolean.valueOf(!infoOK)); request.setAttribute("password.problem", Boolean.valueOf(!passwordOK)); // Indicate if user can set password boolean setPassword = AuthenticationManager.allowSetPassword( context, request, email); request.setAttribute("set.password", Boolean.valueOf(setPassword)); JSPManager.showJSP(request, response, "/register/registration-form.jsp"); // Changes to/creation of e-person in DB cancelled context.abort(); } } /** * Process information from "enter new password" * * @param context * current DSpace context * @param request * current servlet request object * @param response * current servlet response object */ private void processNewPassword(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Get the token String token = request.getParameter("token"); // Get the eperson associated with the password change EPerson eperson = AccountManager.getEPerson(context, token); // If the token isn't valid, show an error if (eperson == null) { log.info(LogManager.getHeader(context, "invalid_token", "token=" + token)); // Invalid token JSPManager .showJSP(request, response, "/register/invalid-token.jsp"); return; } // If the token is valid, we set the current user of the context // to the user associated with the token, so they can update their // info context.setCurrentUser(eperson); // Confirm and set the password boolean passwordOK = EditProfileServlet.confirmAndSetPassword(eperson, request); if (passwordOK) { log.info(LogManager.getHeader(context, "usedtoken_forgotpw", "email=" + eperson.getEmail())); eperson.update(); AccountManager.deleteToken(context, token); JSPManager.showJSP(request, response, "/register/password-changed.jsp"); context.complete(); } else { request.setAttribute("password.problem", Boolean.TRUE); request.setAttribute("token", token); request.setAttribute("eperson", eperson); JSPManager.showJSP(request, response, "/register/new-password.jsp"); } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.itemexport.ItemExport; import org.dspace.app.webui.util.JSPManager; import org.dspace.authorize.AuthorizeException; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.core.Utils; /** * Servlet for retrieving item export archives. The bits are simply piped to the * user. If there is an <code>If-Modified-Since</code> header, only a 304 * status code is returned if the containing item has not been modified since * that date. * <P> * <code>/exportdownload/filename</code> * * @author Jay Paz */ public class ItemExportArchiveServlet extends DSpaceServlet { /** log4j category */ private static Logger log = Logger.getLogger(ItemExportArchiveServlet.class); @Override protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String filename = null; filename = request.getPathInfo().substring( request.getPathInfo().lastIndexOf('/')+1); System.out.println(filename); if (ItemExport.canDownload(context, filename)) { try { InputStream exportStream = ItemExport .getExportDownloadInputStream(filename, context .getCurrentUser()); if (exportStream == null || filename == null) { // No bitstream found or filename was wrong -- ID invalid log.info(LogManager.getHeader(context, "invalid_id", "path=" + filename)); JSPManager.showInvalidIDError(request, response, filename, Constants.BITSTREAM); return; } log.info(LogManager.getHeader(context, "download_export_archive", "filename=" + filename)); // Modification date // TODO: Currently the date of the item, since we don't have // dates // for files long lastModified = ItemExport .getExportFileLastModified(filename); response.setDateHeader("Last-Modified", lastModified); // Check for if-modified-since header long modSince = request.getDateHeader("If-Modified-Since"); if (modSince != -1 && lastModified < modSince) { // Item has not been modified since requested date, // hence bitstream has not; return 304 response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Set the response MIME type response.setContentType(ItemExport.COMPRESSED_EXPORT_MIME_TYPE); // Response length long size = ItemExport.getExportFileSize(filename); response.setHeader("Content-Length", String.valueOf(size)); response.setHeader("Content-Disposition", "attachment;filename=" + filename); Utils.bufferedCopy(exportStream, response.getOutputStream()); exportStream.close(); response.getOutputStream().flush(); } catch (Exception e) { throw new ServletException(e); } } else { throw new AuthorizeException( "You are not authorized to download this Export Archive."); } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import java.text.MessageFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.util.SyndicationFeed; import org.dspace.app.webui.util.JSPManager; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.browse.BrowseEngine; import org.dspace.browse.BrowseException; import org.dspace.browse.BrowseIndex; import org.dspace.browse.BrowseInfo; import org.dspace.browse.BrowserScope; import org.dspace.sort.SortOption; import org.dspace.sort.SortException; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DCDate; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.handle.HandleManager; import org.dspace.search.Harvest; import org.dspace.eperson.Group; import com.sun.syndication.io.FeedException; /** * Servlet for handling requests for a syndication feed. The Handle of the collection * or community is extracted from the URL, e.g: <code>/feed/rss_1.0/1234/5678</code>. * Currently supports only RSS feed formats. * * @author Ben Bosman, Richard Rodgers * @version $Revision: 5845 $ */ public class FeedServlet extends DSpaceServlet { // key for site-wide feed public static final String SITE_FEED_KEY = "site"; // one hour in milliseconds private static final long HOUR_MSECS = 60 * 60 * 1000; /** log4j category */ private static Logger log = Logger.getLogger(FeedServlet.class); private String clazz = "org.dspace.app.webui.servlet.FeedServlet"; // are syndication feeds enabled? private static boolean enabled = false; // number of DSpace items per feed private static int itemCount = 0; // optional cache of feeds private static Map<String, CacheFeed> feedCache = null; // maximum size of cache - 0 means caching disabled private static int cacheSize = 0; // how many days to keep a feed in cache before checking currency private static int cacheAge = 0; // supported syndication formats private static List<String> formats = null; // Whether to include private items or not private static boolean includeAll = true; static { enabled = ConfigurationManager.getBooleanProperty("webui.feed.enable"); // read rest of config info if enabled if (enabled) { String fmtsStr = ConfigurationManager.getProperty("webui.feed.formats"); if ( fmtsStr != null ) { formats = new ArrayList<String>(); String[] fmts = fmtsStr.split(","); for (int i = 0; i < fmts.length; i++) { formats.add(fmts[i]); } } itemCount = ConfigurationManager.getIntProperty("webui.feed.items"); cacheSize = ConfigurationManager.getIntProperty("webui.feed.cache.size"); if (cacheSize > 0) { feedCache = new HashMap<String, CacheFeed>(); cacheAge = ConfigurationManager.getIntProperty("webui.feed.cache.age"); } } } protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { includeAll = ConfigurationManager.getBooleanProperty("harvest.includerestricted.rss", true); String path = request.getPathInfo(); String feedType = null; String handle = null; // build label map from localized Messages resource bundle Locale locale = request.getLocale(); ResourceBundle msgs = ResourceBundle.getBundle("Messages", locale); Map<String, String> labelMap = new HashMap<String, String>(); labelMap.put(SyndicationFeed.MSG_UNTITLED, msgs.getString(clazz + ".notitle")); labelMap.put(SyndicationFeed.MSG_LOGO_TITLE, msgs.getString(clazz + ".logo.title")); labelMap.put(SyndicationFeed.MSG_FEED_DESCRIPTION, msgs.getString(clazz + ".general-feed.description")); labelMap.put(SyndicationFeed.MSG_UITYPE, SyndicationFeed.UITYPE_JSPUI); for (String selector : SyndicationFeed.getDescriptionSelectors()) { labelMap.put("metadata." + selector, msgs.getString(SyndicationFeed.MSG_METADATA + selector)); } if (path != null) { // substring(1) is to remove initial '/' path = path.substring(1); int split = path.indexOf('/'); if (split != -1) { feedType = path.substring(0,split); handle = path.substring(split+1); } } DSpaceObject dso = null; //as long as this is not a site wide feed, //attempt to retrieve the Collection or Community object if(handle != null && !handle.equals(SITE_FEED_KEY)) { // Determine if handle is a valid reference dso = HandleManager.resolveToObject(context, handle); if (dso == null) { log.info(LogManager.getHeader(context, "invalid_handle", "path=" + path)); JSPManager.showInvalidIDError(request, response, handle, -1); return; } } if (! enabled || (dso != null && (dso.getType() != Constants.COLLECTION && dso.getType() != Constants.COMMUNITY)) ) { log.info(LogManager.getHeader(context, "invalid_id", "path=" + path)); JSPManager.showInvalidIDError(request, response, path, -1); return; } // Determine if requested format is supported if( feedType == null || ! formats.contains( feedType ) ) { log.info(LogManager.getHeader(context, "invalid_syndformat", "path=" + path)); JSPManager.showInvalidIDError(request, response, path, -1); return; } if (dso != null && dso.getType() == Constants.COLLECTION) { labelMap.put(SyndicationFeed.MSG_FEED_TITLE, MessageFormat.format(msgs.getString(clazz + ".feed.title"), new Object[]{ msgs.getString(clazz + ".feed-type.collection"), ((Collection)dso).getMetadata("short_description")})); } else if (dso != null && dso.getType() == Constants.COMMUNITY) { labelMap.put(SyndicationFeed.MSG_FEED_TITLE, MessageFormat.format(msgs.getString(clazz + ".feed.title"), new Object[]{ msgs.getString(clazz + ".feed-type.community"), ((Community)dso).getMetadata("short_description")})); } // Lookup or generate the feed // Cache key is handle + locale String cacheKey = (handle==null?"site":handle)+"."+locale.toString(); SyndicationFeed feed = null; if (feedCache != null) { CacheFeed cFeed = feedCache.get(cacheKey); if (cFeed != null) // cache hit, but... { // Is the feed current? boolean cacheFeedCurrent = false; if (cFeed.timeStamp + (cacheAge * HOUR_MSECS) < System.currentTimeMillis()) { cacheFeedCurrent = true; } // Not current, but have any items changed since feed was created/last checked? else if ( ! itemsChanged(context, dso, cFeed.timeStamp)) { // no items have changed, re-stamp feed and use it cFeed.timeStamp = System.currentTimeMillis(); cacheFeedCurrent = true; } if (cacheFeedCurrent) { feed = cFeed.access(); } } } // either not caching, not found in cache, or feed in cache not current if (feed == null) { feed = new SyndicationFeed(SyndicationFeed.UITYPE_JSPUI); feed.populate(request, dso, getItems(context, dso), labelMap); if (feedCache != null) { cache(cacheKey, new CacheFeed(feed)); } } // set the feed to the requested type & return it try { feed.setType(feedType); response.setContentType("text/xml; charset=UTF-8"); feed.output(response.getWriter()); } catch( FeedException fex ) { throw new IOException(fex.getMessage(), fex); } } private boolean itemsChanged(Context context, DSpaceObject dso, long timeStamp) throws SQLException { // construct start and end dates DCDate dcStartDate = new DCDate( new Date(timeStamp) ); DCDate dcEndDate = new DCDate( new Date(System.currentTimeMillis()) ); // convert dates to ISO 8601, stripping the time String startDate = dcStartDate.toString().substring(0, 10); String endDate = dcEndDate.toString().substring(0, 10); // this invocation should return a non-empty list if even 1 item has changed try { return (Harvest.harvest(context, dso, startDate, endDate, 0, 1, !includeAll, false, false, includeAll).size() > 0); } catch (ParseException pe) { // This should never get thrown as we have generated the dates ourselves return false; } } // returns recently changed items, checking for accessibility private Item[] getItems(Context context, DSpaceObject dso) throws IOException, SQLException { try { // new method of doing the browse: String idx = ConfigurationManager.getProperty("recent.submissions.sort-option"); if (idx == null) { throw new IOException("There is no configuration supplied for: recent.submissions.sort-option"); } BrowseIndex bix = BrowseIndex.getItemBrowseIndex(); if (bix == null) { throw new IOException("There is no browse index with the name: " + idx); } BrowserScope scope = new BrowserScope(context); scope.setBrowseIndex(bix); if (dso != null) { scope.setBrowseContainer(dso); } for (SortOption so : SortOption.getSortOptions()) { if (so.getName().equals(idx)) { scope.setSortBy(so.getNumber()); } } scope.setOrder(SortOption.DESCENDING); scope.setResultsPerPage(itemCount); // gather & add items to the feed. BrowseEngine be = new BrowseEngine(context); BrowseInfo bi = be.browseMini(scope); Item[] results = bi.getItemResults(context); if (includeAll) { return results; } else { // Check to see if we can include this item //Group[] authorizedGroups = AuthorizeManager.getAuthorizedGroups(context, results[i], Constants.READ); //boolean added = false; List<Item> items = new ArrayList<Item>(); for (Item result : results) { checkAccess: for (Group group : AuthorizeManager.getAuthorizedGroups(context, result, Constants.READ)) { if ((group.getID() == 0)) { items.add(result); break checkAccess; } } } return items.toArray(new Item[items.size()]); } } catch (SortException se) { log.error("caught exception: ", se); throw new IOException(se.getMessage(), se); } catch (BrowseException e) { log.error("caught exception: ", e); throw new IOException(e.getMessage(), e); } } /************************************************ * private cache management classes and methods * ************************************************/ /** * Add a feed to the cache - reducing the size of the cache by 1 to make room if * necessary. The removed entry has an access count equal to the minumum in the cache. * @param feedKey * The cache key for the feed * @param newFeed * The CacheFeed feed to be cached */ private static void cache(String feedKey, CacheFeed newFeed) { // remove older feed to make room if cache full if (feedCache.size() >= cacheSize) { // cache profiling data int total = 0; String minKey = null; CacheFeed minFeed = null; CacheFeed maxFeed = null; Iterator<String> iter = feedCache.keySet().iterator(); while (iter.hasNext()) { String key = iter.next(); CacheFeed feed = feedCache.get(key); if (minKey != null) { if (feed.hits < minFeed.hits) { minKey = key; minFeed = feed; } if (feed.hits >= maxFeed.hits) { maxFeed = feed; } } else { minKey = key; minFeed = feed; maxFeed = feed; } total += feed.hits; } // log a profile of the cache to assist administrator in tuning it int avg = total / feedCache.size(); String logMsg = "feedCache() - size: " + feedCache.size() + " Hits - total: " + total + " avg: " + avg + " max: " + maxFeed.hits + " min: " + minFeed.hits; log.info(logMsg); // remove minimum hits entry feedCache.remove(minKey); } // add feed to cache feedCache.put(feedKey, newFeed); } /** * Class to instrument accesses & currency of a given feed in cache */ private static class CacheFeed { // currency timestamp public long timeStamp = 0L; // access count public int hits = 0; // the feed private SyndicationFeed feed = null; public CacheFeed(SyndicationFeed feed) { this.feed = feed; timeStamp = System.currentTimeMillis(); } public SyndicationFeed access() { ++hits; return feed; } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dspace.app.webui.util.JSPManager; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Community; import org.dspace.core.Context; /** * Servlet for constructing the advanced search form * * @author gam * @version $Revision: 5845 $ */ public class AdvancedSearchServlet extends DSpaceServlet { protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // just build a list of top-level communities and pass along to the jsp Community[] communities = Community.findAllTop(context); request.setAttribute("communities", communities); JSPManager.showJSP(request, response, "/search/advanced.jsp"); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.Authenticate; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.core.Context; import org.dspace.core.LogManager; /** * Base class for DSpace servlets. This manages the initialisation of a context, * if a context has not already been initialised by an authentication filter. It * also grabs the original request URL for later use. * <P> * Unlike regular servlets, DSpace servlets should override the * <code>doDSGet</code> and <code>doDSPost</code> methods, which provide a * DSpace context to work with, and handle the common exceptions * <code>SQLException</code> and <code>AuthorizeException</code>. * <code>doGet</code> and <code>doPost</code> should be overridden only in * special circumstances. * <P> * Note that if all goes well, the context object passed in to * <code>doDSGet</code> and <code>doDSPut</code> must be completed * <em>after</em> a JSP has been displayed, but <code>before</code> the * method returns. If an error occurs (an exception is thrown, or the context is * not completed) the context is aborted after <code>doDSGet</code> or * <code>doDSPut</code> return. * * @see org.dspace.core.Context * * @author Robert Tansley * @version $Revision: 5845 $ */ public class DSpaceServlet extends HttpServlet { /* * Because the error handling is indentical for GET and POST requests, to * make things easier, doGet and doPost are folded into one method which * then "re-separates" to GET and POST. We do not override "service" since * we wish to allow doGet and doPost to be overridden if necessary (for * example, by lightweight servlets that do not need a DSpace context * object). */ /** log4j category */ private static Logger log = Logger.getLogger(DSpaceServlet.class); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Process an incoming request * * @param request * the request object * @param response * the response object */ private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Context context = null; // set all incoming encoding to UTF-8 request.setCharacterEncoding("UTF-8"); // Get the URL from the request immediately, since forwarding // loses that information UIUtil.storeOriginalURL(request); try { // Obtain a context - either create one, or get the one created by // an authentication filter context = UIUtil.obtainContext(request); // Are we resuming a previous request that was interrupted for // authentication? request = Authenticate.getRealRequest(request); if (log.isDebugEnabled()) { log.debug(LogManager.getHeader(context, "http_request", UIUtil .getRequestLogInfo(request))); } // Invoke the servlet code if (request.getMethod().equals("POST")) { doDSPost(context, request, response); } else { doDSGet(context, request, response); } } catch (SQLException se) { // For database errors, we log the exception and show a suitably // apologetic error log.warn(LogManager.getHeader(context, "database_error", se .toString()), se); // Also email an alert UIUtil.sendAlert(request, se); JSPManager.showInternalError(request, response); } catch (AuthorizeException ae) { /* * If no user is logged in, we will start authentication, since if * they authenticate, they might be allowed to do what they tried to * do. If someone IS logged in, and we got this exception, we know * they tried to do something they aren't allowed to, so we display * an error in that case. */ if (context.getCurrentUser() != null || Authenticate.startAuthentication(context, request, response)) { // FIXME: Log the right info? // Log the error log.info(LogManager.getHeader(context, "authorize_error", ae .toString())); JSPManager.showAuthorizeError(request, response, ae); } } finally { // Abort the context if it's still valid if ((context != null) && context.isValid()) { context.abort(); } } } /** * Process an incoming HTTP GET. If an exception is thrown, or for some * other reason the passed in context is not completed, it will be aborted * and any changes made by this method discarded when this method returns. * * @param context * a DSpace Context object * @param request * the HTTP request * @param response * the HTTP response * * @throws SQLException * if a database error occurs * @throws AuthorizeException * if some authorization error occurs */ protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // If this is not overridden, we invoke the raw HttpServlet "doGet" to // indicate that GET is not supported by this servlet. super.doGet(request, response); } /** * Process an incoming HTTP POST. If an exception is thrown, or for some * other reason the passed in context is not completed, it will be aborted * and any changes made by this method discarded when this method returns. * * @param context * a DSpace Context object * @param request * the HTTP request * @param response * the HTTP response * * @throws SQLException * if a database error occurs * @throws AuthorizeException * if some authorization error occurs */ protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // If this is not overridden, we invoke the raw HttpServlet "doGet" to // indicate that POST is not supported by this servlet. super.doGet(request, response); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.io.PrintWriter; import java.net.URLEncoder; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.app.bulkedit.MetadataExport; import org.dspace.app.bulkedit.DSpaceCSV; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.Item; import org.dspace.content.ItemIterator; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.handle.HandleManager; import org.dspace.search.DSQuery; import org.dspace.search.QueryArgs; import org.dspace.search.QueryResults; import org.dspace.sort.SortOption; /** * Servlet for handling a simple search. * <p> * All metadata is search for the value contained in the "query" parameter. If * the "location" parameter is present, the user's location is switched to that * location using a redirect. Otherwise, the user's current location is used to * constrain the query; i.e., if the user is "in" a collection, only results * from the collection will be returned. * <p> * The value of the "location" parameter should be ALL (which means no * location), a the ID of a community (e.g. "123"), or a community ID, then a * slash, then a collection ID, e.g. "123/456". * * @author Robert Tansley * @version $Id: SimpleSearchServlet.java,v 1.17 2004/12/15 15:21:10 jimdowning * Exp $ */ public class SimpleSearchServlet extends DSpaceServlet { /** log4j category */ private static Logger log = Logger.getLogger(SimpleSearchServlet.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Get the query String query = request.getParameter("query"); int start = UIUtil.getIntParameter(request, "start"); String advanced = request.getParameter("advanced"); String fromAdvanced = request.getParameter("from_advanced"); int sortBy = UIUtil.getIntParameter(request, "sort_by"); String order = request.getParameter("order"); int rpp = UIUtil.getIntParameter(request, "rpp"); String advancedQuery = ""; // can't start earlier than 0 in the results! if (start < 0) { start = 0; } int collCount = 0; int commCount = 0; int itemCount = 0; Item[] resultsItems; Collection[] resultsCollections; Community[] resultsCommunities; QueryResults qResults = null; QueryArgs qArgs = new QueryArgs(); SortOption sortOption = null; if (request.getParameter("etal") != null) { qArgs.setEtAl(UIUtil.getIntParameter(request, "etal")); } try { if (sortBy > 0) { sortOption = SortOption.getSortOption(sortBy); qArgs.setSortOption(sortOption); } if (SortOption.ASCENDING.equalsIgnoreCase(order)) { qArgs.setSortOrder(SortOption.ASCENDING); } else { qArgs.setSortOrder(SortOption.DESCENDING); } } catch (Exception e) { } // Override the page setting if exporting metadata if ("submit_export_metadata".equals(UIUtil.getSubmitButton(request, "submit"))) { qArgs.setPageSize(Integer.MAX_VALUE); } else if (rpp > 0) { qArgs.setPageSize(rpp); } // if the "advanced" flag is set, build the query string from the // multiple query fields if (advanced != null) { query = qArgs.buildQuery(request); advancedQuery = qArgs.buildHTTPQuery(request); } // Ensure the query is non-null if (query == null) { query = ""; } // Get the location parameter, if any String location = request.getParameter("location"); // If there is a location parameter, we should redirect to // do the search with the correct location. if ((location != null) && !location.equals("")) { String url = ""; if (!location.equals("/")) { // Location is a Handle url = "/handle/" + location; } // Encode the query query = URLEncoder.encode(query, Constants.DEFAULT_ENCODING); if (advancedQuery.length() > 0) { query = query + "&from_advanced=true&" + advancedQuery; } // Do the redirect response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + url + "/simple-search?query=" + query)); return; } // Build log information String logInfo = ""; // Get our location Community community = UIUtil.getCommunityLocation(request); Collection collection = UIUtil.getCollectionLocation(request); // get the start of the query results page // List resultObjects = null; qArgs.setQuery(query); qArgs.setStart(start); // Perform the search if (collection != null) { logInfo = "collection_id=" + collection.getID() + ","; // Values for drop-down box request.setAttribute("community", community); request.setAttribute("collection", collection); qResults = DSQuery.doQuery(context, qArgs, collection); } else if (community != null) { logInfo = "community_id=" + community.getID() + ","; request.setAttribute("community", community); // Get the collections within the community for the dropdown box request .setAttribute("collection.array", community .getCollections()); qResults = DSQuery.doQuery(context, qArgs, community); } else { // Get all communities for dropdown box Community[] communities = Community.findAll(context); request.setAttribute("community.array", communities); qResults = DSQuery.doQuery(context, qArgs); } // now instantiate the results and put them in their buckets for (int i = 0; i < qResults.getHitTypes().size(); i++) { Integer myType = qResults.getHitTypes().get(i); // add the handle to the appropriate lists switch (myType.intValue()) { case Constants.ITEM: itemCount++; break; case Constants.COLLECTION: collCount++; break; case Constants.COMMUNITY: commCount++; break; } } // Make objects from the handles - make arrays, fill them out resultsCommunities = new Community[commCount]; resultsCollections = new Collection[collCount]; resultsItems = new Item[itemCount]; collCount = 0; commCount = 0; itemCount = 0; for (int i = 0; i < qResults.getHitTypes().size(); i++) { Integer myId = qResults.getHitIds().get(i); String myHandle = qResults.getHitHandles().get(i); Integer myType = qResults.getHitTypes().get(i); // add the handle to the appropriate lists switch (myType.intValue()) { case Constants.ITEM: if (myId != null) { resultsItems[itemCount] = Item.find(context, myId); } else { resultsItems[itemCount] = (Item)HandleManager.resolveToObject(context, myHandle); } if (resultsItems[itemCount] == null) { throw new SQLException("Query \"" + query + "\" returned unresolvable item"); } itemCount++; break; case Constants.COLLECTION: if (myId != null) { resultsCollections[collCount] = Collection.find(context, myId); } else { resultsCollections[collCount] = (Collection)HandleManager.resolveToObject(context, myHandle); } if (resultsCollections[collCount] == null) { throw new SQLException("Query \"" + query + "\" returned unresolvable collection"); } collCount++; break; case Constants.COMMUNITY: if (myId != null) { resultsCommunities[commCount] = Community.find(context, myId); } else { resultsCommunities[commCount] = (Community)HandleManager.resolveToObject(context, myHandle); } if (resultsCommunities[commCount] == null) { throw new SQLException("Query \"" + query + "\" returned unresolvable community"); } commCount++; break; } } // Log log.info(LogManager.getHeader(context, "search", logInfo + "query=\"" + query + "\",results=(" + resultsCommunities.length + "," + resultsCollections.length + "," + resultsItems.length + ")")); // Pass in some page qualities // total number of pages int pageTotal = 1 + ((qResults.getHitCount() - 1) / qResults .getPageSize()); // current page being displayed int pageCurrent = 1 + (qResults.getStart() / qResults.getPageSize()); // pageLast = min(pageCurrent+9,pageTotal) int pageLast = ((pageCurrent + 9) > pageTotal) ? pageTotal : (pageCurrent + 9); // pageFirst = max(1,pageCurrent-9) int pageFirst = ((pageCurrent - 9) > 1) ? (pageCurrent - 9) : 1; // Pass the results to the display JSP request.setAttribute("items", resultsItems); request.setAttribute("communities", resultsCommunities); request.setAttribute("collections", resultsCollections); request.setAttribute("pagetotal", Integer.valueOf(pageTotal)); request.setAttribute("pagecurrent", Integer.valueOf(pageCurrent)); request.setAttribute("pagelast", Integer.valueOf(pageLast)); request.setAttribute("pagefirst", Integer.valueOf(pageFirst)); request.setAttribute("queryresults", qResults); // And the original query string request.setAttribute("query", query); request.setAttribute("order", qArgs.getSortOrder()); request.setAttribute("sortedBy", sortOption); if (AuthorizeManager.isAdmin(context)) { // Set a variable to create admin buttons request.setAttribute("admin_button", Boolean.TRUE); } if ((fromAdvanced != null) && (qResults.getHitCount() == 0)) { // send back to advanced form if no results Community[] communities = Community.findAll(context); request.setAttribute("communities", communities); request.setAttribute("no_results", "yes"); Map<String, String> queryHash = qArgs.buildQueryMap(request); if (queryHash != null) { for (Map.Entry<String, String> entry : queryHash.entrySet()) { request.setAttribute(entry.getKey(), entry.getValue()); } } JSPManager.showJSP(request, response, "/search/advanced.jsp"); } else if ("submit_export_metadata".equals(UIUtil.getSubmitButton(request, "submit"))) { exportMetadata(context, response, resultsItems); } else { JSPManager.showJSP(request, response, "/search/results.jsp"); } } /** * Export the search results as a csv file * * @param context The DSpace context * @param response The request object * @param items The result items * @throws IOException * @throws ServletException */ protected void exportMetadata(Context context, HttpServletResponse response, Item[] items) throws IOException, ServletException { // Log the attempt log.info(LogManager.getHeader(context, "metadataexport", "exporting_search")); // Export a search view List<Integer> iids = new ArrayList<Integer>(); for (Item item : items) { iids.add(item.getID()); } ItemIterator ii = new ItemIterator(context, iids); MetadataExport exporter = new MetadataExport(context, ii, false); // Perform the export DSpaceCSV csv = exporter.export(); // Return the csv file response.setContentType("text/csv; charset=UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=search-results.csv"); PrintWriter out = response.getWriter(); out.write(csv.toString()); out.flush(); out.close(); log.info(LogManager.getHeader(context, "metadataexport", "exported_file:search-results.csv")); return; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.jsp.jstl.core.Config; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.Authenticate; import org.dspace.app.webui.util.JSPManager; import org.dspace.authenticate.AuthenticationManager; import org.dspace.authenticate.AuthenticationMethod; import org.dspace.authorize.AuthorizeException; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.core.I18nUtil; import java.util.Locale; /** * LDAP username and password authentication servlet. Displays the * login form <code>/login/ldap.jsp</code> on a GET, * otherwise process the parameters as an ldap username and password. * * @author John Finlay (Brigham Young University) * @version $Revision: 5845 $ */ public class LDAPServlet extends DSpaceServlet { /** log4j logger */ private static Logger log = Logger.getLogger(LDAPServlet.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // check if ldap is enables and forward to the correct login form boolean ldap_enabled = ConfigurationManager.getBooleanProperty("ldap.enable"); if (ldap_enabled) { JSPManager.showJSP(request, response, "/login/ldap.jsp"); } else { JSPManager.showJSP(request, response, "/login/password.jsp"); } } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Process the POSTed email and password String netid = request.getParameter("login_netid"); String password = request.getParameter("login_password"); String jsp = null; // Locate the eperson int status = AuthenticationManager.authenticate(context, netid, password, null, request); if (status == AuthenticationMethod.SUCCESS) { // Logged in OK. Authenticate.loggedIn(context, request, context.getCurrentUser()); // Set the Locale according to user preferences Locale epersonLocale = I18nUtil.getEPersonLocale(context.getCurrentUser()); context.setCurrentLocale(epersonLocale); Config.set(request.getSession(), Config.FMT_LOCALE, epersonLocale); log.info(LogManager.getHeader(context, "login", "type=explicit")); // resume previous request Authenticate.resumeInterruptedRequest(request, response); return; } else if (status == AuthenticationMethod.CERT_REQUIRED) { jsp = "/error/require-certificate.jsp"; } else { jsp = "/login/incorrect.jsp"; } // If we reach here, supplied email/password was duff. log.info(LogManager.getHeader(context, "failed_login", "netid=" + netid + ", result=" + String.valueOf(status))); JSPManager.showJSP(request, response, jsp); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import org.apache.log4j.Logger; import org.dspace.core.ConfigurationManager; import javax.servlet.http.HttpServlet; import java.net.URL; import java.net.URLConnection; /** * Simple servlet to load in DSpace and log4j configurations. Should always be * started up before other servlets (use <loadOnStartup>) * * This class holds code to be removed in the next version of the DSpace XMLUI, * it is now managed by a Shared Context Listener inthe dspace-api project. * * It is deprecated, rather than removed to maintain backward compatibility for * local DSpace 1.5.x customized overlays. * * TODO: Remove in trunk * * @deprecated Use Servlet Context Listener provided in dspace-api (remove in > * 1.5.x) * @author Robert Tansley * @version $Revision: 5845 $ */ public class LoadDSpaceConfig extends HttpServlet { private static final Logger LOG = Logger.getLogger(LoadDSpaceConfig.class); public void init() { // On Windows, URL caches can cause problems, particularly with undeployment // So, here we attempt to disable them if we detect that we are running on Windows try { String osName = System.getProperty("os.name"); if (osName != null) { osName = osName.toLowerCase(); } if (osName != null && osName.contains("windows")) { URL url = new URL("http://localhost/"); URLConnection urlConn = url.openConnection(); urlConn.setDefaultUseCaches(false); } } // Any errors thrown in disabling the caches aren't significant to // the normal execution of the application, so we ignore them catch (RuntimeException e) { LOG.error(e.getMessage(), e); } catch (Exception e) { LOG.error(e.getMessage(), e); } if(!ConfigurationManager.isConfigured()) { // Get config parameter String config = getServletContext().getInitParameter("dspace-config"); // Load in DSpace config ConfigurationManager.loadConfig(config); } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.io.StringWriter; import java.net.URLEncoder; import java.sql.SQLException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; import org.apache.log4j.Logger; import org.dspace.app.util.GoogleMetadata; import org.dspace.app.webui.util.Authenticate; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.content.crosswalk.CrosswalkException; import org.dspace.content.crosswalk.DisseminationCrosswalk; import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.core.PluginManager; import org.dspace.eperson.EPerson; import org.dspace.eperson.Group; import org.dspace.eperson.Subscribe; import org.dspace.handle.HandleManager; import org.dspace.plugin.CollectionHomeProcessor; import org.dspace.plugin.CommunityHomeProcessor; import org.dspace.usage.UsageEvent; import org.dspace.utils.DSpace; import org.jdom.Element; import org.jdom.Text; import org.jdom.output.XMLOutputter; /** * Servlet for handling requests within a community or collection. The Handle is * extracted from the URL, e.g: <code>/community/1721.1/1234</code>. If there * is anything after the Handle, the request is forwarded to the appropriate * servlet. For example: * <P> * <code>/community/1721.1/1234/simple-search</code> * <P> * would be forwarded to <code>/simple-search</code>. If there is nothing * after the Handle, the community or collection home page is shown. * * @author Robert Tansley * @version $Revision: 5845 $ */ @SuppressWarnings("deprecation") public class HandleServlet extends DSpaceServlet { /** log4j category */ private static Logger log = Logger.getLogger(DSpaceServlet.class); /** For obtaining &lt;meta&gt; elements to put in the &lt;head&gt; */ private DisseminationCrosswalk xHTMLHeadCrosswalk; public HandleServlet() { super(); xHTMLHeadCrosswalk = (DisseminationCrosswalk) PluginManager .getNamedPlugin(DisseminationCrosswalk.class, "XHTML_HEAD_ITEM"); } protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String handle = null; String extraPathInfo = null; DSpaceObject dso = null; // Original path info, of the form "1721.x/1234" // or "1721.x/1234/extra/stuff" String path = request.getPathInfo(); if (path != null) { // substring(1) is to remove initial '/' path = path.substring(1); try { // Extract the Handle int firstSlash = path.indexOf('/'); int secondSlash = path.indexOf('/', firstSlash + 1); if (secondSlash != -1) { // We have extra path info handle = path.substring(0, secondSlash); extraPathInfo = path.substring(secondSlash); } else { // The path is just the Handle handle = path; } } catch (NumberFormatException nfe) { // Leave handle as null } } // Find out what the handle relates to if (handle != null) { dso = HandleManager.resolveToObject(context, handle); } if (dso == null) { log.info(LogManager .getHeader(context, "invalid_id", "path=" + path)); JSPManager.showInvalidIDError(request, response, StringEscapeUtils.escapeHtml(path), -1); return; } // OK, we have a valid Handle. What is it? if (dso.getType() == Constants.ITEM) { Item item = (Item) dso; new DSpace().getEventService().fireEvent( new UsageEvent( UsageEvent.Action.VIEW, request, context, dso)); // Only use last-modified if this is an anonymous access // - caching content that may be generated under authorisation // is a security problem if (context.getCurrentUser() == null) { response.setDateHeader("Last-Modified", item .getLastModified().getTime()); // Check for if-modified-since header long modSince = request.getDateHeader("If-Modified-Since"); if (modSince != -1 && item.getLastModified().getTime() < modSince) { // Item has not been modified since requested date, // hence bitstream has not; return 304 response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { // Display the item page displayItem(context, request, response, item, handle); } } else { // Display the item page displayItem(context, request, response, item, handle); } } else if (dso.getType() == Constants.COLLECTION) { Collection c = (Collection) dso; new DSpace().getEventService().fireEvent( new UsageEvent( UsageEvent.Action.VIEW, request, context, dso)); //UsageEvent ue = new UsageEvent(); //ue.fire(request, context, AbstractUsageEvent.VIEW, // Constants.COLLECTION, dso.getID()); // Store collection location in request request.setAttribute("dspace.collection", c); /* * Find the "parent" community the collection, mainly for * "breadcrumbs" FIXME: At the moment, just grab the first community * the collection is in. This should probably be more context * sensitive when we have multiple inclusion. */ Community[] parents = c.getCommunities(); request.setAttribute("dspace.community", parents[0]); /* * Find all the "parent" communities for the collection for * "breadcrumbs" */ request.setAttribute("dspace.communities", getParents(parents[0], true)); // home page, or forward to another page? if ((extraPathInfo == null) || (extraPathInfo.equals("/"))) { collectionHome(context, request, response, parents[0], c); } else { // Forward to another servlet request.getRequestDispatcher(extraPathInfo).forward(request, response); } } else if (dso.getType() == Constants.COMMUNITY) { Community c = (Community) dso; new DSpace().getEventService().fireEvent( new UsageEvent( UsageEvent.Action.VIEW, request, context, dso)); //UsageEvent ue = new UsageEvent(); //ue.fire(request, context, AbstractUsageEvent.VIEW, // Constants.COMMUNITY, dso.getID()); // Store collection location in request request.setAttribute("dspace.community", c); /* * Find all the "parent" communities for the community */ request.setAttribute("dspace.communities", getParents(c, false)); // home page, or forward to another page? if ((extraPathInfo == null) || (extraPathInfo.equals("/"))) { communityHome(context, request, response, c); } else { // Forward to another servlet request.getRequestDispatcher(extraPathInfo).forward(request, response); } } else { // Shouldn't happen. Log and treat as invalid ID log.info(LogManager.getHeader(context, "Handle not an item, collection or community", "handle=" + handle)); JSPManager.showInvalidIDError(request, response, StringEscapeUtils.escapeHtml(path), -1); return; } } /** * Show an item page * * @param context * Context object * @param request * the HTTP request * @param response * the HTTP response * @param item * the item * @param handle * the item's handle */ private void displayItem(Context context, HttpServletRequest request, HttpServletResponse response, Item item, String handle) throws ServletException, IOException, SQLException, AuthorizeException { // Tombstone? if (item.isWithdrawn()) { JSPManager.showJSP(request, response, "/tombstone.jsp"); return; } // Ensure the user has authorisation AuthorizeManager.authorizeAction(context, item, Constants.READ); log .info(LogManager.getHeader(context, "view_item", "handle=" + handle)); // show edit link if (item.canEdit()) { // set a variable to create an edit button request.setAttribute("admin_button", Boolean.TRUE); } // Get the collections Collection[] collections = item.getCollections(); // For the breadcrumbs, get the first collection and the first community // that is in. FIXME: Not multiple-inclusion friendly--should be // smarter, context-sensitive request.setAttribute("dspace.collection", item.getOwningCollection()); Community[] comms = item.getOwningCollection().getCommunities(); request.setAttribute("dspace.community", comms[0]); /* * Find all the "parent" communities for the collection */ request.setAttribute("dspace.communities", getParents(comms[0], true)); // Full or simple display? boolean displayAll = false; String modeParam = request.getParameter("mode"); if ((modeParam != null) && modeParam.equalsIgnoreCase("full")) { displayAll = true; } String headMetadata = ""; // Produce <meta> elements for header from crosswalk try { List<Element> l = xHTMLHeadCrosswalk.disseminateList(item); StringWriter sw = new StringWriter(); XMLOutputter xmlo = new XMLOutputter(); xmlo.output(new Text("\n"), sw); for (Element e : l) { // FIXME: we unset the Namespace so it's not printed. // This is fairly yucky, but means the same crosswalk should // work for Manakin as well as the JSP-based UI. e.setNamespace(null); xmlo.output(e, sw); xmlo.output(new Text("\n"), sw); } boolean googleEnabled = ConfigurationManager.getBooleanProperty("google-metadata.enable", false); if (googleEnabled) { // Add Google metadata field names & values GoogleMetadata gmd = new GoogleMetadata(context, item); xmlo.output(new Text("\n"), sw); for (Element e: gmd.disseminateList()) { xmlo.output(e, sw); xmlo.output(new Text("\n"), sw); } } headMetadata = sw.toString(); } catch (CrosswalkException ce) { throw new ServletException(ce); } // Enable suggest link or not boolean suggestEnable = false; if (!ConfigurationManager.getBooleanProperty("webui.suggest.enable")) { // do nothing, the suggestLink is allready set to false } else { // it is in general enabled suggestEnable= true; // check for the enable only for logged in users option if(!ConfigurationManager.getBooleanProperty("webui.suggest.loggedinusers.only")) { // do nothing, the suggestLink stays as it is } else { // check whether there is a logged in user suggestEnable = (context.getCurrentUser() == null ? false : true); } } // Set attributes and display request.setAttribute("suggest.enable", Boolean.valueOf(suggestEnable)); request.setAttribute("display.all", Boolean.valueOf(displayAll)); request.setAttribute("item", item); request.setAttribute("collections", collections); request.setAttribute("dspace.layout.head", headMetadata); JSPManager.showJSP(request, response, "/display-item.jsp"); } /** * Show a community home page, or deal with button press on home page * * @param context * Context object * @param request * the HTTP request * @param response * the HTTP response * @param community * the community */ private void communityHome(Context context, HttpServletRequest request, HttpServletResponse response, Community community) throws ServletException, IOException, SQLException { // Handle click on a browse or search button if (!handleButton(request, response, community.getHandle())) { // No button pressed, display community home page log.info(LogManager.getHeader(context, "view_community", "community_id=" + community.getID())); // Get the collections within the community Collection[] collections = community.getCollections(); // get any subcommunities of the community Community[] subcommunities = community.getSubcommunities(); // perform any necessary pre-processing preProcessCommunityHome(context, request, response, community); // is the user a COMMUNITY_EDITOR? if (community.canEditBoolean()) { // set a variable to create an edit button request.setAttribute("editor_button", Boolean.TRUE); } // can they add to this community? if (AuthorizeManager.authorizeActionBoolean(context, community, Constants.ADD)) { // set a variable to create an edit button request.setAttribute("add_button", Boolean.TRUE); } // can they remove from this community? if (AuthorizeManager.authorizeActionBoolean(context, community, Constants.REMOVE)) { // set a variable to create an edit button request.setAttribute("remove_button", Boolean.TRUE); } // Forward to community home page request.setAttribute("community", community); request.setAttribute("collections", collections); request.setAttribute("subcommunities", subcommunities); JSPManager.showJSP(request, response, "/community-home.jsp"); } } private void preProcessCommunityHome(Context context, HttpServletRequest request, HttpServletResponse response, Community community) throws ServletException, IOException, SQLException { try { CommunityHomeProcessor[] chp = (CommunityHomeProcessor[]) PluginManager.getPluginSequence(CommunityHomeProcessor.class); for (int i = 0; i < chp.length; i++) { chp[i].process(context, request, response, community); } } catch (Exception e) { log.error("caught exception: ", e); throw new ServletException(e); } } /** * Show a collection home page, or deal with button press on home page * * @param context * Context object * @param request * the HTTP request * @param response * the HTTP response * @param community * the community * @param collection * the collection */ private void collectionHome(Context context, HttpServletRequest request, HttpServletResponse response, Community community, Collection collection) throws ServletException, IOException, SQLException, AuthorizeException { // Handle click on a browse or search button if (!handleButton(request, response, collection.getHandle())) { // Will need to know whether to commit to DB boolean updated = false; // No search or browse button pressed, check for if (request.getParameter("submit_subscribe") != null) { // Subscribe button pressed. // Only registered can subscribe, so redirect unless logged in. if (context.getCurrentUser() == null && !Authenticate .startAuthentication(context, request, response)) { return; } else { Subscribe.subscribe(context, context.getCurrentUser(), collection); updated = true; } } else if (request.getParameter("submit_unsubscribe") != null) { Subscribe.unsubscribe(context, context.getCurrentUser(), collection); updated = true; } // display collection home page log.info(LogManager.getHeader(context, "view_collection", "collection_id=" + collection.getID())); // perform any necessary pre-processing preProcessCollectionHome(context, request, response, collection); // Is the user logged in/subscribed? EPerson e = context.getCurrentUser(); boolean subscribed = false; if (e != null) { subscribed = Subscribe.isSubscribed(context, e, collection); // is the user a COLLECTION_EDITOR? if (collection.canEditBoolean(true)) { // set a variable to create an edit button request.setAttribute("editor_button", Boolean.TRUE); } // can they admin this collection? if (AuthorizeManager.authorizeActionBoolean(context, collection, Constants.COLLECTION_ADMIN)) { request.setAttribute("admin_button", Boolean.TRUE); // give them a button to manage submitter list // what group is the submitter? Group group = collection.getSubmitters(); if (group != null) { request.setAttribute("submitters", group); } } // can they submit to this collection? if (AuthorizeManager.authorizeActionBoolean(context, collection, Constants.ADD)) { request .setAttribute("can_submit_button", Boolean.TRUE); } else { request.setAttribute("can_submit_button", Boolean.FALSE); } } // Forward to collection home page request.setAttribute("collection", collection); request.setAttribute("community", community); request.setAttribute("logged.in", Boolean.valueOf(e != null)); request.setAttribute("subscribed", Boolean.valueOf(subscribed)); JSPManager.showJSP(request, response, "/collection-home.jsp"); if (updated) { context.complete(); } } } private void preProcessCollectionHome(Context context, HttpServletRequest request, HttpServletResponse response, Collection collection) throws ServletException, IOException, SQLException { try { CollectionHomeProcessor[] chp = (CollectionHomeProcessor[]) PluginManager.getPluginSequence(CollectionHomeProcessor.class); for (int i = 0; i < chp.length; i++) { chp[i].process(context, request, response, collection); } } catch (Exception e) { log.error("caught exception: ", e); throw new ServletException(e); } } /** * Check to see if a browse or search button has been pressed on a community * or collection home page. If so, redirect to the appropriate URL. * * @param request * HTTP request * @param response * HTTP response * @param handle * Handle of the community/collection home page * * @return true if a browse/search button was pressed and the user was * redirected */ private boolean handleButton(HttpServletRequest request, HttpServletResponse response, String handle) throws IOException { String button = UIUtil.getSubmitButton(request, ""); String location = request.getParameter("location"); String prefix = "/"; String url = null; if (location == null) { return false; } /* * Work out the "prefix" to which to redirect If "/", scope is all of * DSpace, so prefix is "/" If prefix is a handle, scope is a community * or collection, so "/handle/1721.x/xxxx/" is the prefix. */ if (!location.equals("/")) { prefix = "/handle/" + location + "/"; } if (button.equals("submit_search") || (request.getParameter("query") != null)) { /* * Have to check for search button and query - in some browsers, * typing a query into the box and hitting return doesn't produce a * submit button parameter. Redirect to appropriate search page */ url = request.getContextPath() + prefix + "simple-search?query=" + URLEncoder.encode(request.getParameter("query"), Constants.DEFAULT_ENCODING); } // If a button was pressed, redirect to appropriate page if (url != null) { response.sendRedirect(response.encodeRedirectURL(url)); return true; } return false; } /** * Utility method to produce a list of parent communities for a given * community, ending with the passed community, if include is true. If * commmunity is top-level, the array will be empty, or contain only the * passed community, if include is true. The array is ordered highest level * to lowest */ private Community[] getParents(Community c, boolean include) throws SQLException { // Find all the "parent" communities for the community Community[] parents = c.getAllParents(); // put into an array in reverse order int revLength = include ? (parents.length + 1) : parents.length; Community[] reversedParents = new Community[revLength]; int index = parents.length - 1; for (int i = 0; i < parents.length; i++) { reversedParents[i] = parents[index - i]; } if (include) { reversedParents[revLength - 1] = c; } return reversedParents; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet.admin; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dspace.app.webui.servlet.DSpaceServlet; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; /** * Servlet for editing the front page news * * @author gcarpent */ public class NewsEditServlet extends DSpaceServlet { protected void doDSGet(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { //always go first to news-main.jsp JSPManager.showJSP(request, response, "/dspace-admin/news-main.jsp"); } protected void doDSPost(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { //Get submit button String button = UIUtil.getSubmitButton(request, "submit"); String news = ""; //Are we editing the top news or the sidebar news? String position = request.getParameter("position"); if (button.equals("submit_edit")) { //get the existing text from the file news = ConfigurationManager.readNewsFile(position); //pass the position back to the JSP request.setAttribute("position", position); //pass the existing news back to the JSP request.setAttribute("news", news); //show news edit page JSPManager .showJSP(request, response, "/dspace-admin/news-edit.jsp"); } else if (button.equals("submit_save")) { //get text string from form news = (String) request.getParameter("news"); //write the string out to file ConfigurationManager.writeNewsFile(position, news); JSPManager .showJSP(request, response, "/dspace-admin/news-main.jsp"); } else { //the user hit cancel, so return to the main news edit page JSPManager .showJSP(request, response, "/dspace-admin/news-main.jsp"); } c.complete(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet.admin; import org.apache.log4j.Logger; import org.dspace.app.webui.servlet.DSpaceServlet; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.browse.*; import org.dspace.content.Collection; import org.dspace.content.Item; import org.dspace.content.ItemIterator; import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.sort.SortOption; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; /** * Servlet for editing and deleting (expunging) items * * @version $Revision: 5845 $ */ public class ItemMapServlet extends DSpaceServlet { /** Logger */ private static Logger log = Logger.getLogger(ItemMapServlet.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws java.sql.SQLException, javax.servlet.ServletException, java.io.IOException, AuthorizeException { doDSPost(context, request, response); } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws java.sql.SQLException, javax.servlet.ServletException, java.io.IOException, AuthorizeException { String jspPage = null; // get with a collection ID means put up browse window int myID = UIUtil.getIntParameter(request, "cid"); // get collection Collection myCollection = Collection.find(context, myID); // authorize check AuthorizeManager.authorizeAction(context, myCollection, Constants.COLLECTION_ADMIN); String action = request.getParameter("action"); if (action == null) { action = ""; } // Defined non-empty value shows that 'Cancel' has been pressed String cancel = request.getParameter("cancel"); if (cancel == null) { cancel = ""; } if (action.equals("") || !cancel.equals("")) { // get with no action parameter set means to put up the main page // which is statistics and some command buttons to add/remove items // // also holds for interruption by pressing 'Cancel' int count_native = 0; // # of items owned by this collection int count_import = 0; // # of virtual items Map<Integer, Item> myItems = new HashMap<Integer, Item>(); // # for the browser Map<Integer, Collection> myCollections = new HashMap<Integer, Collection>(); // collections for list Map<Integer, Integer> myCounts = new HashMap<Integer, Integer>(); // counts for each collection // get all items from that collection, add them to a hash ItemIterator i = myCollection.getItems(); try { // iterate through the items in this collection, and count how many // are native, and how many are imports, and which collections they // came from while (i.hasNext()) { Item myItem = i.next(); // get key for hash Integer myKey = Integer.valueOf(myItem.getID()); if (myItem.isOwningCollection(myCollection)) { count_native++; } else { count_import++; } // is the collection in the hash? Collection owningCollection = myItem.getOwningCollection(); Integer cKey = Integer.valueOf(owningCollection.getID()); if (myCollections.containsKey(cKey)) { Integer x = myCounts.get(cKey); int myCount = x.intValue() + 1; // increment count for that collection myCounts.put(cKey, Integer.valueOf(myCount)); } else { // store and initialize count myCollections.put(cKey, owningCollection); myCounts.put(cKey, Integer.valueOf(1)); } // store the item myItems.put(myKey, myItem); } } finally { if (i != null) { i.close(); } } // remove this collection's entry because we already have a native // count myCollections.remove(Integer.valueOf(myCollection.getID())); // sort items - later // show page request.setAttribute("collection", myCollection); request.setAttribute("count_native", Integer.valueOf(count_native)); request.setAttribute("count_import", Integer.valueOf(count_import)); request.setAttribute("items", myItems); request.setAttribute("collections", myCollections); request.setAttribute("collection_counts", myCounts); request .setAttribute("all_collections", Collection .findAll(context)); // show this page when we're done jspPage = "itemmap-main.jsp"; // show the page JSPManager.showJSP(request, response, jspPage); } else if (action.equals("Remove")) { // get item IDs to remove String[] itemIDs = request.getParameterValues("item_ids"); String message = "remove"; LinkedList<String> removedItems = new LinkedList<String>(); if (itemIDs == null) { message = "none-removed"; } else { for (int j = 0; j < itemIDs.length; j++) { int i = Integer.parseInt(itemIDs[j]); removedItems.add(itemIDs[j]); Item myItem = Item.find(context, i); // make sure item doesn't belong to this collection if (!myItem.isOwningCollection(myCollection)) { myCollection.removeItem(myItem); try { IndexBrowse ib = new IndexBrowse(context); ib.indexItem(myItem); } catch (BrowseException e) { log.error("caught exception: ", e); throw new ServletException(e); } } } } request.setAttribute("message", message); request.setAttribute("collection", myCollection); request.setAttribute("processedItems", removedItems); // show this page when we're done jspPage = "itemmap-info.jsp"; // show the page JSPManager.showJSP(request, response, jspPage); } else if (action.equals("Add")) { // get item IDs to add String[] itemIDs = request.getParameterValues("item_ids"); String message = "added"; LinkedList<String> addedItems = new LinkedList<String>(); if (itemIDs == null) { message = "none-selected"; } else { for (int j = 0; j < itemIDs.length; j++) { int i = Integer.parseInt(itemIDs[j]); Item myItem = Item.find(context, i); if (AuthorizeManager.authorizeActionBoolean(context, myItem, Constants.READ)) { // make sure item doesn't belong to this collection if (!myItem.isOwningCollection(myCollection)) { myCollection.addItem(myItem); try { IndexBrowse ib = new IndexBrowse(context); ib.indexItem(myItem); } catch (BrowseException e) { log.error("caught exception: ", e); throw new ServletException(e); } addedItems.add(itemIDs[j]); } } } } request.setAttribute("message", message); request.setAttribute("collection", myCollection); request.setAttribute("processedItems", addedItems); // show this page when we're done jspPage = "itemmap-info.jsp"; // show the page JSPManager.showJSP(request, response, jspPage); } else if (action.equals("Search Authors")) { String name = (String) request.getParameter("namepart"); String bidx = ConfigurationManager.getProperty("itemmap.author.index"); if (bidx == null) { throw new ServletException("There is no configuration for itemmap.author.index"); } Map<Integer, Item> items = new HashMap<Integer, Item>(); try { BrowserScope bs = new BrowserScope(context); BrowseIndex bi = BrowseIndex.getBrowseIndex(bidx); // set up the browse scope bs.setBrowseIndex(bi); bs.setOrder(SortOption.ASCENDING); bs.setFilterValue(name); bs.setFilterValuePartial(true); bs.setJumpToValue(null); bs.setResultsPerPage(10000); // an arbitrary number (large) for the time being bs.setBrowseLevel(1); BrowseEngine be = new BrowseEngine(context); BrowseInfo results = be.browse(bs); Item[] browseItems = results.getItemResults(context); // FIXME: oh god this is so annoying - what an API /Richard // we need to deduplicate against existing items in this collection ItemIterator itr = myCollection.getItems(); try { ArrayList<Integer> idslist = new ArrayList<Integer>(); while (itr.hasNext()) { idslist.add(Integer.valueOf(itr.nextID())); } for (int i = 0; i < browseItems.length; i++) { // only if it isn't already in this collection if (!idslist.contains(Integer.valueOf(browseItems[i].getID()))) { // only put on list if you can read item if (AuthorizeManager.authorizeActionBoolean(context, browseItems[i], Constants.READ)) { items.put(Integer.valueOf(browseItems[i].getID()), browseItems[i]); } } } } finally { if (itr != null) { itr.close(); } } } catch (BrowseException e) { log.error("caught exception: ", e); throw new ServletException(e); } request.setAttribute("collection", myCollection); request.setAttribute("browsetext", name); request.setAttribute("items", items); request.setAttribute("browsetype", "Add"); jspPage = "itemmap-browse.jsp"; JSPManager.showJSP(request, response, jspPage); } else if (action.equals("browse")) { // target collection to browse int t = UIUtil.getIntParameter(request, "t"); Collection targetCollection = Collection.find(context, t); // now find all imported items from that collection // seemingly inefficient, but database should have this query cached Map<Integer, Item> items = new HashMap<Integer, Item>(); ItemIterator i = myCollection.getItems(); try { while (i.hasNext()) { Item myItem = i.next(); if (myItem.isOwningCollection(targetCollection)) { Integer myKey = Integer.valueOf(myItem.getID()); items.put(myKey, myItem); } } } finally { if (i != null) { i.close(); } } request.setAttribute("collection", myCollection); request.setAttribute("browsetext", targetCollection .getMetadata("name")); request.setAttribute("items", items); request.setAttribute("browsetype", "Remove"); // show this page when we're done jspPage = "itemmap-browse.jsp"; // show the page JSPManager.showJSP(request, response, jspPage); } context.complete(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet.admin; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.dspace.app.util.AuthorizeUtil; import org.dspace.app.webui.servlet.DSpaceServlet; import org.dspace.app.webui.util.FileUploadRequest; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.authorize.ResourcePolicy; import org.dspace.content.Bitstream; import org.dspace.content.BitstreamFormat; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.FormatIdentifier; import org.dspace.content.Item; import org.dspace.content.MetadataField; import org.dspace.content.MetadataSchema; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.eperson.EPerson; import org.dspace.eperson.Group; /** * Collection creation wizard UI * * @author Robert Tansley * @version $Revision: 6158 $ */ public class CollectionWizardServlet extends DSpaceServlet { /** Initial questions page */ public static final int INITIAL_QUESTIONS = 1; /** Basic information page */ public static final int BASIC_INFO = 2; /** Permissions pages */ public static final int PERMISSIONS = 3; /** Default item page */ public static final int DEFAULT_ITEM = 4; /** Summary page */ public static final int SUMMARY = 5; /** Permissions page for who gets read permissions on new items */ public static final int PERM_READ = 10; /** Permissions page for submitters */ public static final int PERM_SUBMIT = 11; /** Permissions page for workflow step 1 */ public static final int PERM_WF1 = 12; /** Permissions page for workflow step 2 */ public static final int PERM_WF2 = 13; /** Permissions page for workflow step 3 */ public static final int PERM_WF3 = 14; /** Permissions page for collection administrators */ public static final int PERM_ADMIN = 15; /** Logger */ private static Logger log = Logger.getLogger(CollectionWizardServlet.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { /* * For GET, all we should really get is a community_id parameter (DB ID * of community to add collection to). doDSPost handles this */ doDSPost(context, request, response); } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { /* * For POST, we expect from the form: * * community_id DB ID if it was a 'create a new collection' button press * * OR * * collection_id DB ID of collection we're dealing with stage Stage * we're at (from constants above) */ // First, see if we have a multipart request // (the 'basic info' page which might include uploading a logo) String contentType = request.getContentType(); if ((contentType != null) && (contentType.indexOf("multipart/form-data") != -1)) { // This is a multipart request, so it's a file upload processBasicInfo(context, request, response); return; } int communityID = UIUtil.getIntParameter(request, "community_id"); if (communityID > -1) { // We have a community ID, "create new collection" button pressed Community c = Community.find(context, communityID); if (c == null) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil.getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } // Create the collection Collection newCollection = c.createCollection(); request.setAttribute("collection", newCollection); if (AuthorizeManager.isAdmin(context)) { // set a variable to show all buttons request.setAttribute("sysadmin_button", Boolean.TRUE); } try { AuthorizeUtil.authorizeManageAdminGroup(context, newCollection); request.setAttribute("admin_create_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("admin_create_button", Boolean.FALSE); } try { AuthorizeUtil.authorizeManageSubmittersGroup(context, newCollection); request.setAttribute("submitters_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("submitters_button", Boolean.FALSE); } try { AuthorizeUtil.authorizeManageWorkflowsGroup(context, newCollection); request.setAttribute("workflows_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("workflows_button", Boolean.FALSE); } try { AuthorizeUtil.authorizeManageTemplateItem(context, newCollection); request.setAttribute("template_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("template_button", Boolean.FALSE); } JSPManager.showJSP(request, response, "/dspace-admin/wizard-questions.jsp"); context.complete(); } else { // Collection already created, dealing with one of the wizard pages int collectionID = UIUtil.getIntParameter(request, "collection_id"); int stage = UIUtil.getIntParameter(request, "stage"); // Get the collection Collection collection = Collection.find(context, collectionID); // Put it in request attributes, as most JSPs will need it request.setAttribute("collection", collection); if (collection == null) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil.getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } // All pages will need this attribute request.setAttribute("collection.id", String.valueOf(collection .getID())); switch (stage) { case INITIAL_QUESTIONS: processInitialQuestions(context, request, response, collection); break; case PERMISSIONS: processPermissions(context, request, response, collection); break; case DEFAULT_ITEM: processDefaultItem(context, request, response, collection); break; default: log.warn(LogManager.getHeader(context, "integrity_error", UIUtil.getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); } } } /** * Process input from initial questions page * * @param context * DSpace context * @param request * HTTP request * @param response * HTTP response * @param collection * Collection we're editing */ private void processInitialQuestions(Context context, HttpServletRequest request, HttpServletResponse response, Collection collection) throws SQLException, ServletException, IOException, AuthorizeException { // "Public read" checkbox. Only need to do anything // if it's not checked (only system admin can uncheck this!). if (!UIUtil.getBoolParameter(request, "public_read") && AuthorizeManager.isAdmin(context)) { // Remove anonymous default policies for new items AuthorizeManager.removePoliciesActionFilter(context, collection, Constants.DEFAULT_ITEM_READ); AuthorizeManager.removePoliciesActionFilter(context, collection, Constants.DEFAULT_BITSTREAM_READ); } // Some people authorised to submit if (UIUtil.getBoolParameter(request, "submitters")) { // Create submitters group collection.createSubmitters(); } // Check for the workflow steps for (int i = 1; i <= 3; i++) { if (UIUtil.getBoolParameter(request, "workflow" + i)) { // should have workflow step i collection.createWorkflowGroup(i); } } // Check for collection administrators if (UIUtil.getBoolParameter(request, "admins")) { // Create administrators group collection.createAdministrators(); } // Default item stuff? if (UIUtil.getBoolParameter(request, "default.item")) { collection.createTemplateItem(); } // Need to set a name so that the indexer won't throw an exception collection.setMetadata("name", ""); collection.update(); // Now display "basic info" screen JSPManager.showJSP(request, response, "/dspace-admin/wizard-basicinfo.jsp"); context.complete(); } /** * Process input from one of the permissions pages * * @param context * DSpace context * @param request * HTTP request * @param response * HTTP response * @param collection * Collection we're editing */ private void processPermissions(Context context, HttpServletRequest request, HttpServletResponse response, Collection collection) throws SQLException, ServletException, IOException, AuthorizeException { // Which permission are we dealing with? int permission = UIUtil.getIntParameter(request, "permission"); // First, we deal with the special case of the MIT group... if (UIUtil.getBoolParameter(request, "mitgroup")) { Group mitGroup = Group.findByName(context, "MIT Users"); if (permission == PERM_READ) { // assign default item and bitstream read to mitGroup AuthorizeManager.addPolicy(context, collection, Constants.DEFAULT_ITEM_READ, mitGroup); AuthorizeManager.addPolicy(context, collection, Constants.DEFAULT_BITSTREAM_READ, mitGroup); } else { // Must be submit AuthorizeManager.addPolicy(context, collection, Constants.ADD, mitGroup); } } //We need to add the selected people to the group. // First, get the relevant group Group g = null; switch (permission) { case PERM_READ: // Actually need to create a group for this. g = Group.create(context); // Name it according to our conventions g .setName("COLLECTION_" + collection.getID() + "_DEFAULT_ITEM_READ"); // Give it the needed permission AuthorizeManager.addPolicy(context, collection, Constants.DEFAULT_ITEM_READ, g); AuthorizeManager.addPolicy(context, collection, Constants.DEFAULT_BITSTREAM_READ, g); break; case PERM_SUBMIT: g = collection.getSubmitters(); break; case PERM_WF1: g = collection.getWorkflowGroup(1); break; case PERM_WF2: g = collection.getWorkflowGroup(2); break; case PERM_WF3: g = collection.getWorkflowGroup(3); break; case PERM_ADMIN: g = collection.getAdministrators(); break; } // Add people and groups from the form to the group int[] epersonIds = UIUtil.getIntParameters(request, "eperson_id"); int[] groupIds = UIUtil.getIntParameters(request, "group_ids"); if (epersonIds != null) { for (int i = 0; i < epersonIds.length; i++) { EPerson eperson = EPerson.find(context, epersonIds[i]); if (eperson != null) { g.addMember(eperson); } } } if (groupIds != null) { for (int i = 0; i < groupIds.length; i++) { Group group = Group.find(context, groupIds[i]); if (group != null) { g.addMember(group); } } } // Update group g.update(); showNextPage(context, request, response, collection, permission); context.complete(); } /** * process input from basic info page * * @param context * @param request * @param response * @param collection * @throws SQLException * @throws ServletException * @throws IOException * @throws AuthorizeException */ private void processBasicInfo(Context context, HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException, AuthorizeException { try { // Wrap multipart request to get the submission info FileUploadRequest wrapper = new FileUploadRequest(request); Collection collection = Collection.find(context, UIUtil.getIntParameter(wrapper, "collection_id")); if (collection == null) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil.getRequestLogInfo(wrapper))); JSPManager.showIntegrityError(request, response); return; } // Get metadata collection.setMetadata("name", wrapper.getParameter("name")); collection.setMetadata("short_description", wrapper.getParameter("short_description")); collection.setMetadata("introductory_text", wrapper.getParameter("introductory_text")); collection.setMetadata("copyright_text", wrapper.getParameter("copyright_text")); collection.setMetadata("side_bar_text", wrapper.getParameter("side_bar_text")); collection.setMetadata("provenance_description", wrapper.getParameter("provenance_description")); // Need to be more careful about license -- make sure it's null if // nothing was entered String license = wrapper.getParameter("license"); if (!StringUtils.isEmpty(license)) { collection.setLicense(license); } File temp = wrapper.getFile("file"); if (temp != null) { // Read the temp file as logo InputStream is = new BufferedInputStream(new FileInputStream(temp)); Bitstream logoBS = collection.setLogo(is); // Strip all but the last filename. It would be nice // to know which OS the file came from. String noPath = wrapper.getFilesystemName("file"); while (noPath.indexOf('/') > -1) { noPath = noPath.substring(noPath.indexOf('/') + 1); } while (noPath.indexOf('\\') > -1) { noPath = noPath.substring(noPath.indexOf('\\') + 1); } logoBS.setName(noPath); logoBS.setSource(wrapper.getFilesystemName("file")); // Identify the format BitstreamFormat bf = FormatIdentifier.guessFormat(context, logoBS); logoBS.setFormat(bf); AuthorizeManager.addPolicy(context, logoBS, Constants.WRITE, context.getCurrentUser()); logoBS.update(); // Remove temp file if (!temp.delete()) { log.trace("Unable to delete temporary file"); } } collection.update(); // Now work out what next page is showNextPage(context, request, response, collection, BASIC_INFO); context.complete(); } catch (FileSizeLimitExceededException ex) { log.warn("Upload exceeded upload.max"); JSPManager.showFileSizeLimitExceededError(request, response, ex.getMessage(), ex.getActualSize(), ex.getPermittedSize()); } } /** * Process input from default item page * * @param context * DSpace context * @param request * HTTP request * @param response * HTTP response * @param collection * Collection we're editing */ private void processDefaultItem(Context context, HttpServletRequest request, HttpServletResponse response, Collection collection) throws SQLException, ServletException, IOException, AuthorizeException { Item item = collection.getTemplateItem(); for (int i = 0; i < 10; i++) { int dcTypeID = UIUtil.getIntParameter(request, "dctype_" + i); String value = request.getParameter("value_" + i); String lang = request.getParameter("lang_" + i); if ((dcTypeID != -1) && (value != null) && !value.equals("")) { MetadataField field = MetadataField.find(context,dcTypeID); MetadataSchema schema = MetadataSchema.find(context,field.getSchemaID()); item.addMetadata(schema.getName(),field.getElement(), field.getQualifier(), lang, value); } } item.update(); // Now work out what next page is showNextPage(context, request, response, collection, DEFAULT_ITEM); context.complete(); } /** * Work out which page to show next, and show it * * @param context * @param request * @param response * @param collection * @param stage * the stage the user just finished, or if PERMISSIONS, the * particular permissions page * @throws SQLException * @throws ServletException * @throws IOException * @throws AuthorizeException */ private void showNextPage(Context context, HttpServletRequest request, HttpServletResponse response, Collection collection, int stage) throws SQLException, ServletException, IOException, AuthorizeException { // Put collection in request attributes, as most JSPs will need it request.setAttribute("collection", collection); // FIXME: Not a nice hack -- do we show the MIT users checkbox? if (Group.findByName(context, "MIT Users") != null) { request.setAttribute("mitgroup", Boolean.TRUE); } log.debug(LogManager.getHeader(context, "nextpage", "stage=" + stage)); switch (stage) { case BASIC_INFO: // Next page is 'permission to read' page iff ITEM_DEFAULT_READ // for anonymous group is NOT there List<ResourcePolicy> anonReadPols = AuthorizeManager.getPoliciesActionFilter( context, collection, Constants.DEFAULT_ITEM_READ); // At this stage, if there's any ITEM_DEFAULT_READ, it can only // be an anonymous one. if (anonReadPols.size() == 0) { request.setAttribute("permission", Integer.valueOf(PERM_READ)); JSPManager.showJSP(request, response, "/dspace-admin/wizard-permissions.jsp"); break; } case PERM_READ: // Next page is 'permission to submit' iff there's a submit group // defined if (collection.getSubmitters() != null) { request.setAttribute("permission", Integer.valueOf(PERM_SUBMIT)); JSPManager.showJSP(request, response, "/dspace-admin/wizard-permissions.jsp"); break; } case PERM_SUBMIT: // Next page is 'workflow step 1' iff there's a wf step 1 group // defined if (collection.getWorkflowGroup(1) != null) { request.setAttribute("permission", Integer.valueOf(PERM_WF1)); JSPManager.showJSP(request, response, "/dspace-admin/wizard-permissions.jsp"); break; } case PERM_WF1: // Next page is 'workflow step 2' iff there's a wf step 2 group // defined if (collection.getWorkflowGroup(2) != null) { request.setAttribute("permission", Integer.valueOf(PERM_WF2)); JSPManager.showJSP(request, response, "/dspace-admin/wizard-permissions.jsp"); break; } case PERM_WF2: // Next page is 'workflow step 3' iff there's a wf step 2 group // defined if (collection.getWorkflowGroup(3) != null) { request.setAttribute("permission", Integer.valueOf(PERM_WF3)); JSPManager.showJSP(request, response, "/dspace-admin/wizard-permissions.jsp"); break; } case PERM_WF3: // Next page is 'collection administrator' iff there's a collection // administrator group if (collection.getAdministrators() != null) { request.setAttribute("permission", Integer.valueOf(PERM_ADMIN)); JSPManager.showJSP(request, response, "/dspace-admin/wizard-permissions.jsp"); break; } case PERM_ADMIN: // Next page is 'default item' iff there's a default item if (collection.getTemplateItem() != null) { MetadataField[] types = MetadataField.findAll(context); request.setAttribute("dctypes", types); JSPManager.showJSP(request, response, "/dspace-admin/wizard-default-item.jsp"); break; } case DEFAULT_ITEM: // Next page is 'summary page (the last page) // sort of a hack to pass the community ID to the edit collection // page, // which needs it in other contexts if (collection != null) { Community[] communities = collection.getCommunities(); request.setAttribute("community", communities[0]); EditCommunitiesServlet.storeAuthorizeAttributeCollectionEdit(context, request, collection); } JSPManager.showJSP(request, response, "/tools/edit-collection.jsp"); break; } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet.admin; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException; import org.apache.log4j.Logger; import org.dspace.app.util.AuthorizeUtil; import org.dspace.app.webui.servlet.DSpaceServlet; import org.dspace.app.webui.util.FileUploadRequest; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.content.Bitstream; import org.dspace.content.BitstreamFormat; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DSpaceObject; import org.dspace.content.FormatIdentifier; import org.dspace.content.Item; import org.dspace.harvest.HarvestedCollection; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.eperson.Group; /** * Servlet for editing communities and collections, including deletion, * creation, and metadata editing * * @author Robert Tansley * @version $Revision: 6158 $ */ public class EditCommunitiesServlet extends DSpaceServlet { /** User wants to edit a community */ public static final int START_EDIT_COMMUNITY = 1; /** User wants to delete a community */ public static final int START_DELETE_COMMUNITY = 2; /** User wants to create a community */ public static final int START_CREATE_COMMUNITY = 3; /** User wants to edit a collection */ public static final int START_EDIT_COLLECTION = 4; /** User wants to delete a collection */ public static final int START_DELETE_COLLECTION = 5; /** User wants to create a collection */ public static final int START_CREATE_COLLECTION = 6; /** User commited community edit or creation */ public static final int CONFIRM_EDIT_COMMUNITY = 7; /** User confirmed community deletion */ public static final int CONFIRM_DELETE_COMMUNITY = 8; /** User commited collection edit or creation */ public static final int CONFIRM_EDIT_COLLECTION = 9; /** User wants to delete a collection */ public static final int CONFIRM_DELETE_COLLECTION = 10; /** Logger */ private static Logger log = Logger.getLogger(EditCommunitiesServlet.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // GET just displays the list of communities and collections showControls(context, request, response); } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // First, see if we have a multipart request (uploading a logo) String contentType = request.getContentType(); if ((contentType != null) && (contentType.indexOf("multipart/form-data") != -1)) { // This is a multipart request, so it's a file upload processUploadLogo(context, request, response); return; } /* * Respond to submitted forms. Each form includes an "action" parameter * indicating what needs to be done (from the constants above.) */ int action = UIUtil.getIntParameter(request, "action"); /* * Most of the forms supply one or more of these values. Since we just * get null if we try and find something with ID -1, we'll just try and * find both here to save hassle later on */ Community community = Community.find(context, UIUtil.getIntParameter( request, "community_id")); Community parentCommunity = Community.find(context, UIUtil .getIntParameter(request, "parent_community_id")); Collection collection = Collection.find(context, UIUtil .getIntParameter(request, "collection_id")); // Just about every JSP will need the values we received request.setAttribute("community", community); request.setAttribute("parent", parentCommunity); request.setAttribute("collection", collection); /* * First we check for a "cancel" button - if it's been pressed, we * simply return to the main control page */ if (request.getParameter("submit_cancel") != null) { showControls(context, request, response); return; } // Now proceed according to "action" parameter switch (action) { case START_EDIT_COMMUNITY: storeAuthorizeAttributeCommunityEdit(context, request, community); // Display the relevant "edit community" page JSPManager.showJSP(request, response, "/tools/edit-community.jsp"); break; case START_DELETE_COMMUNITY: // Show "confirm delete" page JSPManager.showJSP(request, response, "/tools/confirm-delete-community.jsp"); break; case START_CREATE_COMMUNITY: // no authorize attribute will be given to the jsp so a "clean" creation form // will be always supplied, advanced setting on policies and admin group creation // will be possible after to have completed the community creation // Display edit community page with empty fields + create button JSPManager.showJSP(request, response, "/tools/edit-community.jsp"); break; case START_EDIT_COLLECTION: HarvestedCollection hc = HarvestedCollection.find(context, UIUtil. getIntParameter(request, "collection_id")); request.setAttribute("harvestInstance", hc); storeAuthorizeAttributeCollectionEdit(context, request, collection); // Display the relevant "edit collection" page JSPManager.showJSP(request, response, "/tools/edit-collection.jsp"); break; case START_DELETE_COLLECTION: // Show "confirm delete" page JSPManager.showJSP(request, response, "/tools/confirm-delete-collection.jsp"); break; case START_CREATE_COLLECTION: // Forward to collection creation wizard response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/tools/collection-wizard?community_id=" + community.getID())); break; case CONFIRM_EDIT_COMMUNITY: // Edit or creation of a community confirmed processConfirmEditCommunity(context, request, response, community); break; case CONFIRM_DELETE_COMMUNITY: // remember the parent community, if any Community parent = community.getParentCommunity(); // Delete the community community.delete(); // if community was top-level, redirect to community-list page if (parent == null) { response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/community-list")); } else // redirect to parent community page { response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/handle/" + parent.getHandle())); } // Show main control page //showControls(context, request, response); // Commit changes to DB context.complete(); break; case CONFIRM_EDIT_COLLECTION: // Edit or creation of a collection confirmed processConfirmEditCollection(context, request, response, community, collection); break; case CONFIRM_DELETE_COLLECTION: // Delete the collection community.removeCollection(collection); // remove the collection object from the request, so that the user // will be redirected on the community home page request.removeAttribute("collection"); // Show main control page showControls(context, request, response); // Commit changes to DB context.complete(); break; default: // Erm... weird action value received. log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); } } /** * Store in the request attribute to teach to the jsp which button are * needed/allowed for the community edit form * * @param context * @param request * @param community * @throws SQLException */ private void storeAuthorizeAttributeCommunityEdit(Context context, HttpServletRequest request, Community community) throws SQLException { try { AuthorizeUtil.authorizeManageAdminGroup(context, community); request.setAttribute("admin_create_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("admin_create_button", Boolean.FALSE); } try { AuthorizeUtil.authorizeRemoveAdminGroup(context, community); request.setAttribute("admin_remove_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("admin_remove_button", Boolean.FALSE); } if (AuthorizeManager.authorizeActionBoolean(context, community, Constants.DELETE)) { request.setAttribute("delete_button", Boolean.TRUE); } else { request.setAttribute("delete_button", Boolean.FALSE); } try { AuthorizeUtil.authorizeManageCommunityPolicy(context, community); request.setAttribute("policy_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("policy_button", Boolean.FALSE); } } /** * Store in the request attribute to teach to the jsp which button are * needed/allowed for the collection edit form * * @param context * @param request * @param community * @throws SQLException */ static void storeAuthorizeAttributeCollectionEdit(Context context, HttpServletRequest request, Collection collection) throws SQLException { if (AuthorizeManager.isAdmin(context, collection)) { request.setAttribute("admin_collection", Boolean.TRUE); } else { request.setAttribute("admin_collection", Boolean.FALSE); } try { AuthorizeUtil.authorizeManageAdminGroup(context, collection); request.setAttribute("admin_create_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("admin_create_button", Boolean.FALSE); } try { AuthorizeUtil.authorizeRemoveAdminGroup(context, collection); request.setAttribute("admin_remove_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("admin_remove_button", Boolean.FALSE); } try { AuthorizeUtil.authorizeManageSubmittersGroup(context, collection); request.setAttribute("submitters_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("submitters_button", Boolean.FALSE); } try { AuthorizeUtil.authorizeManageWorkflowsGroup(context, collection); request.setAttribute("workflows_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("workflows_button", Boolean.FALSE); } try { AuthorizeUtil.authorizeManageTemplateItem(context, collection); request.setAttribute("template_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("template_button", Boolean.FALSE); } if (AuthorizeManager.authorizeActionBoolean(context, collection.getParentObject(), Constants.REMOVE)) { request.setAttribute("delete_button", Boolean.TRUE); } else { request.setAttribute("delete_button", Boolean.FALSE); } try { AuthorizeUtil.authorizeManageCollectionPolicy(context, collection); request.setAttribute("policy_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("policy_button", Boolean.FALSE); } } /** * Show community home page with admin controls * * @param context * Current DSpace context * @param request * Current HTTP request * @param response * Current HTTP response */ private void showControls(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // new approach - eliminate the 'list-communities' page in favor of the // community home page, enhanced with admin controls. If no community, // or no parent community, just fall back to the community-list page Community community = (Community) request.getAttribute("community"); Collection collection = (Collection) request.getAttribute("collection"); if (collection != null) { response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/handle/" + collection.getHandle())); } else if (community != null) { response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/handle/" + community.getHandle())); } else { // see if a parent community was specified Community parent = (Community) request.getAttribute("parent"); if (parent != null) { response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/handle/" + parent.getHandle())); } else { // fall back on community-list page response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/community-list")); } } } /** * Create/update community metadata from a posted form * * @param context * DSpace context * @param request * the HTTP request containing posted info * @param response * the HTTP response * @param community * the community to update (or null for creation) */ private void processConfirmEditCommunity(Context context, HttpServletRequest request, HttpServletResponse response, Community community) throws ServletException, IOException, SQLException, AuthorizeException { if (request.getParameter("create").equals("true")) { // if there is a parent community id specified, create community // as its child; otherwise, create it as a top-level community int parentCommunityID = UIUtil.getIntParameter(request, "parent_community_id"); if (parentCommunityID != -1) { Community parent = Community.find(context, parentCommunityID); if (parent != null) { community = parent.createSubcommunity(); } } else { community = Community.create(null, context); } // Set attribute request.setAttribute("community", community); } storeAuthorizeAttributeCommunityEdit(context, request, community); community.setMetadata("name", request.getParameter("name")); community.setMetadata("short_description", request .getParameter("short_description")); String intro = request.getParameter("introductory_text"); if (intro.equals("")) { intro = null; } String copy = request.getParameter("copyright_text"); if (copy.equals("")) { copy = null; } String side = request.getParameter("side_bar_text"); if (side.equals("")) { side = null; } community.setMetadata("introductory_text", intro); community.setMetadata("copyright_text", copy); community.setMetadata("side_bar_text", side); community.update(); // Which button was pressed? String button = UIUtil.getSubmitButton(request, "submit"); if (button.equals("submit_set_logo")) { // Change the logo - delete any that might be there first community.setLogo(null); community.update(); // Display "upload logo" page. Necessary attributes already set by // doDSPost() JSPManager.showJSP(request, response, "/dspace-admin/upload-logo.jsp"); } else if (button.equals("submit_delete_logo")) { // Simply delete logo community.setLogo(null); community.update(); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/tools/edit-community.jsp"); } else if (button.equals("submit_authorization_edit")) { // Forward to policy edit page response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/tools/authorize?community_id=" + community.getID() + "&submit_community_select=1")); } else if (button.equals("submit_admins_create")) { // Create new group Group newGroup = community.createAdministrators(); community.update(); // Forward to group edit page response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/tools/group-edit?group_id=" + newGroup.getID())); } else if (button.equals("submit_admins_remove")) { Group g = community.getAdministrators(); community.removeAdministrators(); community.update(); g.delete(); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/tools/edit-community.jsp"); } else if (button.equals("submit_admins_edit")) { // Edit 'community administrators' group Group g = community.getAdministrators(); response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/tools/group-edit?group_id=" + g.getID())); } else { // Button at bottom clicked - show main control page showControls(context, request, response); } // Commit changes to DB context.complete(); } /** * Create/update collection metadata from a posted form * * @param context * DSpace context * @param request * the HTTP request containing posted info * @param response * the HTTP response * @param community * the community the collection is in * @param collection * the collection to update (or null for creation) */ private void processConfirmEditCollection(Context context, HttpServletRequest request, HttpServletResponse response, Community community, Collection collection) throws ServletException, IOException, SQLException, AuthorizeException { if (request.getParameter("create").equals("true")) { // We need to create a new community collection = community.createCollection(); request.setAttribute("collection", collection); } storeAuthorizeAttributeCollectionEdit(context, request, collection); // Update the basic metadata collection.setMetadata("name", request.getParameter("name")); collection.setMetadata("short_description", request .getParameter("short_description")); String intro = request.getParameter("introductory_text"); if (intro.equals("")) { intro = null; } String copy = request.getParameter("copyright_text"); if (copy.equals("")) { copy = null; } String side = request.getParameter("side_bar_text"); if (side.equals("")) { side = null; } String license = request.getParameter("license"); if (license.equals("")) { license = null; } String provenance = request.getParameter("provenance_description"); if (provenance.equals("")) { provenance = null; } collection.setMetadata("introductory_text", intro); collection.setMetadata("copyright_text", copy); collection.setMetadata("side_bar_text", side); collection.setMetadata("license", license); collection.setMetadata("provenance_description", provenance); // Set the harvesting settings HarvestedCollection hc = HarvestedCollection.find(context, collection.getID()); String contentSource = request.getParameter("source"); // First, if this is not a harvested collection (anymore), set the harvest type to 0; wipe harvest settings if (contentSource.equals("source_normal")) { if (hc != null) { hc.delete(); } } else { // create a new harvest instance if all the settings check out if (hc == null) { hc = HarvestedCollection.create(context, collection.getID()); } String oaiProvider = request.getParameter("oai_provider"); String oaiSetId = request.getParameter("oai_setid"); String metadataKey = request.getParameter("metadata_format"); String harvestType = request.getParameter("harvest_level"); hc.setHarvestParams(Integer.parseInt(harvestType), oaiProvider, oaiSetId, metadataKey); hc.setHarvestStatus(HarvestedCollection.STATUS_READY); hc.update(); } // Which button was pressed? String button = UIUtil.getSubmitButton(request, "submit"); if (button.equals("submit_set_logo")) { // Change the logo - delete any that might be there first collection.setLogo(null); // Display "upload logo" page. Necessary attributes already set by // doDSPost() JSPManager.showJSP(request, response, "/dspace-admin/upload-logo.jsp"); } else if (button.equals("submit_delete_logo")) { // Simply delete logo collection.setLogo(null); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/tools/edit-collection.jsp"); } else if (button.startsWith("submit_wf_create_")) { int step = Integer.parseInt(button.substring(17)); // Create new group Group newGroup = collection.createWorkflowGroup(step); collection.update(); // Forward to group edit page response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/tools/group-edit?group_id=" + newGroup.getID())); } else if (button.equals("submit_admins_create")) { // Create new group Group newGroup = collection.createAdministrators(); collection.update(); // Forward to group edit page response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/tools/group-edit?group_id=" + newGroup.getID())); } else if (button.equals("submit_admins_delete")) { // Remove the administrators group. Group g = collection.getAdministrators(); collection.removeAdministrators(); collection.update(); g.delete(); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/tools/edit-collection.jsp"); } else if (button.equals("submit_submitters_create")) { // Create new group Group newGroup = collection.createSubmitters(); collection.update(); // Forward to group edit page response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/tools/group-edit?group_id=" + newGroup.getID())); } else if (button.equals("submit_submitters_delete")) { // Remove the administrators group. Group g = collection.getSubmitters(); collection.removeSubmitters(); collection.update(); g.delete(); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/tools/edit-collection.jsp"); } else if (button.equals("submit_authorization_edit")) { // Forward to policy edit page response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/tools/authorize?collection_id=" + collection.getID() + "&submit_collection_select=1")); } else if (button.startsWith("submit_wf_edit_")) { int step = Integer.parseInt(button.substring(15)); // Edit workflow group Group g = collection.getWorkflowGroup(step); response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/tools/group-edit?group_id=" + g.getID())); } else if (button.equals("submit_submitters_edit")) { // Edit submitters group Group g = collection.getSubmitters(); response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/tools/group-edit?group_id=" + g.getID())); } else if (button.equals("submit_admins_edit")) { // Edit 'collection administrators' group Group g = collection.getAdministrators(); response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/tools/group-edit?group_id=" + g.getID())); } else if (button.startsWith("submit_wf_delete_")) { // Delete workflow group int step = Integer.parseInt(button.substring(17)); Group g = collection.getWorkflowGroup(step); collection.setWorkflowGroup(step, null); // Have to update to avoid ref. integrity error collection.update(); g.delete(); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/tools/edit-collection.jsp"); } else if (button.equals("submit_create_template")) { // Create a template item collection.createTemplateItem(); // Forward to edit page for new template item Item i = collection.getTemplateItem(); // save the changes collection.update(); context.complete(); response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/tools/edit-item?item_id=" + i.getID())); return; } else if (button.equals("submit_edit_template")) { // Forward to edit page for template item Item i = collection.getTemplateItem(); response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/tools/edit-item?item_id=" + i.getID())); } else if (button.equals("submit_delete_template")) { collection.removeTemplateItem(); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/tools/edit-collection.jsp"); } else { // Plain old "create/update" button pressed - go back to main page showControls(context, request, response); } // Commit changes to DB collection.update(); context.complete(); } /** * Process the input from the upload logo page * * @param context * current DSpace context * @param request * current servlet request object * @param response * current servlet response object */ private void processUploadLogo(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { try { // Wrap multipart request to get the submission info FileUploadRequest wrapper = new FileUploadRequest(request); Community community = Community.find(context, UIUtil.getIntParameter(wrapper, "community_id")); Collection collection = Collection.find(context, UIUtil.getIntParameter(wrapper, "collection_id")); File temp = wrapper.getFile("file"); // Read the temp file as logo InputStream is = new BufferedInputStream(new FileInputStream(temp)); Bitstream logoBS; if (collection == null) { logoBS = community.setLogo(is); } else { logoBS = collection.setLogo(is); } // Strip all but the last filename. It would be nice // to know which OS the file came from. String noPath = wrapper.getFilesystemName("file"); while (noPath.indexOf('/') > -1) { noPath = noPath.substring(noPath.indexOf('/') + 1); } while (noPath.indexOf('\\') > -1) { noPath = noPath.substring(noPath.indexOf('\\') + 1); } logoBS.setName(noPath); logoBS.setSource(wrapper.getFilesystemName("file")); // Identify the format BitstreamFormat bf = FormatIdentifier.guessFormat(context, logoBS); logoBS.setFormat(bf); AuthorizeManager.addPolicy(context, logoBS, Constants.WRITE, context.getCurrentUser()); logoBS.update(); String jsp; DSpaceObject dso; if (collection == null) { community.update(); // Show community edit page request.setAttribute("community", community); storeAuthorizeAttributeCommunityEdit(context, request, community); dso = community; jsp = "/tools/edit-community.jsp"; } else { collection.update(); // Show collection edit page request.setAttribute("collection", collection); request.setAttribute("community", community); storeAuthorizeAttributeCollectionEdit(context, request, collection); dso = collection; jsp = "/tools/edit-collection.jsp"; } if (AuthorizeManager.isAdmin(context, dso)) { // set a variable to show all buttons request.setAttribute("admin_button", Boolean.TRUE); } JSPManager.showJSP(request, response, jsp); // Remove temp file if (!temp.delete()) { log.error("Unable to delete temporary file"); } // Update DB context.complete(); } catch (FileSizeLimitExceededException ex) { log.warn("Upload exceeded upload.max"); JSPManager.showFileSizeLimitExceededError(request, response, ex.getMessage(), ex.getActualSize(), ex.getPermittedSize()); } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet.admin; import java.io.IOException; import java.sql.SQLException; import java.util.LinkedList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dspace.app.webui.servlet.DSpaceServlet; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.content.BitstreamFormat; import org.dspace.core.Context; /** * Servlet for editing the bitstream format registry * * @author Robert Tansley * @version $Revision: 5845 $ */ public class BitstreamFormatRegistry extends DSpaceServlet { /** User wants to edit a format */ public static final int START_EDIT = 1; /** User wants to delete a format */ public static final int START_DELETE = 2; /** User confirms edit of a format */ public static final int CONFIRM_EDIT = 3; /** User confirms delete of a format */ public static final int CONFIRM_DELETE = 4; /** User wants to create a new format */ public static final int CREATE = 4; protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // GET just displays the list of formats showFormats(context, request, response); } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String button = UIUtil.getSubmitButton(request, "submit"); if (button.equals("submit_update")) { // Update the metadata for a bitstream format BitstreamFormat bf = BitstreamFormat.find(context, UIUtil .getIntParameter(request, "format_id")); bf.setMIMEType(request.getParameter("mimetype")); bf.setShortDescription(request.getParameter("short_description")); bf.setDescription(request.getParameter("description")); bf .setSupportLevel(UIUtil.getIntParameter(request, "support_level")); bf.setInternal((request.getParameter("internal") != null) && request.getParameter("internal").equals("true")); // Separate comma-separated extensions List<String> extensions = new LinkedList<String>(); String extParam = request.getParameter("extensions"); while (extParam.length() > 0) { int c = extParam.indexOf(','); if (c > 0) { extensions.add(extParam.substring(0, c).trim()); extParam = extParam.substring(c + 1).trim(); } else { if (extParam.trim().length() > 0) { extensions.add(extParam.trim()); extParam = ""; } } } // Set extensions in the format - convert to array String[] extArray = (String[]) extensions .toArray(new String[extensions.size()]); bf.setExtensions(extArray); bf.update(); showFormats(context, request, response); context.complete(); } else if (button.equals("submit_add")) { // Add a new bitstream - simply add to the list, and let the user // edit with the main form BitstreamFormat bf = BitstreamFormat.create(context); // We set the "internal" flag to true, so that the empty bitstream // format doesn't show up in the submission UI yet bf.setInternal(true); bf.update(); showFormats(context, request, response); context.complete(); } else if (button.equals("submit_delete")) { // Start delete process - go through verification step BitstreamFormat bf = BitstreamFormat.find(context, UIUtil .getIntParameter(request, "format_id")); request.setAttribute("format", bf); JSPManager.showJSP(request, response, "/dspace-admin/confirm-delete-format.jsp"); } else if (button.equals("submit_confirm_delete")) { // User confirms deletion of format BitstreamFormat bf = BitstreamFormat.find(context, UIUtil .getIntParameter(request, "format_id")); bf.delete(); showFormats(context, request, response); context.complete(); } else { // Cancel etc. pressed - show list again showFormats(context, request, response); } } /** * Show list of bitstream formats * * @param context * Current DSpace context * @param request * Current HTTP request * @param response * Current HTTP response */ private void showFormats(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { BitstreamFormat[] formats = BitstreamFormat.findAll(context); request.setAttribute("formats", formats); JSPManager.showJSP(request, response, "/dspace-admin/list-formats.jsp"); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet.admin; import java.io.IOException; import java.sql.SQLException; import java.util.Locale; import java.util.ResourceBundle; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.servlet.DSpaceServlet; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.content.MetadataSchema; import org.dspace.content.NonUniqueMetadataException; import org.dspace.core.Context; /** * Servlet for editing the Dublin Core schema registry. * * @author Martin Hald * @version $Revision: 5845 $ */ public class MetadataSchemaRegistryServlet extends DSpaceServlet { /** Logger */ private static Logger log = Logger.getLogger(MetadataSchemaRegistryServlet.class); private String clazz = "org.dspace.app.webui.servlet.admin.MetadataSchemaRegistryServlet"; protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // GET just displays the list of type showSchemas(context, request, response); } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String button = UIUtil.getSubmitButton(request, "submit"); if (button.equals("submit_add")) { // We are either going to create a new dc schema or update and // existing one depending on if a schema_id was passed in String id = request.getParameter("dc_schema_id"); // The sanity check will update the request error string if needed if (!sanityCheck(request)) { showSchemas(context, request, response); context.abort(); return; } try { if (id.equals("")) { // Create a new metadata schema MetadataSchema schema = new MetadataSchema(); schema.setNamespace(request.getParameter("namespace")); schema.setName(request.getParameter("short_name")); schema.create(context); showSchemas(context, request, response); context.complete(); } else { // Update an existing schema MetadataSchema schema = MetadataSchema.find(context, UIUtil.getIntParameter(request, "dc_schema_id")); schema.setNamespace(request.getParameter("namespace")); schema.setName(request.getParameter("short_name")); schema.update(context); showSchemas(context, request, response); context.complete(); } } catch (NonUniqueMetadataException e) { request.setAttribute("error", "Please make the namespace and short name unique."); showSchemas(context, request, response); context.abort(); return; } } else if (button.equals("submit_delete")) { // Start delete process - go through verification step MetadataSchema schema = MetadataSchema.find(context, UIUtil .getIntParameter(request, "dc_schema_id")); request.setAttribute("schema", schema); JSPManager.showJSP(request, response, "/dspace-admin/confirm-delete-mdschema.jsp"); } else if (button.equals("submit_confirm_delete")) { // User confirms deletion of type MetadataSchema dc = MetadataSchema.find(context, UIUtil .getIntParameter(request, "dc_schema_id")); dc.delete(context); showSchemas(context, request, response); context.complete(); } else { // Cancel etc. pressed - show list again showSchemas(context, request, response); } } /** * Return false if the schema arguments fail to pass the constraints. If * there is an error the request error String will be updated with an error * description. * * @param request * @return true of false */ private boolean sanityCheck(HttpServletRequest request) { Locale locale = request.getLocale(); ResourceBundle labels = ResourceBundle.getBundle("Messages", locale); // TODO: add more namespace checks String namespace = request.getParameter("namespace"); if (namespace.length() == 0) { return error(request, labels.getString(clazz + ".emptynamespace")); } String name = request.getParameter("short_name"); if (name.length() == 0) { return error(request, labels.getString(clazz + ".emptyname")); } if (name.length() > 32) { return error(request, labels.getString(clazz + ".nametolong")); } for (int ii = 0; ii < name.length(); ii++) { if (name.charAt(ii) == ' ' || name.charAt(ii) == '_' || name.charAt(ii) == '.') { return error(request, labels.getString(clazz + ".illegalchar")); } } return true; } /** * Bind the error text to the request object. * * @param request * @param text * @return false */ private boolean error(HttpServletRequest request, String text) { request.setAttribute("error", text); return false; } /** * Show list of DC type * * @param context * Current DSpace context * @param request * Current HTTP request * @param response * Current HTTP response * @throws ServletException * @throws IOException * @throws SQLException * @throws IOException */ private void showSchemas(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, SQLException, IOException { MetadataSchema[] schemas = MetadataSchema.findAll(context); request.setAttribute("schemas", schemas); log.info("Showing Schemas"); JSPManager.showJSP(request, response, "/dspace-admin/list-metadata-schemas.jsp"); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet.admin; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dspace.app.webui.servlet.DSpaceServlet; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.core.Context; import org.dspace.eperson.EPerson; /** * Servlet browsing through e-people and selecting them * * @author Robert Tansley * @version $Revision: 5845 $ */ public class EPersonListServlet extends DSpaceServlet { protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { doDSGet(context, request, response); } protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Are we for selecting a single or multiple epeople? boolean multiple = UIUtil.getBoolParameter(request, "multiple"); // What are we sorting by. Lastname is default int sortBy = EPerson.LASTNAME; String sbParam = request.getParameter("sortby"); if ((sbParam != null) && sbParam.equals("lastname")) { sortBy = EPerson.LASTNAME; } else if ((sbParam != null) && sbParam.equals("email")) { sortBy = EPerson.EMAIL; } else if ((sbParam != null) && sbParam.equals("id")) { sortBy = EPerson.ID; } else if ((sbParam != null) && sbParam.equals("language")) { sortBy = EPerson.LANGUAGE; } // What's the index of the first eperson to show? Default is 0 int first = UIUtil.getIntParameter(request, "first"); int offset = UIUtil.getIntParameter(request, "offset"); if (first == -1) { first = 0; } if (offset == -1) { offset = 0; } EPerson[] epeople; String search = request.getParameter("search"); if (search != null && !search.equals("")) { epeople = EPerson.search(context, search); request.setAttribute("offset", Integer.valueOf(offset)); } else { // Retrieve the e-people in the specified order epeople = EPerson.findAll(context, sortBy); request.setAttribute("offset", Integer.valueOf(0)); } // Set attributes for JSP request.setAttribute("sortby", Integer.valueOf(sortBy)); request.setAttribute("first", Integer.valueOf(first)); request.setAttribute("epeople", epeople); request.setAttribute("search", search); if (multiple) { request.setAttribute("multiple", Boolean.TRUE); } JSPManager.showJSP(request, response, "/tools/eperson-list.jsp"); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet.admin; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.dspace.app.webui.servlet.DSpaceServlet; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.eperson.EPerson; import org.dspace.eperson.Group; /** * Servlet for editing groups * * @author dstuve * @version $Revision: 5845 $ */ public class GroupEditServlet extends DSpaceServlet { protected void doDSGet(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { doDSPost(c, request, response); } protected void doDSPost(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Find out if there's a group parameter int groupID = UIUtil.getIntParameter(request, "group_id"); Group group = null; if (groupID >= 0) { group = Group.find(c, groupID); } // group is set if (group != null) { // is this user authorized to edit this group? AuthorizeManager.authorizeAction(c, group, Constants.ADD); boolean submit_edit = (request.getParameter("submit_edit") != null); boolean submit_group_update = (request.getParameter("submit_group_update") != null); boolean submit_group_delete = (request.getParameter("submit_group_delete") != null); boolean submit_confirm_delete = (request.getParameter("submit_confirm_delete") != null); boolean submit_cancel_delete = (request.getParameter("submit_cancel_delete") != null); // just chosen a group to edit - get group and pass it to // group-edit.jsp if (submit_edit && !submit_group_update && !submit_group_delete) { request.setAttribute("group", group); request.setAttribute("members", group.getMembers()); request.setAttribute("membergroups", group.getMemberGroups()); JSPManager.showJSP(request, response, "/tools/group-edit.jsp"); } // update the members of the group else if (submit_group_update) { // first off, did we change the group name? String newName = request.getParameter("group_name"); if (!newName.equals(group.getName())) { group.setName(newName); group.update(); } int[] eperson_ids = UIUtil.getIntParameters(request, "eperson_id"); int[] group_ids = UIUtil.getIntParameters(request, "group_ids"); // now get members, and add new ones and remove missing ones EPerson[] members = group.getMembers(); Group[] membergroups = group.getMemberGroups(); if (eperson_ids != null) { // some epeople were listed, now make group's epeople match // given epeople Set memberSet = new HashSet(); Set epersonIDSet = new HashSet(); // add all members to a set for (int x = 0; x < members.length; x++) { Integer epersonID = Integer.valueOf(members[x].getID()); memberSet.add(epersonID); } // now all eperson_ids are put in a set for (int x = 0; x < eperson_ids.length; x++) { epersonIDSet.add(Integer.valueOf(eperson_ids[x])); } // process eperson_ids, adding those to group not already // members Iterator i = epersonIDSet.iterator(); while (i.hasNext()) { Integer currentID = (Integer) i.next(); if (!memberSet.contains(currentID)) { group.addMember(EPerson.find(c, currentID .intValue())); } } // process members, removing any that aren't in eperson_ids for (int x = 0; x < members.length; x++) { EPerson e = members[x]; if (!epersonIDSet.contains(Integer.valueOf(e.getID()))) { group.removeMember(e); } } } else { // no members found (ids == null), remove them all! for (int y = 0; y < members.length; y++) { group.removeMember(members[y]); } } if (group_ids != null) { // some groups were listed, now make group's member groups // match given group IDs Set memberSet = new HashSet(); Set groupIDSet = new HashSet(); // add all members to a set for (int x = 0; x < membergroups.length; x++) { Integer myID = Integer.valueOf(membergroups[x].getID()); memberSet.add(myID); } // now all eperson_ids are put in a set for (int x = 0; x < group_ids.length; x++) { groupIDSet.add(Integer.valueOf(group_ids[x])); } // process group_ids, adding those to group not already // members Iterator i = groupIDSet.iterator(); while (i.hasNext()) { Integer currentID = (Integer) i.next(); if (!memberSet.contains(currentID)) { group .addMember(Group.find(c, currentID .intValue())); } } // process members, removing any that aren't in eperson_ids for (int x = 0; x < membergroups.length; x++) { Group g = membergroups[x]; if (!groupIDSet.contains(Integer.valueOf(g.getID()))) { group.removeMember(g); } } } else { // no members found (ids == null), remove them all! for (int y = 0; y < membergroups.length; y++) { group.removeMember(membergroups[y]); } } group.update(); request.setAttribute("group", group); request.setAttribute("members", group.getMembers()); request.setAttribute("membergroups", group.getMemberGroups()); JSPManager.showJSP(request, response, "/tools/group-edit.jsp"); c.complete(); } else if (submit_group_delete) { // direct to a confirmation step request.setAttribute("group", group); JSPManager.showJSP(request, response, "/dspace-admin/group-confirm-delete.jsp"); } else if (submit_confirm_delete) { // phony authorize, only admins can do this AuthorizeManager.authorizeAction(c, group, Constants.WRITE); // delete group, return to group-list.jsp group.delete(); showMainPage(c, request, response); } else if (submit_cancel_delete) { // show group list showMainPage(c, request, response); } else { // unknown action, show edit page request.setAttribute("group", group); request.setAttribute("members", group.getMembers()); request.setAttribute("membergroups", group.getMemberGroups()); JSPManager.showJSP(request, response, "/tools/group-edit.jsp"); } } else // no group set { // want to add a group - create a blank one, and pass to // group_edit.jsp String button = UIUtil.getSubmitButton(request, "submit"); if (button.equals("submit_add")) { group = Group.create(c); group.setName("new group" + group.getID()); group.update(); request.setAttribute("group", group); request.setAttribute("members", group.getMembers()); request.setAttribute("membergroups", group.getMemberGroups()); JSPManager.showJSP(request, response, "/tools/group-edit.jsp"); c.complete(); } else { // show the main page (select groups) showMainPage(c, request, response); } } } private void showMainPage(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { Group[] groups = Group.findAll(c, Group.NAME); // if( groups == null ) { System.out.println("groups are null"); } // else System.out.println("# of groups: " + groups.length); request.setAttribute("groups", groups); JSPManager.showJSP(request, response, "/tools/group-list.jsp"); c.complete(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet.admin; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dspace.app.webui.servlet.DSpaceServlet; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.core.Context; import org.dspace.eperson.Group; /** * Servlet browsing through groups and selecting them * * * @version $Revision: 5845 $ */ public class GroupListServlet extends DSpaceServlet { protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Are we for selecting a single or multiple groups? boolean multiple = UIUtil.getBoolParameter(request, "multiple"); // What are we sorting by? Name is default int sortBy = Group.NAME; String sbParam = request.getParameter("sortby"); if (sbParam != null && sbParam.equals("id")) { sortBy = Group.ID; } // What's the index of the first group to show? Default is 0 int first = UIUtil.getIntParameter(request, "first"); if (first == -1) { first = 0; } // Retrieve the e-people in the specified order Group[] groups = Group.findAll(context, sortBy); // Set attributes for JSP request.setAttribute("sortby", Integer.valueOf(sortBy)); request.setAttribute("first", Integer.valueOf(first)); request.setAttribute("groups", groups); if (multiple) { request.setAttribute("multiple", Boolean.TRUE); } JSPManager.showJSP(request, response, "/tools/group-select-list.jsp"); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet.admin; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dspace.app.webui.servlet.DSpaceServlet; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.core.Context; import org.dspace.eperson.EPerson; import org.dspace.eperson.Group; import org.dspace.eperson.EPersonDeletionException; /** * Servlet for editing and creating e-people * * @author David Stuve * @version $Revision: 5845 $ */ public class EPersonAdminServlet extends DSpaceServlet { protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { showMain(context, request, response); } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String button = UIUtil.getSubmitButton(request, "submit"); if (button.equals("submit_add")) { // add an EPerson, then jump user to edit page EPerson e = EPerson.create(context); // create clever name and do update before continuing e.setEmail("newuser" + e.getID()); e.update(); request.setAttribute("eperson", e); JSPManager.showJSP(request, response, "/dspace-admin/eperson-edit.jsp"); context.complete(); } else if (button.equals("submit_edit")) { // edit an eperson EPerson e = EPerson.find(context, UIUtil.getIntParameter(request, "eperson_id")); // Check the EPerson exists if (e == null) { request.setAttribute("no_eperson_selected", Boolean.TRUE); showMain(context, request, response); } else { // what groups is this person a member of? Group[] groupMemberships = Group.allMemberGroups(context, e); request.setAttribute("eperson", e); request.setAttribute("group.memberships", groupMemberships); JSPManager.showJSP(request, response, "/dspace-admin/eperson-edit.jsp"); context.complete(); } } else if (button.equals("submit_save")) { // Update the metadata for an e-person EPerson e = EPerson.find(context, UIUtil.getIntParameter(request, "eperson_id")); // see if the user changed the email - if so, make sure // the new email is unique String oldEmail = e.getEmail(); String newEmail = request.getParameter("email").trim(); String netid = request.getParameter("netid"); if (!newEmail.equals(oldEmail)) { // change to email, now see if it's unique if (EPerson.findByEmail(context, newEmail) == null) { // it's unique - proceed! e.setEmail(newEmail); e .setFirstName(request.getParameter("firstname") .equals("") ? null : request .getParameter("firstname")); e .setLastName(request.getParameter("lastname") .equals("") ? null : request .getParameter("lastname")); if (netid != null) { e.setNetid(netid.equals("") ? null : netid.toLowerCase()); } else { e.setNetid(null); } // FIXME: More data-driven? e.setMetadata("phone", request.getParameter("phone") .equals("") ? null : request.getParameter("phone")); e.setMetadata("language", request.getParameter("language") .equals("") ? null : request.getParameter("language")); e.setCanLogIn((request.getParameter("can_log_in") != null) && request.getParameter("can_log_in") .equals("true")); e.setRequireCertificate((request .getParameter("require_certificate") != null) && request.getParameter("require_certificate") .equals("true")); e.update(); showMain(context, request, response); context.complete(); } else { // not unique - send error message & let try again request.setAttribute("eperson", e); request.setAttribute("email_exists", Boolean.TRUE); JSPManager.showJSP(request, response, "/dspace-admin/eperson-edit.jsp"); context.complete(); } } else { // no change to email if (netid != null) { e.setNetid(netid.equals("") ? null : netid.toLowerCase()); } else { e.setNetid(null); } e .setFirstName(request.getParameter("firstname").equals( "") ? null : request.getParameter("firstname")); e .setLastName(request.getParameter("lastname") .equals("") ? null : request .getParameter("lastname")); // FIXME: More data-driven? e.setMetadata("phone", request.getParameter("phone").equals("") ? null : request.getParameter("phone")); e.setMetadata("language", request.getParameter("language") .equals("") ? null : request.getParameter("language")); e.setCanLogIn((request.getParameter("can_log_in") != null) && request.getParameter("can_log_in").equals("true")); e.setRequireCertificate((request .getParameter("require_certificate") != null) && request.getParameter("require_certificate").equals( "true")); e.update(); showMain(context, request, response); context.complete(); } } else if (button.equals("submit_delete")) { // Start delete process - go through verification step EPerson e = EPerson.find(context, UIUtil.getIntParameter(request, "eperson_id")); // Check the EPerson exists if (e == null) { request.setAttribute("no_eperson_selected", Boolean.TRUE); showMain(context, request, response); } else { request.setAttribute("eperson", e); JSPManager.showJSP(request, response, "/dspace-admin/eperson-confirm-delete.jsp"); } } else if (button.equals("submit_confirm_delete")) { // User confirms deletion of type EPerson e = EPerson.find(context, UIUtil.getIntParameter(request, "eperson_id")); try { e.delete(); } catch (EPersonDeletionException ex) { request.setAttribute("eperson", e); request.setAttribute("tableList", ex.getTables()); JSPManager.showJSP(request, response, "/dspace-admin/eperson-deletion-error.jsp"); } showMain(context, request, response); context.complete(); } else { // Cancel etc. pressed - show list again showMain(context, request, response); } } private void showMain(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { JSPManager.showJSP(request, response, "/dspace-admin/eperson-main.jsp"); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet.admin; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dspace.app.webui.servlet.DSpaceServlet; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.core.Context; import org.dspace.workflow.WorkflowItem; import org.dspace.workflow.WorkflowManager; /** * Servlet for aborting workflows * * @author dstuve * @version $Revision: 5845 $ */ public class WorkflowAbortServlet extends DSpaceServlet { protected void doDSGet(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Get displays list of workflows showWorkflows(c, request, response); } protected void doDSPost(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String button = UIUtil.getSubmitButton(request, "submit"); if (button.equals("submit_abort")) { // bring up the confirm page WorkflowItem wi = WorkflowItem.find(c, UIUtil.getIntParameter( request, "workflow_id")); request.setAttribute("workflow", wi); JSPManager.showJSP(request, response, "/dspace-admin/workflow-abort-confirm.jsp"); } else if (button.equals("submit_abort_confirm")) { // do the actual abort WorkflowItem wi = WorkflowItem.find(c, UIUtil.getIntParameter( request, "workflow_id")); WorkflowManager.abort(c, wi, c.getCurrentUser()); // now show what's left showWorkflows(c, request, response); } else { // must have been cancel showWorkflows(c, request, response); } // now commit the changes c.complete(); } private void showWorkflows(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { WorkflowItem[] w = WorkflowItem.findAll(c); request.setAttribute("workflows", w); JSPManager .showJSP(request, response, "/dspace-admin/workflow-list.jsp"); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet.admin; import java.io.IOException; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dspace.app.util.AuthorizeUtil; import org.dspace.app.webui.servlet.DSpaceServlet; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.authorize.PolicySet; import org.dspace.authorize.ResourcePolicy; import org.dspace.content.Bitstream; import org.dspace.content.Bundle; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.eperson.EPerson; import org.dspace.eperson.Group; import org.dspace.handle.HandleManager; /** * Servlet for editing permissions * * @author dstuve * @version $Revision: 5845 $ */ public class AuthorizeAdminServlet extends DSpaceServlet { protected void doDSGet(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // handle gets and posts with the post method doDSPost(c, request, response); // show the main page (select communities, collections, items, etc) // showMainPage(c, request, response); } protected void doDSPost(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String button = UIUtil.getSubmitButton(request, "submit"); // check authorization!! the authorize servlet is available to all registred users // it is need because also item/collection/community admin could be // allowed to manage policies if (button.equals("submit_collection")) { // select a collection to work on Collection[] collections = Collection.findAll(c); request.setAttribute("collections", collections); JSPManager.showJSP(request, response, "/dspace-admin/collection-select.jsp"); } else if (button.equals("submit_community")) { // select a community to work on Community[] communities = Community.findAll(c); request.setAttribute("communities", communities); JSPManager.showJSP(request, response, "/dspace-admin/community-select.jsp"); } else if (button.equals("submit_advanced")) { // select a collections to work on Collection[] collections = Collection.findAll(c); Group[] groups = Group.findAll(c, Group.NAME); request.setAttribute("collections", collections); request.setAttribute("groups", groups); JSPManager.showJSP(request, response, "/dspace-admin/authorize-advanced.jsp"); } else if (button.equals("submit_item")) { // select an item to work on JSPManager.showJSP(request, response, "/dspace-admin/item-select.jsp"); } // ITEMS //////////////////////////////////////////////////// else if (button.equals("submit_item_select")) { Item item = null; int itemId = UIUtil.getIntParameter(request, "item_id"); String handle = request.getParameter("handle"); // if id is set, use it if (itemId > 0) { item = Item.find(c, itemId); } else if ((handle != null) && !handle.equals("")) { // otherwise, attempt to resolve handle DSpaceObject dso = HandleManager.resolveToObject(c, handle); // make sure it's an item if ((dso != null) && (dso.getType() == Constants.ITEM)) { item = (Item) dso; } } // no item set yet, failed ID & handle, ask user to try again if (item == null) { request.setAttribute("invalid.id", Boolean.TRUE); JSPManager.showJSP(request, response, "/dspace-admin/item-select.jsp"); } else { // show edit form! prepItemEditForm(c, request, item); JSPManager.showJSP(request, response, "/dspace-admin/authorize-item-edit.jsp"); } } else if (button.equals("submit_item_add_policy")) { // want to add a policy, create an empty one and invoke editor Item item = Item .find(c, UIUtil.getIntParameter(request, "item_id")); AuthorizeUtil.authorizeManageItemPolicy(c, item); ResourcePolicy policy = ResourcePolicy.create(c); policy.setResource(item); policy.update(); Group[] groups = Group.findAll(c, Group.NAME); EPerson[] epeople = EPerson.findAll(c, EPerson.EMAIL); // return to item permission page request.setAttribute("edit_title", "Item " + item.getID()); request.setAttribute("policy", policy); request.setAttribute("groups", groups); request.setAttribute("epeople", epeople); request.setAttribute("id_name", "item_id"); request.setAttribute("id", "" + item.getID()); request.setAttribute("newpolicy", "true"); JSPManager.showJSP(request, response, "/dspace-admin/authorize-policy-edit.jsp"); } else if (button.equals("submit_item_edit_policy")) { // edit an item's policy - set up and call policy editor Item item = Item .find(c, UIUtil.getIntParameter(request, "item_id")); AuthorizeUtil.authorizeManageItemPolicy(c, item); int policyId = UIUtil.getIntParameter(request, "policy_id"); ResourcePolicy policy = null; policy = ResourcePolicy.find(c, policyId); Group[] groups = Group.findAll(c, Group.NAME); EPerson[] epeople = EPerson.findAll(c, EPerson.EMAIL); // return to collection permission page request.setAttribute("edit_title", "Item " + item.getID()); request.setAttribute("policy", policy); request.setAttribute("groups", groups); request.setAttribute("epeople", epeople); request.setAttribute("id_name", "item_id"); request.setAttribute("id", "" + item.getID()); JSPManager.showJSP(request, response, "/dspace-admin/authorize-policy-edit.jsp"); } else if (button.equals("submit_bundle_add_policy")) { // want to add a policy, create an empty one and invoke editor Item item = Item .find(c, UIUtil.getIntParameter(request, "item_id")); Bundle bundle = Bundle.find(c, UIUtil.getIntParameter(request, "bundle_id")); AuthorizeUtil.authorizeManageBundlePolicy(c, bundle); ResourcePolicy policy = ResourcePolicy.create(c); policy.setResource(bundle); policy.update(); Group[] groups = Group.findAll(c, Group.NAME); EPerson[] epeople = EPerson.findAll(c, EPerson.EMAIL); // return to item permission page request.setAttribute("edit_title", "(Item, Bundle) = (" + item.getID() + "," + bundle.getID() + ")"); request.setAttribute("policy", policy); request.setAttribute("groups", groups); request.setAttribute("epeople", epeople); request.setAttribute("id_name", "item_id"); request.setAttribute("id", "" + item.getID()); request.setAttribute("newpolicy", "true"); JSPManager.showJSP(request, response, "/dspace-admin/authorize-policy-edit.jsp"); } else if (button.equals("submit_bitstream_add_policy")) { // want to add a policy, create an empty one and invoke editor Item item = Item .find(c, UIUtil.getIntParameter(request, "item_id")); Bitstream bitstream = Bitstream.find(c, UIUtil.getIntParameter( request, "bitstream_id")); AuthorizeUtil.authorizeManageBitstreamPolicy(c, bitstream); ResourcePolicy policy = ResourcePolicy.create(c); policy.setResource(bitstream); policy.update(); Group[] groups = Group.findAll(c, Group.NAME); EPerson[] epeople = EPerson.findAll(c, EPerson.EMAIL); // return to item permission page request.setAttribute("edit_title", "(Item,Bitstream) = (" + item.getID() + "," + bitstream.getID() + ")"); request.setAttribute("policy", policy); request.setAttribute("groups", groups); request.setAttribute("epeople", epeople); request.setAttribute("id_name", "item_id"); request.setAttribute("id", "" + item.getID()); request.setAttribute("newpolicy", "true"); JSPManager.showJSP(request, response, "/dspace-admin/authorize-policy-edit.jsp"); } else if (button.equals("submit_item_delete_policy")) { // delete a permission from an item Item item = Item .find(c, UIUtil.getIntParameter(request, "item_id")); AuthorizeUtil.authorizeManageItemPolicy(c, item); ResourcePolicy policy = ResourcePolicy.find(c, UIUtil .getIntParameter(request, "policy_id")); // do the remove policy.delete(); // show edit form! prepItemEditForm(c, request, item); JSPManager.showJSP(request, response, "/dspace-admin/authorize-item-edit.jsp"); } // COLLECTIONS //////////////////////////////////////////////////////// else if (button.equals("submit_collection_add_policy")) { // want to add a policy, create an empty one and invoke editor Collection collection = Collection.find(c, UIUtil.getIntParameter( request, "collection_id")); AuthorizeUtil.authorizeManageCollectionPolicy(c, collection); ResourcePolicy policy = ResourcePolicy.create(c); policy.setResource(collection); policy.update(); Group[] groups = Group.findAll(c, Group.NAME); EPerson[] epeople = EPerson.findAll(c, EPerson.EMAIL); // return to collection permission page request.setAttribute("edit_title", "Collection " + collection.getID()); request.setAttribute("policy", policy); request.setAttribute("groups", groups); request.setAttribute("epeople", epeople); request.setAttribute("id_name", "collection_id"); request.setAttribute("id", "" + collection.getID()); request.setAttribute("newpolicy", "true"); JSPManager.showJSP(request, response, "/dspace-admin/authorize-policy-edit.jsp"); } else if (button.equals("submit_community_select")) { // edit the collection's permissions Community target = Community.find(c, UIUtil.getIntParameter( request, "community_id")); List<ResourcePolicy> policies = AuthorizeManager.getPolicies(c, target); request.setAttribute("community", target); request.setAttribute("policies", policies); JSPManager.showJSP(request, response, "/dspace-admin/authorize-community-edit.jsp"); } else if (button.equals("submit_collection_delete_policy")) { // delete a permission from a collection Collection collection = Collection.find(c, UIUtil.getIntParameter( request, "collection_id")); AuthorizeUtil.authorizeManageCollectionPolicy(c, collection); ResourcePolicy policy = ResourcePolicy.find(c, UIUtil .getIntParameter(request, "policy_id")); // do the remove policy.delete(); // return to collection permission page request.setAttribute("collection", collection); List<ResourcePolicy> policies = AuthorizeManager.getPolicies(c, collection); request.setAttribute("policies", policies); JSPManager.showJSP(request, response, "/dspace-admin/authorize-collection-edit.jsp"); } else if (button.equals("submit_community_delete_policy")) { // delete a permission from a community Community community = Community.find(c, UIUtil.getIntParameter( request, "community_id")); AuthorizeUtil.authorizeManageCommunityPolicy(c, community); ResourcePolicy policy = ResourcePolicy.find(c, UIUtil .getIntParameter(request, "policy_id")); // do the remove policy.delete(); // return to collection permission page request.setAttribute("community", community); List<ResourcePolicy> policies = AuthorizeManager.getPolicies(c, community); request.setAttribute("policies", policies); JSPManager.showJSP(request, response, "/dspace-admin/authorize-community-edit.jsp"); } else if (button.equals("submit_collection_edit_policy")) { // edit a collection's policy - set up and call policy editor Collection collection = Collection.find(c, UIUtil.getIntParameter( request, "collection_id")); AuthorizeUtil.authorizeManageCollectionPolicy(c, collection); int policyId = UIUtil.getIntParameter(request, "policy_id"); ResourcePolicy policy = null; if (policyId == -1) { // create new policy policy = ResourcePolicy.create(c); policy.setResource(collection); policy.update(); } else { policy = ResourcePolicy.find(c, policyId); } Group[] groups = Group.findAll(c, Group.NAME); EPerson[] epeople = EPerson.findAll(c, EPerson.EMAIL); // return to collection permission page request.setAttribute("edit_title", "Collection " + collection.getID()); request.setAttribute("policy", policy); request.setAttribute("groups", groups); request.setAttribute("epeople", epeople); request.setAttribute("id_name", "collection_id"); request.setAttribute("id", "" + collection.getID()); JSPManager.showJSP(request, response, "/dspace-admin/authorize-policy-edit.jsp"); } else if (button.equals("submit_community_edit_policy")) { // edit a community's policy - set up and call policy editor Community community = Community.find(c, UIUtil.getIntParameter( request, "community_id")); AuthorizeUtil.authorizeManageCommunityPolicy(c, community); int policyId = UIUtil.getIntParameter(request, "policy_id"); ResourcePolicy policy = null; if (policyId == -1) { // create new policy policy = ResourcePolicy.create(c); policy.setResource(community); policy.update(); } else { policy = ResourcePolicy.find(c, policyId); } Group[] groups = Group.findAll(c, Group.NAME); EPerson[] epeople = EPerson.findAll(c, EPerson.EMAIL); // return to collection permission page request .setAttribute("edit_title", "Community " + community.getID()); request.setAttribute("policy", policy); request.setAttribute("groups", groups); request.setAttribute("epeople", epeople); request.setAttribute("id_name", "community_id"); request.setAttribute("id", "" + community.getID()); JSPManager.showJSP(request, response, "/dspace-admin/authorize-policy-edit.jsp"); } else if (button.equals("submit_collection_add_policy")) { // want to add a policy, create an empty one and invoke editor Collection collection = Collection.find(c, UIUtil.getIntParameter( request, "collection_id")); AuthorizeUtil.authorizeManageCollectionPolicy(c, collection); ResourcePolicy policy = ResourcePolicy.create(c); policy.setResource(collection); policy.update(); Group[] groups = Group.findAll(c, Group.NAME); EPerson[] epeople = EPerson.findAll(c, EPerson.EMAIL); // return to collection permission page request.setAttribute("edit_title", "Collection " + collection.getID()); request.setAttribute("policy", policy); request.setAttribute("groups", groups); request.setAttribute("epeople", epeople); request.setAttribute("id_name", "collection_id"); request.setAttribute("id", "" + collection.getID()); request.setAttribute("newpolicy", "true"); JSPManager.showJSP(request, response, "/dspace-admin/authorize-policy-edit.jsp"); } else if (button.equals("submit_community_add_policy")) { // want to add a policy, create an empty one and invoke editor Community community = Community.find(c, UIUtil.getIntParameter( request, "community_id")); AuthorizeUtil.authorizeManageCommunityPolicy(c, community); ResourcePolicy policy = ResourcePolicy.create(c); policy.setResource(community); policy.update(); Group[] groups = Group.findAll(c, Group.NAME); EPerson[] epeople = EPerson.findAll(c, EPerson.EMAIL); // return to collection permission page request .setAttribute("edit_title", "Community " + community.getID()); request.setAttribute("policy", policy); request.setAttribute("groups", groups); request.setAttribute("epeople", epeople); request.setAttribute("id_name", "community_id"); request.setAttribute("id", "" + community.getID()); request.setAttribute("newpolicy", "true"); JSPManager.showJSP(request, response, "/dspace-admin/authorize-policy-edit.jsp"); } else if (button.equals("submit_save_policy")) { int policyId = UIUtil.getIntParameter(request, "policy_id"); int actionId = UIUtil.getIntParameter(request, "action_id"); int groupId = UIUtil.getIntParameter(request, "group_id"); int collectionId = UIUtil .getIntParameter(request, "collection_id"); int communityId = UIUtil.getIntParameter(request, "community_id"); int itemId = UIUtil.getIntParameter(request, "item_id"); Item item = null; Collection collection = null; Community community = null; String displayPage = null; ResourcePolicy policy = ResourcePolicy.find(c, policyId); AuthorizeUtil.authorizeManagePolicy(c, policy); Group group = Group.find(c, groupId); if (collectionId != -1) { collection = Collection.find(c, collectionId); // modify the policy policy.setAction(actionId); policy.setGroup(group); policy.update(); // if it is a read, policy, modify the logo policy to match if (actionId == Constants.READ) { // first get a list of READ policies from collection List<ResourcePolicy> rps = AuthorizeManager.getPoliciesActionFilter(c, collection, Constants.READ); // remove all bitstream policies, then add READs Bitstream bs = collection.getLogo(); if (bs != null) { AuthorizeManager.removeAllPolicies(c, bs); AuthorizeManager.addPolicies(c, rps, bs); } } // set up page attributes request.setAttribute("collection", collection); request.setAttribute("policies", AuthorizeManager.getPolicies( c, collection)); displayPage = "/dspace-admin/authorize-collection-edit.jsp"; } else if (communityId != -1) { community = Community.find(c, communityId); // modify the policy policy.setAction(actionId); policy.setGroup(group); policy.update(); // if it is a read, policy, modify the logo policy to match if (actionId == Constants.READ) { // first get a list of READ policies from collection List<ResourcePolicy> rps = AuthorizeManager.getPoliciesActionFilter(c, community, Constants.READ); // remove all bitstream policies, then add READs Bitstream bs = community.getLogo(); if (bs != null) { AuthorizeManager.removeAllPolicies(c, bs); AuthorizeManager.addPolicies(c, rps, bs); } } // set up page attributes request.setAttribute("community", community); request.setAttribute("policies", AuthorizeManager.getPolicies( c, community)); displayPage = "/dspace-admin/authorize-community-edit.jsp"; } else if (itemId != -1) { item = Item.find(c, itemId); // modify the policy policy.setAction(actionId); policy.setGroup(group); policy.update(); // show edit form! prepItemEditForm(c, request, item); displayPage = "/dspace-admin/authorize-item-edit.jsp"; } // now return to previous state JSPManager.showJSP(request, response, displayPage); } else if (button.equals("submit_cancel_policy")) { // delete the policy that we created if it's a new one if ((request.getParameter("newpolicy") != null)) { int policyId = UIUtil.getIntParameter(request, "policy_id"); ResourcePolicy rp = ResourcePolicy.find(c, policyId); AuthorizeUtil.authorizeManagePolicy(c, rp); rp.delete(); } // return to the previous page int collectionId = UIUtil.getIntParameter(request, "collection_id"); int communityId = UIUtil.getIntParameter(request, "community_id"); int itemId = UIUtil.getIntParameter(request, "item_id"); String displayPage = null; if (collectionId != -1) { // set up for return to collection edit page Collection t = Collection.find(c, collectionId); request.setAttribute("collection", t); request.setAttribute("policies", AuthorizeManager.getPolicies( c, t)); displayPage = "/dspace-admin/authorize-collection-edit.jsp"; } else if (communityId != -1) { // set up for return to community edit page Community t = Community.find(c, communityId); request.setAttribute("community", t); request.setAttribute("policies", AuthorizeManager.getPolicies( c, t)); displayPage = "/dspace-admin/authorize-community-edit.jsp"; } else if (itemId != -1) { // set up for return to item edit page Item t = Item.find(c, itemId); // show edit form! prepItemEditForm(c, request, t); displayPage = "/dspace-admin/authorize-item-edit.jsp"; } JSPManager.showJSP(request, response, displayPage); } else if (button.equals("submit_advanced_clear")) { AuthorizeUtil.requireAdminRole(c); // remove all policies for a set of objects int collectionId = UIUtil.getIntParameter(request, "collection_id"); int resourceType = UIUtil.getIntParameter(request, "resource_type"); // if it's to bitstreams, do it to bundles too PolicySet.setPolicies(c, Constants.COLLECTION, collectionId, resourceType, 0, 0, false, true); if (resourceType == Constants.BITSTREAM) { PolicySet.setPolicies(c, Constants.COLLECTION, collectionId, Constants.BUNDLE, 0, 0, false, true); } // return to the main page showMainPage(c, request, response); } else if (button.equals("submit_advanced_add")) { AuthorizeUtil.requireAdminRole(c); // add a policy to a set of objects int collectionId = UIUtil.getIntParameter(request, "collection_id"); int resourceType = UIUtil.getIntParameter(request, "resource_type"); int actionId = UIUtil.getIntParameter(request, "action_id"); int groupId = UIUtil.getIntParameter(request, "group_id"); PolicySet.setPolicies(c, Constants.COLLECTION, collectionId, resourceType, actionId, groupId, false, false); // if it's a bitstream, do it to the bundle too if (resourceType == Constants.BITSTREAM) { PolicySet.setPolicies(c, Constants.COLLECTION, collectionId, Constants.BUNDLE, actionId, groupId, false, false); } // return to the main page showMainPage(c, request, response); } else if (button.equals("submit_collection_select")) { // edit the collection's permissions Collection collection = Collection.find(c, UIUtil.getIntParameter( request, "collection_id")); List<ResourcePolicy> policies = AuthorizeManager.getPolicies(c, collection); request.setAttribute("collection", collection); request.setAttribute("policies", policies); JSPManager.showJSP(request, response, "/dspace-admin/authorize-collection-edit.jsp"); } else { // return to the main page showMainPage(c, request, response); } c.complete(); } void showMainPage(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { JSPManager.showJSP(request, response, "/dspace-admin/authorize-main.jsp"); } void prepItemEditForm(Context c, HttpServletRequest request, Item item) throws SQLException { List<ResourcePolicy> itemPolicies = AuthorizeManager.getPolicies(c, item); // Put bundle and bitstream policies in their own hashes Map<Integer, List<ResourcePolicy>> bundlePolicies = new HashMap<Integer, List<ResourcePolicy>>(); Map<Integer, List<ResourcePolicy>> bitstreamPolicies = new HashMap<Integer, List<ResourcePolicy>>(); Bundle[] bundles = item.getBundles(); for (int i = 0; i < bundles.length; i++) { Bundle myBundle = bundles[i]; List<ResourcePolicy> myPolicies = AuthorizeManager.getPolicies(c, myBundle); // add bundle's policies to bundle_policies map bundlePolicies.put(Integer.valueOf(myBundle.getID()), myPolicies); // go through all bundle's bitstreams, add to bitstream map Bitstream[] bitstreams = myBundle.getBitstreams(); for (int j = 0; j < bitstreams.length; j++) { Bitstream myBitstream = bitstreams[j]; myPolicies = AuthorizeManager.getPolicies(c, myBitstream); bitstreamPolicies.put(Integer.valueOf(myBitstream.getID()), myPolicies); } } request.setAttribute("item", item); request.setAttribute("item_policies", itemPolicies); request.setAttribute("bundles", bundles); request.setAttribute("bundle_policies", bundlePolicies); request.setAttribute("bitstream_policies", bitstreamPolicies); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet.admin; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.dspace.app.util.AuthorizeUtil; import org.dspace.app.util.DCInput; import org.dspace.app.util.DCInputsReaderException; import org.dspace.app.util.Util; import org.dspace.app.webui.servlet.DSpaceServlet; import org.dspace.app.webui.util.FileUploadRequest; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.content.Bitstream; import org.dspace.content.BitstreamFormat; import org.dspace.content.Bundle; import org.dspace.content.Collection; import org.dspace.content.DCDate; import org.dspace.content.DCPersonName; import org.dspace.content.DCSeriesNumber; import org.dspace.content.DCValue; import org.dspace.content.DSpaceObject; import org.dspace.content.FormatIdentifier; import org.dspace.content.Item; import org.dspace.content.MetadataField; import org.dspace.content.MetadataSchema; import org.dspace.content.authority.ChoiceAuthorityManager; import org.dspace.content.authority.Choices; import org.dspace.content.authority.MetadataAuthorityManager; import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.handle.HandleManager; import org.dspace.license.CreativeCommons; import proj.oceandocs.submission.DCInputSetExt; import proj.oceandocs.submission.DCInputsReaderExt; /** * Servlet for editing and deleting (expunging) items * * @author Robert Tansley * @version $Revision: 6158 $ */ public class EditItemServlet extends DSpaceServlet { /** User wants to delete (expunge) an item */ public static final int START_DELETE = 1; /** User confirms delete (expunge) of item */ public static final int CONFIRM_DELETE = 2; /** User updates item */ public static final int UPDATE_ITEM = 3; /** User starts withdrawal of item */ public static final int START_WITHDRAW = 4; /** User confirms withdrawal of item */ public static final int CONFIRM_WITHDRAW = 5; /** User reinstates a withdrawn item */ public static final int REINSTATE = 6; /** User starts the movement of an item */ public static final int START_MOVE_ITEM = 7; /** User confirms the movement of the item */ public static final int CONFIRM_MOVE_ITEM = 8; public static final int CHANGE_DOCTYPE = 9; public static final int ADD_FIELD = 10; public static final int REMOVE_FIELD = 11; public static final int NEW_FIELD = 12; public static final String LANGUAGE_QUALIFIER = getDefaultLanguageQualifier(); /** Logger */ private static Logger log = Logger.getLogger(EditItemServlet.class); private static DCInputsReaderExt inputsReader = null; @Override protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { /* * GET with no parameters displays "find by handle/id" form parameter * item_id -> find and edit item with internal ID item_id parameter * handle -> find and edit corresponding item if internal ID or Handle * are invalid, "find by handle/id" form is displayed again with error * message */ int internalID = UIUtil.getIntParameter(request, "item_id"); String handle = request.getParameter("handle"); boolean showError = false; // See if an item ID or Handle was passed in Item itemToEdit = null; if (internalID > 0) { itemToEdit = Item.find(context, internalID); showError = (itemToEdit == null); } else if ((handle != null) && !handle.equals("")) { // resolve handle DSpaceObject dso = HandleManager.resolveToObject(context, handle.trim()); // make sure it's an ITEM if ((dso != null) && (dso.getType() == Constants.ITEM)) { itemToEdit = (Item) dso; showError = false; } else { showError = true; } } // Show edit form if appropriate if (itemToEdit != null) { // now check to see if person can edit item checkEditAuthorization(context, itemToEdit); showEditForm(context, request, response, itemToEdit); } else { if (showError) { request.setAttribute("invalid.id", Boolean.TRUE); } JSPManager.showJSP(request, response, "/tools/get-item-id.jsp"); } } @Override protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // First, see if we have a multipart request (uploading a new bitstream) String contentType = request.getContentType(); if ((contentType != null) && (contentType.indexOf("multipart/form-data") != -1)) { // This is a multipart request, so it's a file upload processUploadBitstream(context, request, response); return; } /* * Then we check for a "cancel" button - if it's been pressed, we simply * return to the "find by handle/id" page */ if (request.getParameter("submit_cancel") != null) { JSPManager.showJSP(request, response, "/tools/get-item-id.jsp"); return; } /* * Respond to submitted forms. Each form includes an "action" parameter * indicating what needs to be done (from the constants above.) */ int action = UIUtil.getIntParameter(request, "action"); Item item = Item.find(context, UIUtil.getIntParameter(request, "item_id")); if (item == null) { return; } String handle = HandleManager.findHandle(context, item); // now check to see if person can edit item checkEditAuthorization(context, item); request.setAttribute("item", item); request.setAttribute("handle", handle); switch (action) { case START_DELETE: // Show "delete item" confirmation page JSPManager.showJSP(request, response, "/tools/confirm-delete-item.jsp"); break; case CONFIRM_DELETE: // Delete the item - if "cancel" was pressed this would be // picked up above // FIXME: Don't know if this does all it should - remove Handle? Collection[] collections = item.getCollections(); // Remove item from all the collections it's in for (int i = 0; i < collections.length; i++) { collections[i].removeItem(item); } // Due to "virtual" owning collection, item.getCollections() could have excluded the owning collection // so delete the item from it's owning collection if (item.getOwningCollection() != null) item.getOwningCollection().removeItem(item); JSPManager.showJSP(request, response, "/tools/get-item-id.jsp"); context.complete(); break; case UPDATE_ITEM: processUpdateItem(context, request, response, item); break; case START_WITHDRAW: // Show "withdraw item" confirmation page JSPManager.showJSP(request, response, "/tools/confirm-withdraw-item.jsp"); break; case CONFIRM_WITHDRAW: // Withdraw the item item.withdraw(); JSPManager.showJSP(request, response, "/tools/get-item-id.jsp"); context.complete(); break; case REINSTATE: item.reinstate(); JSPManager.showJSP(request, response, "/tools/get-item-id.jsp"); context.complete(); break; case START_MOVE_ITEM: if (AuthorizeManager.isAdmin(context, item)) { // Display move collection page with fields of collections and communities Collection[] allNotLinkedCollections = item.getCollectionsNotLinked(); Collection[] allLinkedCollections = item.getCollections(); // get only the collection where the current user has the right permission List<Collection> authNotLinkedCollections = new ArrayList<Collection>(); for (Collection c : allNotLinkedCollections) { if (AuthorizeManager.authorizeActionBoolean(context, c, Constants.ADD)) { authNotLinkedCollections.add(c); } } List<Collection> authLinkedCollections = new ArrayList<Collection>(); for (Collection c : allLinkedCollections) { if (AuthorizeManager.authorizeActionBoolean(context, c, Constants.REMOVE)) { authLinkedCollections.add(c); } } Collection[] notLinkedCollections = new Collection[authNotLinkedCollections.size()]; notLinkedCollections = authNotLinkedCollections.toArray(notLinkedCollections); Collection[] linkedCollections = new Collection[authLinkedCollections.size()]; linkedCollections = authLinkedCollections.toArray(linkedCollections); request.setAttribute("linkedCollections", linkedCollections); request.setAttribute("notLinkedCollections", notLinkedCollections); JSPManager.showJSP(request, response, "/tools/move-item.jsp"); } else { throw new ServletException("You must be an administrator to move an item"); } break; case CONFIRM_MOVE_ITEM: if (AuthorizeManager.isAdmin(context, item)) { Collection fromCollection = Collection.find(context, UIUtil.getIntParameter(request, "collection_from_id")); Collection toCollection = Collection.find(context, UIUtil.getIntParameter(request, "collection_to_id")); Boolean inheritPolicies = false; if (request.getParameter("inheritpolicies") != null) { inheritPolicies = true; } if (fromCollection == null || toCollection == null) { throw new ServletException("Missing or incorrect collection IDs for moving item"); } item.move(fromCollection, toCollection, inheritPolicies); showEditForm(context, request, response, item); context.complete(); } else { throw new ServletException("You must be an administrator to move an item"); } break; case CHANGE_DOCTYPE: String doctype = request.getParameter("select_doctype"); if (doctype != null && !"".equals(doctype)) { item.clearMetadata("dc", "type", null, Item.ANY); item.addMetadata("dc", "type", null, Item.ANY, doctype); item.update(); showEditForm(context, request, response, item); context.complete(); } break; case ADD_FIELD: break; case REMOVE_FIELD: break; default: // Erm... weird action value received. log.warn(LogManager.getHeader(context, "integrity_error", UIUtil.getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); } } /** * Throw an exception if user isn't authorized to edit this item * * @param c * @param item */ private void checkEditAuthorization(Context c, Item item) throws AuthorizeException, java.sql.SQLException { if (!item.canEdit()) { int userID = 0; // first, check if userid is set if (c.getCurrentUser() != null) { userID = c.getCurrentUser().getID(); } // show an error or throw an authorization exception throw new AuthorizeException("EditItemServlet: User " + userID + " not authorized to edit item " + item.getID()); } } /** * Show the item edit form for a particular item * * @param context * DSpace context * @param request * the HTTP request containing posted info * @param response * the HTTP response * @param item * the item */ private void showEditForm(Context context, HttpServletRequest request, HttpServletResponse response, Item item) throws ServletException, IOException, SQLException, AuthorizeException { if (request.getParameter("cc_license_url") != null) { // check authorization AuthorizeUtil.authorizeManageCCLicense(context, item); // turn off auth system to allow replace also to user that can't // remove/add bitstream to the item context.turnOffAuthorisationSystem(); // set or replace existing CC license CreativeCommons.setLicense(context, item, request.getParameter("cc_license_url")); context.restoreAuthSystemState(); context.commit(); } // Get the handle, if any String handle = HandleManager.findHandle(context, item); // Collections Collection[] collections = item.getCollections(); // All DC types in the registry MetadataField[] types = MetadataField.findAll(context); // Get a HashMap of metadata field ids and a field name to display Map<Integer, String> metadataFields = new HashMap<Integer, String>(); // Get all existing Schemas MetadataSchema[] schemas = MetadataSchema.findAll(context); for (int i = 0; i < schemas.length; i++) { String schemaName = schemas[i].getName(); // Get all fields for the given schema MetadataField[] fields = MetadataField.findAllInSchema(context, schemas[i].getSchemaID()); for (int j = 0; j < fields.length; j++) { Integer fieldID = Integer.valueOf(fields[j].getFieldID()); String displayName = ""; displayName = schemaName + "." + fields[j].getElement() + (fields[j].getQualifier() == null ? "" : "." + fields[j].getQualifier()); metadataFields.put(fieldID, displayName); } } request.setAttribute("admin_button", AuthorizeManager.authorizeActionBoolean(context, item, Constants.ADMIN)); try { AuthorizeUtil.authorizeManageItemPolicy(context, item); request.setAttribute("policy_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("policy_button", Boolean.FALSE); } if (AuthorizeManager.authorizeActionBoolean(context, item.getParentObject(), Constants.REMOVE)) { request.setAttribute("delete_button", Boolean.TRUE); } else { request.setAttribute("delete_button", Boolean.FALSE); } try { AuthorizeManager.authorizeAction(context, item, Constants.ADD); request.setAttribute("create_bitstream_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("create_bitstream_button", Boolean.FALSE); } try { AuthorizeManager.authorizeAction(context, item, Constants.REMOVE); request.setAttribute("remove_bitstream_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("remove_bitstream_button", Boolean.FALSE); } try { AuthorizeUtil.authorizeManageCCLicense(context, item); request.setAttribute("cclicense_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("cclicense_button", Boolean.FALSE); } if (!item.isWithdrawn()) { try { AuthorizeUtil.authorizeWithdrawItem(context, item); request.setAttribute("withdraw_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("withdraw_button", Boolean.FALSE); } } else { try { AuthorizeUtil.authorizeReinstateItem(context, item); request.setAttribute("reinstate_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("reinstate_button", Boolean.FALSE); } } request.setAttribute("item", item); request.setAttribute("handle", handle); request.setAttribute("collections", collections); request.setAttribute("dc.types", types); request.setAttribute("metadataFields", metadataFields); JSPManager.showJSP(request, response, "/tools/edit-item-form.jsp"); } /** * Process input from the edit item form * * @param context * DSpace context * @param request * the HTTP request containing posted info * @param response * the HTTP response * @param item * the item */ private void processUpdateItem(Context context, HttpServletRequest request, HttpServletResponse response, Item item) throws ServletException, IOException, SQLException, AuthorizeException { String button = UIUtil.getSubmitButton(request, "submit"); String docType = ""; DCValue[] doctypes = item.getMetadata("dc", "type", null, Item.ANY); if (doctypes.length > 0) { docType = doctypes[0].value; } // We'll sort the parameters by name. This ensures that DC fields // of the same element/qualifier are added in the correct sequence. // Get the parameters names List<String> paramNames = Collections.list(request.getParameterNames()); List<DCInput> inputs = null; try { inputsReader = new DCInputsReaderExt(); DCInputSetExt inset = inputsReader.getInputs(docType); if (inset != null) { inputs = inset.getAllFields(); } } catch (DCInputsReaderException e) { throw new ServletException(e); } /* * "Cancel" handled above, so whatever happens, we need to update the * item metadata. First, we remove it all, then build it back up again. */ //item.clearMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY); // Step 1: // clear out all item metadata defined on this page for (int i = 0; i < inputs.size(); i++) { String qualifier = inputs.get(i).getQualifier(); if (qualifier == null && inputs.get(i).getInputType().equals("qualdrop_value")) { qualifier = Item.ANY; } item.clearMetadata(inputs.get(i).getSchema(), inputs.get(i).getElement(), qualifier, Item.ANY); } // now update the item metadata. String fieldName; boolean moreInput = false; for (int j = 0; j < inputs.size(); j++) { String element = inputs.get(j).getElement(); String qualifier = inputs.get(j).getQualifier(); String schema = inputs.get(j).getSchema(); if (qualifier != null && !qualifier.equals(Item.ANY)) { fieldName = schema + "_" + element + '_' + qualifier; } else { fieldName = schema + "_" + element; } String language_qual = request.getParameter(fieldName + "_lang"); String fieldKey = MetadataAuthorityManager.makeFieldKey(schema, element, qualifier); ChoiceAuthorityManager cmgr = ChoiceAuthorityManager.getManager(); String inputType = inputs.get(j).getInputType(); if (inputType.equals("name")) { readNames(request, item, schema, element, qualifier, inputs.get(j).getRepeatable()); } else if (inputType.equals("date")) { readDate(request, item, schema, element, qualifier); } // choice-controlled input with "select" presentation type is // always rendered as a dropdown menu else if (inputType.equals("dropdown") || inputType.equals("list") || (cmgr.isChoicesConfigured(fieldKey) && "select".equals(cmgr.getPresentation(fieldKey)))) { String[] vals = request.getParameterValues(fieldName); if (vals != null) { for (int z = 0; z < vals.length; z++) { if (!vals[z].equals("")) { item.addMetadata(schema, element, qualifier, language_qual == null ? LANGUAGE_QUALIFIER : language_qual, vals[z]); } } } } else if (inputType.equals("series")) { readSeriesNumbers(request, item, schema, element, qualifier, inputs.get(j).getRepeatable()); } else if (inputType.equals("qualdrop_value")) { List<String> quals = getRepeatedParameter(request, schema + "_" + element, schema + "_" + element + "_qualifier"); List<String> vals = getRepeatedParameter(request, schema + "_" + element, schema + "_" + element + "_value"); for (int z = 0; z < vals.size(); z++) { String thisQual = quals.get(z); if ("".equals(thisQual)) { thisQual = null; } String thisVal = vals.get(z); if (!button.equals("submit_" + schema + "_" + element + "_remove_" + z) && !thisVal.equals("")) { item.addMetadata(schema, element, thisQual, null, thisVal); } } } else if ((inputType.equals("onebox")) || (inputType.equals("twobox")) || (inputType.equals("textarea"))) { readText(request, item, schema, element, qualifier, inputs.get(j).getRepeatable(), language_qual == null ? LANGUAGE_QUALIFIER : language_qual); } else { throw new ServletException("Field " + fieldName + " has an unknown input type: " + inputType); } // determine if more input fields were requested if (!moreInput && button.equals("submit_" + fieldName + "_add")) { moreInput = true; item.addMetadata(schema, element, qualifier, LANGUAGE_QUALIFIER, ""); item.update(); // if(request.getAttribute("moreInputs") == null) // request.setAttribute("moreInputs", true); // showEditForm(context, request, response, item); } // was XMLUI's "remove" button pushed? else if (button.equals("submit_" + fieldName + "_delete")) { showEditForm(context, request, response, item); } } for (String p : paramNames) { if (p.startsWith("bitstream_name")) { // We have bitstream metadata // First, get the bundle and bitstream ID // Parameter name is bitstream_name_(bundleID)_(bitstreamID) StringTokenizer st = new StringTokenizer(p, "_"); // Ignore "bitstream" and "name" st.nextToken(); st.nextToken(); // Bundle ID and bitstream ID next int bundleID = Integer.parseInt(st.nextToken()); int bitstreamID = Integer.parseInt(st.nextToken()); Bundle bundle = Bundle.find(context, bundleID); Bitstream bitstream = Bitstream.find(context, bitstreamID); // Get the string "(bundleID)_(bitstreamID)" for finding other // parameters related to this bitstream String key = String.valueOf(bundleID) + "_" + bitstreamID; // Update bitstream metadata, or delete? if (button.equals("submit_delete_bitstream_" + key)) { // "delete" button pressed bundle.removeBitstream(bitstream); // Delete bundle too, if empty if (bundle.getBitstreams().length == 0) { item.removeBundle(bundle); } } else { // Update the bitstream metadata String name = request.getParameter(p); String source = request.getParameter("bitstream_source_" + key); String desc = request.getParameter("bitstream_description_" + key); int formatID = UIUtil.getIntParameter(request, "bitstream_format_id_" + key); String userFormatDesc = request.getParameter("bitstream_user_format_description_" + key); int primaryBitstreamID = UIUtil.getIntParameter(request, bundleID + "_primary_bitstream_id"); // Empty strings become non-null if (source.equals("")) { source = null; } if (desc.equals("")) { desc = null; } if (userFormatDesc.equals("")) { userFormatDesc = null; } bitstream.setName(name); bitstream.setSource(source); bitstream.setDescription(desc); bitstream.setFormat(BitstreamFormat.find(context, formatID)); if (primaryBitstreamID > 0) { bundle.setPrimaryBitstreamID(primaryBitstreamID); } if (userFormatDesc != null) { bitstream.setUserFormatDescription(userFormatDesc); } bitstream.update(); bundle.update(); } } } HashMap<String, String> otherFields = new HashMap<String, String>(); List<DCValue> otherDC = new ArrayList<DCValue>(); List<String> otherToClean = new ArrayList<String>(); for(String p: paramNames) { if(p.startsWith("other_")) otherFields.put(p, request.getParameter(p)); } String fname ="", fval ="", flang = ""; String parts[]; for(Map.Entry<String, String> kvp: otherFields.entrySet()) { if(!kvp.getKey().endsWith("_lang")) { parts = kvp.getKey().split("_"); fname = parts[2]; fval = kvp.getValue(); flang = otherFields.get(kvp.getKey() + "_lang"); if(!otherToClean.contains(fname)) otherToClean.add(fname); DCValue dcv = new DCValue(); dcv.value = fval; dcv.language = flang; dcv.setQuals(fname, "."); otherDC.add(dcv); } } for(String tc: otherToClean) { parts = tc.split("\\."); if(parts.length == 2) item.clearMetadata(parts[0], parts[1], null, Item.ANY); else if(parts.length == 3) item.clearMetadata(parts[0], parts[1], parts[2], Item.ANY); } for(DCValue dcv: otherDC) { // only if the value is nonempty if (dcv.value != null && !dcv.value.trim().equals("")) item.addMetadata(dcv.schema, dcv.element, dcv.qualifier, dcv.language, dcv.value); } /* * Now respond to button presses, other than "Remove" or "Delete" button * presses which were dealt with in the above loop. */ if (button.equals("submit_addfield")) { // Adding a metadata field int dcTypeID = UIUtil.getIntParameter(request, "addfield_dctype"); String value = request.getParameter("addfield_value").trim(); String lang = request.getParameter("addfield_lang"); // trim language and set empty string language = null if (lang != null) { lang = lang.trim(); if (lang.equals("")) { lang = null; } } MetadataField field = MetadataField.find(context, dcTypeID); MetadataSchema mschema = MetadataSchema.find(context, field.getSchemaID()); item.addMetadata(mschema.getName(), field.getElement(), field.getQualifier(), lang, value); item.update(); // showEditForm(context, request, response, item); } if (button.equals( "submit_addcc")) { // Show cc-edit page request.setAttribute("item", item); JSPManager.showJSP(request, response, "/tools/creative-commons-edit.jsp"); } if (button.equals( "submit_addbitstream")) { // Show upload bitstream page request.setAttribute("item", item); JSPManager.showJSP(request, response, "/tools/upload-bitstream.jsp"); } else { // Show edit page again showEditForm(context, request, response, item); } item.updateISSN(); //item.updateCitationString(); item.updateSubjectFields(); item.update(); // Complete transaction context.complete(); } /** * Process the input from the upload bitstream page * * @param context * current DSpace context * @param request * current servlet request object * @param response * current servlet response object */ private void processUploadBitstream(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { try { // Wrap multipart request to get the submission info FileUploadRequest wrapper = new FileUploadRequest(request); Bitstream b = null; Item item = Item.find(context, UIUtil.getIntParameter(wrapper, "item_id")); File temp = wrapper.getFile("file"); // Read the temp file as logo InputStream is = new BufferedInputStream(new FileInputStream(temp)); // now check to see if person can edit item checkEditAuthorization(context, item); // do we already have an ORIGINAL bundle? Bundle[] bundles = item.getBundles("ORIGINAL"); if (bundles.length < 1) { // set bundle's name to ORIGINAL b = item.createSingleBitstream(is, "ORIGINAL"); // set the permission as defined in the owning collection Collection owningCollection = item.getOwningCollection(); if (owningCollection != null) { Bundle bnd = b.getBundles()[0]; bnd.inheritCollectionDefaultPolicies(owningCollection); } } else { // we have a bundle already, just add bitstream b = bundles[0].createBitstream(is); } // Strip all but the last filename. It would be nice // to know which OS the file came from. String noPath = wrapper.getFilesystemName("file"); while (noPath.indexOf('/') > -1) { noPath = noPath.substring(noPath.indexOf('/') + 1); } while (noPath.indexOf('\\') > -1) { noPath = noPath.substring(noPath.indexOf('\\') + 1); } b.setName(noPath); b.setSource(wrapper.getFilesystemName("file")); // Identify the format BitstreamFormat bf = FormatIdentifier.guessFormat(context, b); b.setFormat(bf); b.update(); item.update(); // Back to edit form showEditForm(context, request, response, item); // Remove temp file if (!temp.delete()) { log.error("Unable to delete temporary file"); } // Update DB context.complete(); } catch (FileSizeLimitExceededException ex) { log.warn("Upload exceeded upload.max"); JSPManager.showFileSizeLimitExceededError(request, response, ex.getMessage(), ex.getActualSize(), ex.getPermittedSize()); } } // **************************************************************** // **************************************************************** // METHODS FOR FILLING DC FIELDS FROM METADATA FORMS // **************************************************************** // **************************************************************** /** * Set relevant metadata fields in an item from name values in the form. * Some fields are repeatable in the form. If this is the case, and the * field is "dc.contributor.author", the names in the request will be from * the fields as follows: * * dc_contributor_author_last -> last name of first author * dc_contributor_author_first -> first name(s) of first author * dc_contributor_author_last_1 -> last name of second author * dc_contributor_author_first_1 -> first name(s) of second author * * and so on. If the field is unqualified: * * dc_contributor_last -> last name of first contributor * dc_contributor_first -> first name(s) of first contributor * * If the parameter "submit_dc_contributor_author_remove_n" is set, that * value is removed. * * Otherwise the parameters are of the form: * * dc_contributor_author_last dc_contributor_author_first * * The values will be put in separate DCValues, in the form "last name, * first name(s)", ordered as they appear in the list. These will replace * any existing values. * * @param request * the request object * @param item * the item to update * @param schema * the metadata schema * @param element * the metadata element * @param qualifier * the metadata qualifier, or null if unqualified * @param repeated * set to true if the field is repeatable on the form */ protected void readNames(HttpServletRequest request, Item item, String schema, String element, String qualifier, boolean repeated) { String metadataField = MetadataField.formKey(schema, element, qualifier); String fieldKey = MetadataField.formKey(schema, element, qualifier); boolean isAuthorityControlled = false; // Names to add List<String> firsts = new LinkedList<String>(); List<String> lasts = new LinkedList<String>(); List<String> auths = new LinkedList<String>(); List<String> confs = new LinkedList<String>(); List<String> langs = new LinkedList<String>(); if (repeated) { firsts = getRepeatedParameter(request, metadataField, metadataField + "_first"); lasts = getRepeatedParameter(request, metadataField, metadataField + "_last"); langs = getRepeatedParameter(request, metadataField, metadataField + "_lang"); if (isAuthorityControlled) { auths = getRepeatedParameter(request, metadataField, metadataField + "_authority"); confs = getRepeatedParameter(request, metadataField, metadataField + "_confidence"); } // Find out if the relevant "remove" button was pressed // TODO: These separate remove buttons are only relevant // for DSpace JSP UI, and the code below can be removed // once the DSpace JSP UI is obsolete! String buttonPressed = Util.getSubmitButton(request, ""); String removeButton = "submit_" + metadataField + "_remove_"; if (buttonPressed.startsWith(removeButton)) { int valToRemove = Integer.parseInt(buttonPressed.substring(removeButton.length())); firsts.remove(valToRemove); lasts.remove(valToRemove); if (valToRemove < langs.size()) { langs.remove(valToRemove); } if (isAuthorityControlled) { auths.remove(valToRemove); confs.remove(valToRemove); } } } else { // Just a single name String lastName = request.getParameter(metadataField + "_last"); String firstNames = request.getParameter(metadataField + "_first"); String nameLang = request.getParameter(metadataField + "_lang"); String authority = request.getParameter(metadataField + "_authority"); String confidence = request.getParameter(metadataField + "_confidence"); if (lastName != null) { lasts.add(lastName); } if (firstNames != null) { firsts.add(firstNames); } if (nameLang != null) { langs.add(nameLang); } auths.add(authority == null ? "" : authority); confs.add(confidence == null ? "" : confidence); } // Remove existing values, already done in doProcessing see also bug DS-203 // item.clearMetadata(schema, element, qualifier, Item.ANY); // Put the names in the correct form for (int i = 0; i < lasts.size(); i++) { String f = firsts.get(i); String l = lasts.get(i); String ll = ""; if (i < langs.size()) { ll = langs.get(i); } // only add if lastname is non-empty if ((l != null) && !((l.trim()).equals(""))) { // Ensure first name non-null if (f == null) { f = ""; } // If there is a comma in the last name, we take everything // after that comma, and add it to the right of the // first name int comma = l.indexOf(','); if (comma >= 0) { f = f + l.substring(comma + 1); l = l.substring(0, comma); // Remove leading whitespace from first name while (f.startsWith(" ")) { f = f.substring(1); } } // Add to the database -- unless required authority is missing if (isAuthorityControlled) { String authKey = auths.size() > i ? auths.get(i) : null; String sconf = (authKey != null && confs.size() > i) ? confs.get(i) : null; if (MetadataAuthorityManager.getManager().isAuthorityRequired(fieldKey) && (authKey == null || authKey.length() == 0)) { log.warn("Skipping value of " + metadataField + " because the required Authority key is missing or empty."); //addErrorField(request, metadataField); } else { item.addMetadata(schema, element, qualifier, ll, new DCPersonName(l, f).toString(), authKey, (sconf != null && sconf.length() > 0) ? Choices.getConfidenceValue(sconf) : Choices.CF_ACCEPTED); } } else { item.addMetadata(schema, element, qualifier, ll, new DCPersonName(l, f).toString()); } } } } /** * Fill out an item's metadata values from a plain standard text field. If * the field isn't repeatable, the input field name is called: * * element_qualifier * * or for an unqualified element: * * element * * Repeated elements are appended with an underscore then an integer. e.g.: * * dc_title_alternative dc_title_alternative_1 * * The values will be put in separate DCValues, ordered as they appear in * the list. These will replace any existing values. * * @param request * the request object * @param item * the item to update * @param schema * the short schema name * @param element * the metadata element * @param qualifier * the metadata qualifier, or null if unqualified * @param repeated * set to true if the field is repeatable on the form * @param lang * language to set (ISO code) */ protected void readText(HttpServletRequest request, Item item, String schema, String element, String qualifier, boolean repeated, String lang) { // FIXME: Of course, language should be part of form, or determined // some other way String metadataField = MetadataField.formKey(schema, element, qualifier); String fieldKey = MetadataAuthorityManager.makeFieldKey(schema, element, qualifier); boolean isAuthorityControlled = MetadataAuthorityManager.getManager().isAuthorityControlled(fieldKey); // Values to add List<String> vals = null; List<String> auths = null; List<String> confs = null; List<String> langs = null; if (repeated) { vals = getRepeatedParameter(request, metadataField, metadataField); langs = getRepeatedParameter(request, metadataField, metadataField + "_lang"); if (isAuthorityControlled) { auths = getRepeatedParameter(request, metadataField, metadataField + "_authority"); confs = getRepeatedParameter(request, metadataField, metadataField + "_confidence"); } // Find out if the relevant "remove" button was pressed // TODO: These separate remove buttons are only relevant // for DSpace JSP UI, and the code below can be removed // once the DSpace JSP UI is obsolete! String buttonPressed = Util.getSubmitButton(request, ""); String removeButton = "submit_" + metadataField + "_remove_"; if (buttonPressed.startsWith(removeButton)) { int valToRemove = Integer.parseInt(buttonPressed.substring(removeButton.length())); vals.remove(valToRemove); if (valToRemove < langs.size()) { langs.remove(valToRemove); } if (isAuthorityControlled) { auths.remove(valToRemove); confs.remove(valToRemove); } } } else { // Just a single name vals = new LinkedList<String>(); langs = new LinkedList<String>(); String value = request.getParameter(metadataField); String ll = request.getParameter(metadataField + "_lang"); if (value != null) { vals.add(value.trim()); } if (ll != null) { langs.add(ll); } if (isAuthorityControlled) { auths = new LinkedList<String>(); confs = new LinkedList<String>(); String av = request.getParameter(metadataField + "_authority"); String cv = request.getParameter(metadataField + "_confidence"); auths.add(av == null ? "" : av.trim()); confs.add(cv == null ? "" : cv.trim()); } } // Remove existing values, already done in doProcessing see also bug DS-203 // item.clearMetadata(schema, element, qualifier, Item.ANY); // Put the names in the correct form for (int i = 0; i < vals.size(); i++) { // Add to the database if non-empty String s = vals.get(i); String l = lang; if (i < langs.size()) { l = langs.get(i); } if ((s != null) && !s.equals("")) { if (isAuthorityControlled) { String authKey = auths.size() > i ? auths.get(i) : null; String sconf = (authKey != null && confs.size() > i) ? confs.get(i) : null; if (MetadataAuthorityManager.getManager().isAuthorityRequired(fieldKey) && (authKey == null || authKey.length() == 0)) { log.warn("Skipping value of " + metadataField + " because the required Authority key is missing or empty."); //addErrorField(request, metadataField); } else { item.addMetadata(schema, element, qualifier, l, s, authKey, (sconf != null && sconf.length() > 0) ? Choices.getConfidenceValue(sconf) : Choices.CF_ACCEPTED); } } else { item.addMetadata(schema, element, qualifier, l, s); } } } } /** * Fill out a metadata date field with the value from a form. The date is * taken from the three parameters: * * element_qualifier_year element_qualifier_month element_qualifier_day * * The granularity is determined by the values that are actually set. If the * year isn't set (or is invalid) * * @param request * the request object * @param item * the item to update * @param schema * the metadata schema * @param element * the metadata element * @param qualifier * the metadata qualifier, or null if unqualified * @throws SQLException */ protected void readDate(HttpServletRequest request, Item item, String schema, String element, String qualifier) throws SQLException { String metadataField = MetadataField.formKey(schema, element, qualifier); int year = Util.getIntParameter(request, metadataField + "_year"); int month = Util.getIntParameter(request, metadataField + "_month"); int day = Util.getIntParameter(request, metadataField + "_day"); // FIXME: Probably should be some more validation // Make a standard format date DCDate d = new DCDate(year, month, day, -1, -1, -1); // already done in doProcessing see also bug DS-203 // item.clearMetadata(schema, element, qualifier, Item.ANY); if (year > 0) { // Only put in date if there is one! item.addMetadata(schema, element, qualifier, null, d.toString()); } } /** * Set relevant metadata fields in an item from series/number values in the * form. Some fields are repeatable in the form. If this is the case, and * the field is "relation.ispartof", the names in the request will be from * the fields as follows: * * dc_relation_ispartof_series dc_relation_ispartof_number * dc_relation_ispartof_series_1 dc_relation_ispartof_number_1 * * and so on. If the field is unqualified: * * dc_relation_series dc_relation_number * * Otherwise the parameters are of the form: * * dc_relation_ispartof_series dc_relation_ispartof_number * * The values will be put in separate DCValues, in the form "last name, * first name(s)", ordered as they appear in the list. These will replace * any existing values. * * @param request * the request object * @param item * the item to update * @param schema * the metadata schema * @param element * the metadata element * @param qualifier * the metadata qualifier, or null if unqualified * @param repeated * set to true if the field is repeatable on the form */ protected void readSeriesNumbers(HttpServletRequest request, Item item, String schema, String element, String qualifier, boolean repeated) { String metadataField = MetadataField.formKey(schema, element, qualifier); // Names to add List<String> series = new LinkedList<String>(); List<String> numbers = new LinkedList<String>(); if (repeated) { series = getRepeatedParameter(request, metadataField, metadataField + "_series"); numbers = getRepeatedParameter(request, metadataField, metadataField + "_number"); // Find out if the relevant "remove" button was pressed String buttonPressed = Util.getSubmitButton(request, ""); String removeButton = "submit_" + metadataField + "_remove_"; if (buttonPressed.startsWith(removeButton)) { int valToRemove = Integer.parseInt(buttonPressed.substring(removeButton.length())); series.remove(valToRemove); numbers.remove(valToRemove); } } else { // Just a single name String s = request.getParameter(metadataField + "_series"); String n = request.getParameter(metadataField + "_number"); // Only put it in if there was a name present if ((s != null) && !s.equals("")) { // if number is null, just set to a nullstring if (n == null) { n = ""; } series.add(s); numbers.add(n); } } // Remove existing values, already done in doProcessing see also bug DS-203 // item.clearMetadata(schema, element, qualifier, Item.ANY); // Put the names in the correct form for (int i = 0; i < series.size(); i++) { String s = (series.get(i)).trim(); String n = (numbers.get(i)).trim(); // Only add non-empty if (!s.equals("") || !n.equals("")) { item.addMetadata(schema, element, qualifier, null, new DCSeriesNumber(s, n).toString()); } } } /** * Get repeated values from a form. If "foo" is passed in as the parameter, * values in the form of parameters "foo", "foo_1", "foo_2", etc. are * returned. * <P> * This method can also handle "composite fields" (metadata fields which may * require multiple params, etc. a first name and last name). * * @param request * the HTTP request containing the form information * @param metadataField * the metadata field which can store repeated values * @param param * the repeated parameter on the page (used to fill out the * metadataField) * * @return a List of Strings */ protected List<String> getRepeatedParameter(HttpServletRequest request, String metadataField, String param) { List<String> vals = new LinkedList<String>(); int i = 1; //start index at the first of the previously entered values boolean foundLast = false; // Iterate through the values in the form. while (!foundLast) { String s = null; //First, add the previously entered values. // This ensures we preserve the order that these values were entered s = request.getParameter(param + "_" + i); // If there are no more previously entered values, // see if there's a new value entered in textbox if (s == null) { s = request.getParameter(param); //this will be the last value added foundLast = true; } // We're only going to add non-null values if (s != null) { boolean addValue = true; // Check to make sure that this value was not selected to be // removed. // (This is for the "remove multiple" option available in // Manakin) String[] selected = request.getParameterValues(metadataField + "_selected"); if (selected != null) { for (int j = 0; j < selected.length; j++) { if (selected[j].equals(metadataField + "_" + i)) { addValue = false; } } } if (addValue) { vals.add(s.trim()); } } i++; } log.debug("getRepeatedParameter: metadataField=" + metadataField + " param=" + metadataField + ", return count = " + vals.size()); return vals; } /** * @return the default language qualifier for metadata */ public static String getDefaultLanguageQualifier() { String language = ""; language = ConfigurationManager.getProperty("default.language"); if (StringUtils.isEmpty(language)) { language = "en"; } return language; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet.admin; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dspace.app.webui.servlet.DSpaceServlet; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.core.I18nUtil; /** * Servlet for editing the default license * * @author Stuart Lewis */ public class LicenseEditServlet extends DSpaceServlet { /** * Handle GET requests. This does nothing but forwards * the request on to the POST handler. */ protected void doDSGet(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Forward on to the post handler this.doDSPost(c, request, response); } /** * Handle the POST requests. */ protected void doDSPost(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { //Get submit button String button = UIUtil.getSubmitButton(request, "submit"); if (button.equals("submit_cancel")) { // Show main admin index JSPManager.showJSP(request, response, "/dspace-admin/index.jsp"); } else if (!button.equals("submit_save")) { // Get the existing text from the ConfigurationManager String license = ConfigurationManager.getLicenseText(I18nUtil.getDefaultLicense(c)); // Pass the existing license back to the JSP request.setAttribute("license", license); // Show edit page JSPManager.showJSP(request, response, "/dspace-admin/license-edit.jsp"); } else { // Get text string from form String license = (String)request.getParameter("license"); // Is the license empty? if (license.trim().equals("")) { // Get the existing text from the ConfigurationManager license = ConfigurationManager.getLicenseText(I18nUtil.getDefaultLicense(c)); // Pass the existing license back to the JSP request.setAttribute("license", license); // Pass the 'empty' message back request.setAttribute("empty", "true"); // Show edit page JSPManager.showJSP(request, response, "/dspace-admin/license-edit.jsp"); } else { // Write the string out to file ConfigurationManager.writeLicenseFile(I18nUtil.getDefaultLicense(c), license); // Pass the existing license back to the JSP request.setAttribute("license", license); // Pass the 'edited' message back request.setAttribute("edited", "true"); // Show edit page JSPManager.showJSP(request, response, "/dspace-admin/license-edit.jsp"); } } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet.admin; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.authorize.AuthorizeException; import org.dspace.browse.BrowseException; import org.dspace.browse.BrowseIndex; import org.dspace.browse.BrowserScope; import org.dspace.core.Context; import org.dspace.app.webui.servlet.AbstractBrowserServlet; import org.dspace.app.webui.util.JSPManager; /** * Servlet for browsing through withdrawn items: * * @author Graham Triggs * @version $Revision: 6164 $ */ public class WithdrawnBrowserServlet extends AbstractBrowserServlet { /** log4j category */ private static Logger log = Logger.getLogger(WithdrawnBrowserServlet.class); /** * Do the usual DSpace GET method. You will notice that browse does not currently * respond to POST requests. */ protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { try { // all browse requests currently come to GET. BrowserScope scope = getBrowserScopeForRequest(context, request, response); // Check that we are doing an item browse if (scope.getBrowseIndex() == null || scope.getBrowseIndex().isItemIndex()) { // And override the index in the scope with the withdrawn items scope.setBrowseIndex(BrowseIndex.getWithdrawnBrowseIndex()); } else { showError(context, request, response); } // execute browse request processBrowse(context, scope, request, response); } catch (BrowseException be) { log.error("caught exception: ", be); throw new ServletException(be); } } /** * Display the error page * * @param context * @param request * @param response * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ protected void showError(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { request.setAttribute("useAdminLayout", "yes"); JSPManager.showInternalError(request, response); } /** * Display the No Results page * * @param context * @param request * @param response * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ protected void showNoResultsPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { request.setAttribute("browseWithdrawn", "yes"); JSPManager.showJSP(request, response, "/browse/no-results.jsp"); } /** * Display the single page. This is the page which lists just the single values of a * metadata browse, not individual items. Single values are links through to all the items * that match that metadata value * * @param context * @param request * @param response * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ protected void showSinglePage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Show an error as this currently isn't supported showError(context, request, response); } /** * Display a full item listing. * * @param context * @param request * @param response * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ protected void showFullPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { request.setAttribute("browseWithdrawn", "yes"); JSPManager.showJSP(request, response, "/browse/full.jsp"); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet.admin; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.content.SupervisedItem; import org.dspace.content.WorkspaceItem; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.eperson.Group; import org.dspace.eperson.Supervisor; /** * Servlet to handle administration of the supervisory system * * @author Richard Jones * @version $Revision: 5845 $ */ public class SuperviseServlet extends org.dspace.app.webui.servlet.DSpaceServlet { /** log4j category */ private static Logger log = Logger.getLogger(SuperviseServlet.class); protected void doDSGet(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // pass all requests to the same place for simplicity doDSPost(c, request, response); } protected void doDSPost(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String button = UIUtil.getSubmitButton(request, "submit_base"); //direct the request to the relevant set of methods if (button.equals("submit_add")) { showLinkPage(c, request, response); } else if (button.equals("submit_view")) { showListPage(c, request, response); } else if (button.equals("submit_base")) { showMainPage(c, request, response); } else if (button.equals("submit_link")) { // do form validation before anything else if (validateAddForm(c, request, response)) { addSupervisionOrder(c, request, response); showMainPage(c, request, response); } } else if (button.equals("submit_remove")) { showConfirmRemovePage(c, request, response); } else if (button.equals("submit_doremove")) { removeSupervisionOrder(c, request, response); showMainPage(c, request, response); } else if (button.equals("submit_clean")) { cleanSupervisorDatabase(c, request, response); showMainPage(c, request, response); } } //********************************************************************** //****************** Methods for Page display ************************** //********************************************************************** /** * Confirms the removal of a supervision order * * @param context the context of the request * @param request the servlet request * @param response the servlet response */ private void showConfirmRemovePage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // get the values from the request int wsItemID = UIUtil.getIntParameter(request,"siID"); int groupID = UIUtil.getIntParameter(request,"gID"); // get the workspace item and the group from the request values WorkspaceItem wsItem = WorkspaceItem.find(context, wsItemID); Group group = Group.find(context, groupID); // set the attributes for the JSP request.setAttribute("wsItem",wsItem); request.setAttribute("group", group); JSPManager.showJSP(request, response, "/dspace-admin/supervise-confirm-remove.jsp" ); } /** * Displays the form to link groups to workspace items * * @param context the context of the request * @param request the servlet request * @param response the servlet response */ private void showLinkPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // get all the groups Group[] groups = Group.findAll(context,1); // get all the workspace items WorkspaceItem[] wsItems = WorkspaceItem.findAll(context); // set the attributes for the JSP request.setAttribute("groups",groups); request.setAttribute("wsItems",wsItems); JSPManager.showJSP(request, response, "/dspace-admin/supervise-link.jsp" ); } /** * Displays the options you have in the supervisor admin area * * @param context the context of the request * @param request the servlet request * @param response the servlet response */ private void showMainPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { JSPManager.showJSP(request, response, "/dspace-admin/supervise-main.jsp"); } /** * Displays the list of current settings for supervisors * * @param context the context of the request * @param request the servlet request * @param response the servlet response */ private void showListPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // get all the supervised items SupervisedItem[] si = SupervisedItem.getAll(context); // set the attributes for the JSP request.setAttribute("supervised",si); JSPManager.showJSP(request, response, "/dspace-admin/supervise-list.jsp" ); } //********************************************************************** //*************** Methods for data manipulation ************************ //********************************************************************** /** * Adds supervisory settings to the database * * @param context the context of the request * @param request the servlet request * @param response the servlet response */ void addSupervisionOrder(Context context, HttpServletRequest request, HttpServletResponse response) throws SQLException, AuthorizeException, ServletException, IOException { // get the values from the request int groupID = UIUtil.getIntParameter(request,"TargetGroup"); int wsItemID = UIUtil.getIntParameter(request,"TargetWSItem"); int policyType = UIUtil.getIntParameter(request, "PolicyType"); Supervisor.add(context, groupID, wsItemID, policyType); log.info(LogManager.getHeader(context, "Supervision Order Set", "workspace_item_id="+wsItemID+",eperson_group_id="+groupID)); context.complete(); } /** * Maintains integrity of the supervisory database. Should be more closely * integrated into the workspace code, perhaps * * @param context the context of the request * @param request the servlet request * @param response the servlet response */ private void cleanSupervisorDatabase(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // ditch any supervision orders that are no longer relevant Supervisor.removeRedundant(context); context.complete(); } /** * Remove the supervisory group and its policies from the database * * @param context the context of the request * @param request the servlet request * @param response the servlet response */ void removeSupervisionOrder(Context context, HttpServletRequest request, HttpServletResponse response) throws SQLException, AuthorizeException, ServletException, IOException { // get the values from the request int wsItemID = UIUtil.getIntParameter(request,"siID"); int groupID = UIUtil.getIntParameter(request,"gID"); Supervisor.remove(context, wsItemID, groupID); log.info(LogManager.getHeader(context, "Supervision Order Removed", "workspace_item_id="+wsItemID+",eperson_group_id="+groupID)); context.complete(); } /** * validate the submitted form to ensure that there is not a supervision * order for this already. * * @param context the context of the request * @param request the servlet request * @param response the servlet response */ private boolean validateAddForm(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { int groupID = UIUtil.getIntParameter(request,"TargetGroup"); int wsItemID = UIUtil.getIntParameter(request,"TargetWSItem"); boolean invalid = Supervisor.isOrder(context, wsItemID, groupID); if (invalid) { JSPManager.showJSP(request, response, "/dspace-admin/supervise-duplicate.jsp"); return false; } else { return true; } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet.admin; import java.io.IOException; import java.sql.SQLException; import java.util.Locale; import java.util.ResourceBundle; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.servlet.DSpaceServlet; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.content.MetadataField; import org.dspace.content.MetadataSchema; import org.dspace.content.NonUniqueMetadataException; import org.dspace.core.Context; /** * Servlet for editing the Dublin Core registry * * @author Robert Tansley * @author Martin Hald * @version $Revision: 5845 $ */ public class MetadataFieldRegistryServlet extends DSpaceServlet { /** Logger */ private static Logger log = Logger.getLogger(MetadataFieldRegistryServlet.class); private String clazz = "org.dspace.app.webui.servlet.admin.MetadataFieldRegistryServlet"; /** * @see org.dspace.app.webui.servlet.DSpaceServlet#doDSGet(org.dspace.core.Context, * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // GET just displays the list of type int schemaID = getSchemaID(request); showTypes(context, request, response, schemaID); } /** * @see org.dspace.app.webui.servlet.DSpaceServlet#doDSPost(org.dspace.core.Context, * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String button = UIUtil.getSubmitButton(request, "submit"); int schemaID = getSchemaID(request); // Get access to the localized resource bundle Locale locale = context.getCurrentLocale(); ResourceBundle labels = ResourceBundle.getBundle("Messages", locale); if (button.equals("submit_update")) { // The sanity check will update the request error string if needed if (!sanityCheck(request, labels)) { showTypes(context, request, response, schemaID); context.abort(); return; } try { // Update the metadata for a DC type MetadataField dc = MetadataField.find(context, UIUtil .getIntParameter(request, "dc_type_id")); dc.setElement(request.getParameter("element")); String qual = request.getParameter("qualifier"); if (qual.equals("")) { qual = null; } dc.setQualifier(qual); dc.setScopeNote(request.getParameter("scope_note")); dc.update(context); showTypes(context, request, response, schemaID); context.complete(); } catch (NonUniqueMetadataException e) { context.abort(); log.error(e); } } else if (button.equals("submit_add")) { // The sanity check will update the request error string if needed if (!sanityCheck(request, labels)) { showTypes(context, request, response, schemaID); context.abort(); return; } // Add a new DC type - simply add to the list, and let the user // edit with the main form try { MetadataField dc = new MetadataField(); dc.setSchemaID(schemaID); dc.setElement(request.getParameter("element")); String qual = request.getParameter("qualifier"); if (qual.equals("")) { qual = null; } dc.setQualifier(qual); dc.setScopeNote(request.getParameter("scope_note")); dc.create(context); showTypes(context, request, response, schemaID); context.complete(); } catch (NonUniqueMetadataException e) { // Record the exception as a warning log.warn(e); // Show the page again but with an error message to inform the // user that the metadata field was not created and why request.setAttribute("error", labels.getString(clazz + ".createfailed")); showTypes(context, request, response, schemaID); context.abort(); } } else if (button.equals("submit_delete")) { // Start delete process - go through verification step MetadataField dc = MetadataField.find(context, UIUtil .getIntParameter(request, "dc_type_id")); request.setAttribute("type", dc); JSPManager.showJSP(request, response, "/dspace-admin/confirm-delete-mdfield.jsp"); } else if (button.equals("submit_confirm_delete")) { // User confirms deletion of type MetadataField dc = MetadataField.find(context, UIUtil .getIntParameter(request, "dc_type_id")); try { dc.delete(context); request.setAttribute("failed", Boolean.FALSE); showTypes(context, request, response, schemaID); } catch (Exception e) { request.setAttribute("type", dc); request.setAttribute("failed", true); JSPManager.showJSP(request, response, "/dspace-admin/confirm-delete-mdfield.jsp"); } context.complete(); } else if (button.equals("submit_move")) { // User requests that one or more metadata elements be moved to a // new metadata schema. Note that we change the default schema ID to // be the destination schema. try { schemaID = Integer.parseInt(request .getParameter("dc_dest_schema_id")); String[] param = request.getParameterValues("dc_field_id"); if (schemaID == 0 || param == null) { request.setAttribute("error", labels.getString(clazz + ".movearguments")); showTypes(context, request, response, schemaID); context.abort(); } else { for (int ii = 0; ii < param.length; ii++) { int fieldID = Integer.parseInt(param[ii]); MetadataField field = MetadataField.find(context, fieldID); field.setSchemaID(schemaID); field.update(context); } context.complete(); // Send the user to the metadata schema in which they just moved // the metadata fields response.sendRedirect(request.getContextPath() + "/dspace-admin/metadata-schema-registry?dc_schema_id=" + schemaID); } } catch (NonUniqueMetadataException e) { // Record the exception as a warning log.warn(e); // Show the page again but with an error message to inform the // user that the metadata field could not be moved request.setAttribute("error", labels.getString(clazz + ".movefailed")); showTypes(context, request, response, schemaID); context.abort(); } } else { // Cancel etc. pressed - show list again showTypes(context, request, response, schemaID); } } /** * Get the schema that we are currently working in from the HTTP request. If * not present then default to the DSpace Dublin Core schema (schemaID 1). * * @param request * @return the current schema ID */ private int getSchemaID(HttpServletRequest request) { int schemaID = MetadataSchema.DC_SCHEMA_ID; if (request.getParameter("dc_schema_id") != null) { schemaID = Integer.parseInt(request.getParameter("dc_schema_id")); } return schemaID; } /** * Show list of DC type * * @param context * Current DSpace context * @param request * Current HTTP request * @param response * Current HTTP response * @param schemaID * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ private void showTypes(Context context, HttpServletRequest request, HttpServletResponse response, int schemaID) throws ServletException, IOException, SQLException, AuthorizeException { // Find matching metadata fields MetadataField[] types = MetadataField .findAllInSchema(context, schemaID); request.setAttribute("types", types); // Pull the metadata schema object as well MetadataSchema schema = MetadataSchema.find(context, schemaID); request.setAttribute("schema", schema); // Pull all metadata schemas for the pulldown MetadataSchema[] schemas = MetadataSchema.findAll(context); request.setAttribute("schemas", schemas); JSPManager .showJSP(request, response, "/dspace-admin/list-metadata-fields.jsp"); } /** * Return false if the metadata field fail to pass the constraint tests. If * there is an error the request error String will be updated with an error * description. * * @param request * @param labels * @return true of false */ private boolean sanityCheck(HttpServletRequest request, ResourceBundle labels) { String element = request.getParameter("element"); if (element.length() == 0) { return error(request, labels.getString(clazz + ".elemempty")); } for (int ii = 0; ii < element.length(); ii++) { if (element.charAt(ii) == '.' || element.charAt(ii) == '_' || element.charAt(ii) == ' ') { return error(request, labels.getString(clazz + ".badelemchar")); } } if (element.length() > 64) { return error(request, labels.getString(clazz + ".elemtoolong")); } String qualifier = request.getParameter("qualifier"); if ("".equals(qualifier)) { qualifier = null; } if (qualifier != null) { if (qualifier.length() > 64) { return error(request, labels.getString(clazz + ".qualtoolong")); } for (int ii = 0; ii < qualifier.length(); ii++) { if (qualifier.charAt(ii) == '.' || qualifier.charAt(ii) == '_' || qualifier.charAt(ii) == ' ') { return error(request, labels.getString(clazz + ".badqualchar")); } } } return true; } /** * Bind the error text to the request object. * * @param request * @param text * @return false */ private boolean error(HttpServletRequest request, String text) { request.setAttribute("error", text); return false; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Collection; import org.dspace.core.Context; import org.dspace.eperson.EPerson; import org.dspace.eperson.Subscribe; /** * Servlet for constructing the components of the "My DSpace" page * * @author Robert Tansley * @version $Revision: 5845 $ */ public class SubscribeServlet extends DSpaceServlet { protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Simply show list of subscriptions showSubscriptions(context, request, response, false); } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { /* * Parameters: submit_unsubscribe - unsubscribe from a collection * submit_clear - clear all subscriptions submit_cancel - cancel update - * go to My DSpace. */ String submit = UIUtil.getSubmitButton(request, "submit"); EPerson e = context.getCurrentUser(); if (submit.equals("submit_clear")) { // unsubscribe user from everything Subscribe.unsubscribe(context, e, null); // Show the list of subscriptions showSubscriptions(context, request, response, true); context.complete(); } else if (submit.equals("submit_unsubscribe")) { int collID = UIUtil.getIntParameter(request, "collection"); Collection c = Collection.find(context, collID); // Sanity check - ignore duff values if (c != null) { Subscribe.unsubscribe(context, e, c); } // Show the list of subscriptions showSubscriptions(context, request, response, true); context.complete(); } else { // Back to "My DSpace" response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/mydspace")); } } /** * Show the list of subscriptions * * @param context * DSpace context * @param request * HTTP request * @param response * HTTP response * @param updated * if <code>true</code>, write a message indicating that * updated subscriptions have been stored */ private void showSubscriptions(Context context, HttpServletRequest request, HttpServletResponse response, boolean updated) throws ServletException, IOException, SQLException { // Subscribed collections Collection[] subs = Subscribe.getSubscriptions(context, context .getCurrentUser()); request.setAttribute("subscriptions", subs); request.setAttribute("updated", Boolean.valueOf(updated)); JSPManager.showJSP(request, response, "/mydspace/subscriptions.jsp"); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.io.InputStream; import java.net.URLDecoder; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.JSPManager; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Bitstream; import org.dspace.content.Bundle; import org.dspace.content.Item; import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.core.Utils; import org.dspace.handle.HandleManager; import org.dspace.usage.UsageEvent; import org.dspace.utils.DSpace; /** * Servlet for HTML bitstream support. * <P> * If we receive a request like this: * <P> * <code>http://dspace.foo.edu/html/123.456/789/foo/bar/index.html</code> * <P> * we first check for a bitstream with the *exact* filename * <code>foo/bar/index.html</code>. Otherwise, we strip the path information * (up to three levels deep to prevent infinite URL spaces occurring) and see if * we have a bitstream with the filename <code>index.html</code> (with no * path). If this exists, it is served up. This is because if an end user * uploads a composite HTML document with the submit UI, we will not have * accurate path information, and so we assume that if the browser is requesting * foo/bar/index.html but we only have index.html, that this is the desired file * but we lost the path information on upload. * * @author Austin Kim, Robert Tansley * @version $Revision: 5845 $ */ public class HTMLServlet extends DSpaceServlet { /** log4j category */ private static Logger log = Logger.getLogger(HTMLServlet.class); /** * Default maximum number of path elements to strip when testing if a * bitstream called "foo.html" should be served when "xxx/yyy/zzz/foo.html" * is requested. */ private int maxDepthGuess; /** * Create an HTML Servlet */ public HTMLServlet() { super(); if (ConfigurationManager.getProperty("webui.html.max-depth-guess") != null) { maxDepthGuess = ConfigurationManager .getIntProperty("webui.html.max-depth-guess"); } else { maxDepthGuess = 3; } } // Return bitstream whose name matches the target bitstream-name // bsName, or null if there is no match. Match must be exact. // NOTE: This does not detect duplicate bitstream names, just returns first. private static Bitstream getItemBitstreamByName(Item item, String bsName) throws SQLException { Bundle[] bundles = item.getBundles(); for (int i = 0; i < bundles.length; i++) { Bitstream[] bitstreams = bundles[i].getBitstreams(); for (int k = 0; k < bitstreams.length; k++) { if (bsName.equals(bitstreams[k].getName())) { return bitstreams[k]; } } } return null; } // On the surface it doesn't make much sense for this servlet to // handle POST requests, but in practice some HTML pages which // are actually JSP get called on with a POST, so it's needed. protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { doDSGet(context, request, response); } protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { Item item = null; Bitstream bitstream = null; String idString = request.getPathInfo(); String filenameNoPath = null; String fullpath = null; String handle = null; // Parse URL if (idString != null) { // Remove leading slash if (idString.startsWith("/")) { idString = idString.substring(1); } // Get handle and full file path int slashIndex = idString.indexOf('/'); if (slashIndex != -1) { slashIndex = idString.indexOf('/', slashIndex + 1); if (slashIndex != -1) { handle = idString.substring(0, slashIndex); fullpath = URLDecoder.decode(idString .substring(slashIndex + 1), Constants.DEFAULT_ENCODING); // Get filename with no path slashIndex = fullpath.indexOf('/'); if (slashIndex != -1) { String[] pathComponents = fullpath.split("/"); if (pathComponents.length <= maxDepthGuess + 1) { filenameNoPath = pathComponents[pathComponents.length - 1]; } } } } } if (handle != null && fullpath != null) { // Find the item try { /* * If the original item doesn't have a Handle yet (because it's * in the workflow) what we actually have is a fake Handle in * the form: db-id/1234 where 1234 is the database ID of the * item. */ if (handle.startsWith("db-id")) { String dbIDString = handle .substring(handle.indexOf('/') + 1); int dbID = Integer.parseInt(dbIDString); item = Item.find(context, dbID); } else { item = (Item) HandleManager .resolveToObject(context, handle); } } catch (NumberFormatException nfe) { // Invalid ID - this will be dealt with below } } if (item != null) { // Try to find bitstream with exactly matching name + path bitstream = getItemBitstreamByName(item, fullpath); if (bitstream == null && filenameNoPath != null) { // No match with the full path, but we can try again with // only the filename bitstream = getItemBitstreamByName(item, filenameNoPath); } } // Did we get a bitstream? if (bitstream != null) { log.info(LogManager.getHeader(context, "view_html", "handle=" + handle + ",bitstream_id=" + bitstream.getID())); new DSpace().getEventService().fireEvent( new UsageEvent( UsageEvent.Action.VIEW, request, context, bitstream)); //new UsageEvent().fire(request, context, AbstractUsageEvent.VIEW, // Constants.BITSTREAM, bitstream.getID()); // Set the response MIME type response.setContentType(bitstream.getFormat().getMIMEType()); // Response length response.setHeader("Content-Length", String.valueOf(bitstream .getSize())); // Pipe the bits InputStream is = bitstream.retrieve(); Utils.bufferedCopy(is, response.getOutputStream()); is.close(); response.getOutputStream().flush(); } else { // No bitstream - we got an invalid ID log.info(LogManager.getHeader(context, "view_html", "invalid_bitstream_id=" + idString)); JSPManager.showInvalidIDError(request, response, idString, Constants.BITSTREAM); } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.content.Item; import org.dspace.content.WorkspaceItem; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.LogManager; /** * Servlet for handling the workspace item * * @author Richard Jones * @version $Revision: 5845 $ */ public class WorkspaceServlet extends DSpaceServlet { /** log4j category */ private static Logger log = Logger.getLogger(WorkspaceServlet.class); protected void doDSGet(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // just pass all requests to the same place. doDSPost(c, request, response); } protected void doDSPost(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String button = UIUtil.getSubmitButton(request, "submit_error"); // direct the request to the relevant set of methods if (button.equals("submit_open")) { showMainPage(c, request, response); } else if (button.equals("submit_cancel")) { goToMyDSpace(c, request, response); } else if (button.equals("submit_error")) { showErrorPage(c, request, response); } } /** * Show error page if nothing has been <code>POST</code>ed to servlet * * @param context the context of the request * @param request the servlet request * @param response the servlet response */ private void showErrorPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { int wsItemID = UIUtil.getIntParameter(request, "workspace_id"); log.error(LogManager.getHeader(context, "Workspace Item View Failed", "workspace_item_id="+wsItemID)); JSPManager.showJSP(request, response, "/workspace/ws-error.jsp"); } /** * Return the user to the mydspace servlet * * @param context the context of the request * @param request the servlet request * @param response the servlet response */ private void goToMyDSpace(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { response.sendRedirect(response.encodeRedirectURL( request.getContextPath() + "/mydspace")); } /** * show the workspace item home page * * @param context the context of the request * @param request the servlet request * @param response the servlet response */ private void showMainPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // get the values out of the request int wsItemID = UIUtil.getIntParameter(request, "workspace_id"); // get the workspace item WorkspaceItem wsItem = WorkspaceItem.find(context, wsItemID); // Ensure the user has authorisation Item item = wsItem.getItem(); AuthorizeManager.authorizeAction(context, item, Constants.READ); log.info(LogManager.getHeader(context, "View Workspace Item", "workspace_item_id="+wsItemID)); // set the attributes for the JSP request.setAttribute("wsItem", wsItem); JSPManager.showJSP(request, response, "/workspace/ws-main.jsp"); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.io.Writer; import java.sql.SQLException; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dspace.authorize.AuthorizeException; import org.dspace.core.Context; import org.dspace.content.authority.Choice; import proj.oceandocs.authority.AuthorityManager; /** * * @author Denys Slipetskyy */ public class AuthorityServlet extends DSpaceServlet { @Override protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { process(context, request, response); } @Override protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { process(context, request, response); } /** * Generate the <li> element for scripaculos autocompleter component * * Looks for request parameters: * field - MD field key, i.e. form key, REQUIRED - derivated from url. * query - string to match * collection - db ID of Collection ot serve as context * start - index to start from, default 0. * limit - max number of lines, default 1000. * format - opt. result XML/XHTML format: "select", "ul", "xml"(default) * locale - explicit locale, pass to choice plugin */ private void process(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String[] paths = request.getPathInfo().split("/"); String generator = paths[paths.length - 1]; String input = request.getParameter("value") == null ? "": request.getParameter("value"); response.setContentType("text/plain; charset=\"utf-8\""); Writer writer = response.getWriter(); AuthorityManager am = new AuthorityManager(generator, context); if(am != null){ ArrayList<Choice> choices = am.getAutocompleteSet(input); writer.append("<ul>"); for(Choice ch: choices) { writer.append("<li id=\"").append(ch.authority).append("\">").append(ch.value).append("</li>\n"); } writer.append("</ul>"); }else { writer.append("<ul></ul>"); } writer.flush(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ /* * */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.io.Writer; import java.util.Properties; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.xml.sax.SAXException; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.content.authority.ChoiceAuthorityManager; import org.dspace.content.authority.Choices; import org.dspace.content.authority.ChoicesXMLGenerator; import org.dspace.core.Context; import org.apache.xml.serializer.SerializerFactory; import org.apache.xml.serializer.Serializer; import org.apache.xml.serializer.OutputPropertiesFactory; import org.apache.xml.serializer.Method; /** * * @author bollini */ public class AuthorityChooseServlet extends DSpaceServlet { @Override protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { process(context, request, response); } @Override protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { process(context, request, response); } /** * Generate the AJAX response Document. * * Looks for request parameters: * field - MD field key, i.e. form key, REQUIRED - derivated from url. * query - string to match * collection - db ID of Collection ot serve as context * start - index to start from, default 0. * limit - max number of lines, default 1000. * format - opt. result XML/XHTML format: "select", "ul", "xml"(default) * locale - explicit locale, pass to choice plugin */ private void process(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String[] paths = request.getPathInfo().split("/"); String field = paths[paths.length-1]; ChoiceAuthorityManager cam = ChoiceAuthorityManager.getManager(); String query = request.getParameter("query"); String format = request.getParameter("format"); int collection = UIUtil.getIntParameter(request, "collection"); int start = UIUtil.getIntParameter(request, "start"); int limit = UIUtil.getIntParameter(request, "limit"); Choices result = cam.getMatches(field, query, collection, start, limit, null); // Choice[] testValues = { // new Choice("rp0001", "VALUE1","TEST LABEL1"), // new Choice("rp0002", "VALUE2","TEST LABEL2"), // new Choice("rp0003", "VALUE3","TEST LABEL3"), // new Choice("rp0004", "VALUE COGN, LABEL1","TEST COGN, LABEL1"), // new Choice("rp0005", "VALUE COGN, LABEL2","TEST COGN, LABEL2"), // new Choice("rp0006", "VALUE COGN, LABEL3","TEST COGN, LABEL3") // }; // // Choices result = new Choices(testValues,start,testValues.length,Choices.CF_ACCEPTED,false); response.setContentType("text/xml; charset=\"utf-8\""); Writer writer = response.getWriter(); // borrow xalan's serializer to let us use SAX choice menu generator Properties props = OutputPropertiesFactory.getDefaultMethodProperties(Method.XML); Serializer ser = SerializerFactory.getSerializer(props); ser.setWriter(writer); try { ChoicesXMLGenerator.generate(result, format, ser.asContentHandler()); } catch(SAXException e) { throw new IOException(e.toString(), e); } finally { ser.reset(); } writer.flush(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Bitstream; import org.dspace.content.Bundle; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.core.Utils; import org.dspace.handle.HandleManager; import org.dspace.usage.UsageEvent; import org.dspace.utils.DSpace; /** * Servlet for retrieving bitstreams. The bits are simply piped to the user. If * there is an <code>If-Modified-Since</code> header, only a 304 status code * is returned if the containing item has not been modified since that date. * <P> * <code>/bitstream/handle/sequence_id/filename</code> * * @author Robert Tansley * @version $Revision: 5845 $ */ public class BitstreamServlet extends DSpaceServlet { /** log4j category */ private static Logger log = Logger.getLogger(BitstreamServlet.class); /** * Threshold on Bitstream size before content-disposition will be set. */ private int threshold; @Override public void init(ServletConfig arg0) throws ServletException { super.init(arg0); threshold = ConfigurationManager .getIntProperty("webui.content_disposition_threshold"); } @Override protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { Item item = null; Bitstream bitstream = null; // Get the ID from the URL String idString = request.getPathInfo(); String handle = ""; String sequenceText = ""; String filename = null; int sequenceID; if (idString == null) { idString = ""; } // Parse 'handle' and 'sequence' (bitstream seq. number) out // of remaining URL path, which is typically of the format: // {handle}/{sequence}/{bitstream-name} // But since the bitstream name MAY have any number of "/"s in // it, and the handle is guaranteed to have one slash, we // scan from the start to pick out handle and sequence: // Remove leading slash if any: if (idString.startsWith("/")) { idString = idString.substring(1); } // skip first slash within handle int slashIndex = idString.indexOf('/'); if (slashIndex != -1) { slashIndex = idString.indexOf('/', slashIndex + 1); if (slashIndex != -1) { handle = idString.substring(0, slashIndex); int slash2 = idString.indexOf('/', slashIndex + 1); if (slash2 != -1) { sequenceText = idString.substring(slashIndex+1,slash2); filename = idString.substring(slash2+1); } } } try { sequenceID = Integer.parseInt(sequenceText); } catch (NumberFormatException nfe) { sequenceID = -1; } // Now try and retrieve the item DSpaceObject dso = HandleManager.resolveToObject(context, handle); // Make sure we have valid item and sequence number if (dso != null && dso.getType() == Constants.ITEM && sequenceID >= 0) { item = (Item) dso; if (item.isWithdrawn()) { log.info(LogManager.getHeader(context, "view_bitstream", "handle=" + handle + ",withdrawn=true")); JSPManager.showJSP(request, response, "/tombstone.jsp"); return; } boolean found = false; Bundle[] bundles = item.getBundles(); for (int i = 0; (i < bundles.length) && !found; i++) { Bitstream[] bitstreams = bundles[i].getBitstreams(); for (int k = 0; (k < bitstreams.length) && !found; k++) { if (sequenceID == bitstreams[k].getSequenceID()) { bitstream = bitstreams[k]; found = true; } } } } if (bitstream == null || filename == null || !filename.equals(bitstream.getName())) { // No bitstream found or filename was wrong -- ID invalid log.info(LogManager.getHeader(context, "invalid_id", "path=" + idString)); JSPManager.showInvalidIDError(request, response, idString, Constants.BITSTREAM); return; } log.info(LogManager.getHeader(context, "view_bitstream", "bitstream_id=" + bitstream.getID())); //new UsageEvent().fire(request, context, AbstractUsageEvent.VIEW, // Constants.BITSTREAM, bitstream.getID()); new DSpace().getEventService().fireEvent( new UsageEvent( UsageEvent.Action.VIEW, request, context, bitstream)); // Modification date // Only use last-modified if this is an anonymous access // - caching content that may be generated under authorisation // is a security problem if (context.getCurrentUser() == null) { // TODO: Currently the date of the item, since we don't have dates // for files response.setDateHeader("Last-Modified", item.getLastModified() .getTime()); // Check for if-modified-since header long modSince = request.getDateHeader("If-Modified-Since"); if (modSince != -1 && item.getLastModified().getTime() < modSince) { // Item has not been modified since requested date, // hence bitstream has not; return 304 response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } // Pipe the bits InputStream is = bitstream.retrieve(); // Set the response MIME type response.setContentType(bitstream.getFormat().getMIMEType()); // Response length response.setHeader("Content-Length", String .valueOf(bitstream.getSize())); if(threshold != -1 && bitstream.getSize() >= threshold) { UIUtil.setBitstreamDisposition(bitstream.getName(), request, response); } Utils.bufferedCopy(is, response.getOutputStream()); is.close(); response.getOutputStream().flush(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.JSPManager; import org.dspace.authorize.AuthorizeException; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.core.Utils; /** * Servlet for retrieving sitemaps. * <P> * The servlet is configured via the "type" config parameter to serve either * sitemaps.org or basic HTML sitemaps. * <P> * The "map" parameter specifies the index of a sitemap to serve. If no "map" * parameter is specified, the sitemap index is served. * * @author Stuart Lewis * @author Robert Tansley * @version $Revision: 5845 $ */ public class SitemapServlet extends DSpaceServlet { /** log4j category */ private static Logger log = Logger.getLogger(SitemapServlet.class); /** true if we are for serving sitemap.org sitemaps, false otherwise */ private boolean forSitemapsOrg; public void init() { forSitemapsOrg = false; String initParam = getInitParameter("type"); if (initParam != null && initParam.equalsIgnoreCase("sitemaps.org")) { forSitemapsOrg = true; } else if (initParam == null || !initParam.equalsIgnoreCase("html")) { log.warn("Invalid initialization parameter for servlet " + getServletName() + ": assuming basic HTML"); } } protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String param = request.getParameter("map"); String ext = (forSitemapsOrg ? ".xml.gz" : ".html"); String mimeType = (forSitemapsOrg ? "text/xml" : "text/html"); String fileStem = (param == null ? "sitemap_index" : "sitemap" + param); sendFile(request, response, fileStem + ext, mimeType, forSitemapsOrg); } private void sendFile(HttpServletRequest request, HttpServletResponse response, String file, String mimeType, boolean compressed) throws ServletException, IOException { File f = new File(ConfigurationManager.getProperty("sitemap.dir"), file); if (!f.exists()) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); JSPManager.showJSP(request, response, "/error/404.jsp"); return; } long lastMod = f.lastModified(); response.setDateHeader("Last-Modified", lastMod); // Check for if-modified-since header long modSince = request.getDateHeader("If-Modified-Since"); if (modSince != -1 && lastMod < modSince) { // Sitemap file has not been modified since requested date, // hence bitstream has not; return 304 response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } if (compressed) { response.setHeader("Content-Encoding", "gzip"); } // Pipe the bits InputStream is = new FileInputStream(f); try { // Set the response MIME type response.setContentType(mimeType); // Response length response.setHeader("Content-Length", String.valueOf(f.length())); Utils.bufferedCopy(is, response.getOutputStream()); } finally { is.close(); } response.getOutputStream().flush(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.Item; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.handle.HandleManager; import org.dspace.search.DSQuery; import org.dspace.search.QueryArgs; import org.dspace.search.QueryResults; /** * Servlet that provides funcionality for searching the repository using a * controlled vocabulary as a basis for selecting the search keywords. * * @author Miguel Ferreira * @version $Revision: 5845 $ */ public class ControlledVocabularySearchServlet extends DSpaceServlet { // the log private static Logger log = Logger .getLogger(ControlledVocabularySearchServlet.class); // the jsp that displays the HTML version of controlled-vocabulary private static final String SEARCH_JSP = "/controlledvocabulary/search.jsp"; // the jsp that will show the search results private static final String RESULTS_JSP = "/controlledvocabulary/results.jsp"; /** * Handles requests */ protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String action = request.getParameter("action") == null ? "" : request .getParameter("action"); if (action.equals("search")) { List<String> keywords = extractKeywords(request); String query = join(keywords, " or "); doSearch(context, request, query); JSPManager.showJSP(request, response, RESULTS_JSP); } else if (action.equals("filter")) { String filter = request.getParameter("filter"); request.getSession().setAttribute("conceptsearch.filter", filter); JSPManager.showJSP(request, response, SEARCH_JSP); } else { JSPManager.showJSP(request, response, SEARCH_JSP); } } /** * Collects the selected terms from the HTML taxonomy displayed on the * search form * * @param request * The HttpServletRequest * @return A Vector with the selected terms from the taxonomy. */ private List<String> extractKeywords(HttpServletRequest request) { List<String> keywords = new ArrayList<String>(); Enumeration enumeration = request.getParameterNames(); while (enumeration.hasMoreElements()) { String element = (String) enumeration.nextElement(); if (element.startsWith("cb_")) { keywords.add("\"" + request.getParameter(element) + "\""); } } return keywords; } /** * Searches the repository and and puts the results in the request object * * @param context * The DSpace context * @param request * The request object * @param query * The query expression * @throws IOException * @throws SQLException */ private void doSearch(Context context, HttpServletRequest request, String query) throws IOException, SQLException { // Get the query // String query = request.getParameter("query"); int start = UIUtil.getIntParameter(request, "start"); String advanced = request.getParameter("advanced"); // can't start earlier than 0 in the results! if (start < 0) { start = 0; } List<String> itemHandles = new ArrayList<String>(); List<String> collectionHandles = new ArrayList<String>(); List<String> communityHandles = new ArrayList<String>(); Item[] resultsItems; Collection[] resultsCollections; Community[] resultsCommunities; QueryResults qResults = null; QueryArgs qArgs = new QueryArgs(); // if the "advanced" flag is set, build the query string from the // multiple query fields if (advanced != null) { query = qArgs.buildQuery(request); } // Ensure the query is non-null if (query == null) { query = ""; } // Build log information String logInfo = ""; // Get our location Community community = UIUtil.getCommunityLocation(request); Collection collection = UIUtil.getCollectionLocation(request); // get the start of the query results page // List resultObjects = null; qArgs.setQuery(query); qArgs.setStart(start); // Perform the search if (collection != null) { logInfo = "collection_id=" + collection.getID() + ","; // Values for drop-down box request.setAttribute("community", community); request.setAttribute("collection", collection); qResults = DSQuery.doQuery(context, qArgs, collection); } else if (community != null) { logInfo = "community_id=" + community.getID() + ","; request.setAttribute("community", community); // Get the collections within the community for the dropdown box request .setAttribute("collection.array", community .getCollections()); qResults = DSQuery.doQuery(context, qArgs, community); } else { // Get all communities for dropdown box Community[] communities = Community.findAll(context); request.setAttribute("community.array", communities); qResults = DSQuery.doQuery(context, qArgs); } // now instantiate the results and put them in their buckets for (int i = 0; i < qResults.getHitHandles().size(); i++) { String myHandle = qResults.getHitHandles().get(i); Integer myType = qResults.getHitTypes().get(i); // add the handle to the appropriate lists switch (myType.intValue()) { case Constants.ITEM: itemHandles.add(myHandle); break; case Constants.COLLECTION: collectionHandles.add(myHandle); break; case Constants.COMMUNITY: communityHandles.add(myHandle); break; } } int numCommunities = communityHandles.size(); int numCollections = collectionHandles.size(); int numItems = itemHandles.size(); // Make objects from the handles - make arrays, fill them out resultsCommunities = new Community[numCommunities]; resultsCollections = new Collection[numCollections]; resultsItems = new Item[numItems]; for (int i = 0; i < numItems; i++) { String myhandle = itemHandles.get(i); Object o = HandleManager.resolveToObject(context, myhandle); resultsItems[i] = (Item) o; if (resultsItems[i] == null) { throw new SQLException("Query \"" + query + "\" returned unresolvable handle: " + myhandle); } } for (int i = 0; i < collectionHandles.size(); i++) { String myhandle = collectionHandles.get(i); Object o = HandleManager.resolveToObject(context, myhandle); resultsCollections[i] = (Collection) o; if (resultsCollections[i] == null) { throw new SQLException("Query \"" + query + "\" returned unresolvable handle: " + myhandle); } } for (int i = 0; i < communityHandles.size(); i++) { String myhandle = communityHandles.get(i); Object o = HandleManager.resolveToObject(context, myhandle); resultsCommunities[i] = (Community) o; if (resultsCommunities[i] == null) { throw new SQLException("Query \"" + query + "\" returned unresolvable handle: " + myhandle); } } // Log log.info(LogManager.getHeader(context, "search", logInfo + "query=\"" + query + "\",results=(" + resultsCommunities.length + "," + resultsCollections.length + "," + resultsItems.length + ")")); // Pass in some page qualities // total number of pages int pageTotal = 1 + ((qResults.getHitCount() - 1) / qResults .getPageSize()); // current page being displayed int pageCurrent = 1 + (qResults.getStart() / qResults.getPageSize()); // pageLast = min(pageCurrent+9,pageTotal) int pageLast = ((pageCurrent + 9) > pageTotal) ? pageTotal : (pageCurrent + 9); // pageFirst = max(1,pageCurrent-9) int pageFirst = ((pageCurrent - 9) > 1) ? (pageCurrent - 9) : 1; // Pass the results to the display JSP request.setAttribute("items", resultsItems); request.setAttribute("communities", resultsCommunities); request.setAttribute("collections", resultsCollections); request.setAttribute("pagetotal", Integer.valueOf(pageTotal)); request.setAttribute("pagecurrent", Integer.valueOf(pageCurrent)); request.setAttribute("pagelast", Integer.valueOf(pageLast)); request.setAttribute("pagefirst", Integer.valueOf(pageFirst)); request.setAttribute("queryresults", qResults); // And the original query string request.setAttribute("query", query); } /** * Joins each element present in a list with a separator * * @param list * The list of elements * @param separator * The separator that will be used between each element * @return A string with all the elements concatened and separated by the * provided connector */ public static String join(List<String> list, String separator) { StringBuilder result = new StringBuilder(); for (String entry : list) { if (result.length() > 0) { result.append(separator); } result.append(entry); } return result.toString(); } /** * Handle posts */ protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { doDSGet(context, request, response); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.TransformerException; import org.w3c.dom.Document; import org.apache.log4j.Logger; import org.dspace.app.util.OpenSearch; import org.dspace.app.util.SyndicationFeed; import org.dspace.app.util.Util; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DSpaceObject; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.handle.HandleManager; import org.dspace.search.DSQuery; import org.dspace.search.QueryArgs; import org.dspace.search.QueryResults; import org.dspace.sort.SortOption; /** * Servlet for producing OpenSearch-compliant search results, and the * OpenSearch description document. * <p> * OpenSearch is a specification for describing and advertising search-engines * and their result formats. Commonly, RSS and Atom formats are used, which * the current implementation supports, as is HTML (used directly in browsers). * NB: this is baseline OpenSearch, no extensions currently supported. * </p> * <p> * The value of the "scope" parameter should be absent (which means no * scope restriction), or the handle of a community or collection, otherwise * parameters exactly match those of the SearchServlet. * </p> * * @author Richard Rodgers * */ public class OpenSearchServlet extends DSpaceServlet { private static final long serialVersionUID = 1L; private static String msgKey = "org.dspace.app.webui.servlet.FeedServlet"; /** log4j category */ private static Logger log = Logger.getLogger(OpenSearchServlet.class); // locale-sensitive metadata labels private Map<String, Map<String, String>> localeLabels = null; public void init() { localeLabels = new HashMap<String, Map<String, String>>(); } protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // dispense with simple service document requests String scope = request.getParameter("scope"); if (scope !=null && "".equals(scope)) { scope = null; } String path = request.getPathInfo(); if (path != null && path.endsWith("description.xml")) { String svcDescrip = OpenSearch.getDescription(scope); response.setContentType(OpenSearch.getContentType("opensearchdescription")); response.setContentLength(svcDescrip.length()); response.getWriter().write(svcDescrip); return; } // get enough request parameters to decide on action to take String format = request.getParameter("format"); if (format == null || "".equals(format)) { // default to atom format = "atom"; } // do some sanity checking if (! OpenSearch.getFormats().contains(format)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } // then the rest - we are processing the query String query = request.getParameter("query"); int start = Util.getIntParameter(request, "start"); int rpp = Util.getIntParameter(request, "rpp"); int sort = Util.getIntParameter(request, "sort_by"); String order = request.getParameter("order"); String sortOrder = (order == null || order.length() == 0 || order.toLowerCase().startsWith("asc")) ? SortOption.ASCENDING : SortOption.DESCENDING; QueryArgs qArgs = new QueryArgs(); // can't start earlier than 0 in the results! if (start < 0) { start = 0; } qArgs.setStart(start); if (rpp > 0) { qArgs.setPageSize(rpp); } qArgs.setSortOrder(sortOrder); if (sort > 0) { try { qArgs.setSortOption(SortOption.getSortOption(sort)); } catch(Exception e) { // invalid sort id - do nothing } } qArgs.setSortOrder(sortOrder); // Ensure the query is non-null if (query == null) { query = ""; } // If there is a scope parameter, attempt to dereference it // failure will only result in its being ignored DSpaceObject container = (scope != null) ? HandleManager.resolveToObject(context, scope) : null; // Build log information String logInfo = ""; // get the start of the query results page qArgs.setQuery(query); // Perform the search QueryResults qResults = null; if (container == null) { qResults = DSQuery.doQuery(context, qArgs); } else if (container instanceof Collection) { logInfo = "collection_id=" + container.getID() + ","; qResults = DSQuery.doQuery(context, qArgs, (Collection)container); } else if (container instanceof Community) { logInfo = "community_id=" + container.getID() + ","; qResults = DSQuery.doQuery(context, qArgs, (Community)container); } else { throw new IllegalStateException("Invalid container for search context"); } // now instantiate the results DSpaceObject[] results = new DSpaceObject[qResults.getHitHandles().size()]; for (int i = 0; i < qResults.getHitHandles().size(); i++) { String myHandle = qResults.getHitHandles().get(i); DSpaceObject dso = HandleManager.resolveToObject(context, myHandle); if (dso == null) { throw new SQLException("Query \"" + query + "\" returned unresolvable handle: " + myHandle); } results[i] = dso; } // Log log.info(LogManager.getHeader(context, "search", logInfo + "query=\"" + query + "\",results=(" + results.length + ")")); // format and return results Map<String, String> labelMap = getLabels(request); Document resultsDoc = OpenSearch.getResultsDoc(format, query, qResults, container, results, labelMap); try { Transformer xf = TransformerFactory.newInstance().newTransformer(); response.setContentType(OpenSearch.getContentType(format)); xf.transform(new DOMSource(resultsDoc), new StreamResult(response.getWriter())); } catch (TransformerException e) { log.error(e); throw new ServletException(e.toString(), e); } } private Map<String, String> getLabels(HttpServletRequest request) { // Get access to the localized resource bundle Locale locale = request.getLocale(); Map<String, String> labelMap = localeLabels.get(locale.toString()); if (labelMap == null) { labelMap = getLocaleLabels(locale); localeLabels.put(locale.toString(), labelMap); } return labelMap; } private Map<String, String> getLocaleLabels(Locale locale) { Map<String, String> labelMap = new HashMap<String, String>(); ResourceBundle labels = ResourceBundle.getBundle("Messages", locale); labelMap.put(SyndicationFeed.MSG_UNTITLED, labels.getString(msgKey + ".notitle")); labelMap.put(SyndicationFeed.MSG_LOGO_TITLE, labels.getString(msgKey + ".logo.title")); labelMap.put(SyndicationFeed.MSG_FEED_DESCRIPTION, labels.getString(msgKey + ".general-feed.description")); labelMap.put(SyndicationFeed.MSG_UITYPE, SyndicationFeed.UITYPE_JSPUI); for (String selector : SyndicationFeed.getDescriptionSelectors()) { labelMap.put("metadata." + selector, labels.getString(SyndicationFeed.MSG_METADATA + selector)); } return labelMap; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.content.Bitstream; import org.dspace.content.Bundle; import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.core.Utils; import org.dspace.usage.UsageEvent; import org.dspace.utils.DSpace; /** * Servlet for retrieving bitstreams. The bits are simply piped to the user. * <P> * <code>/retrieve/bitstream-id</code> * * @author Robert Tansley * @version $Revision: 5845 $ */ public class RetrieveServlet extends DSpaceServlet { /** log4j category */ private static Logger log = Logger.getLogger(RetrieveServlet.class); /** * Threshold on Bitstream size before content-disposition will be set. */ private int threshold; @Override public void init(ServletConfig arg0) throws ServletException { super.init(arg0); threshold = ConfigurationManager .getIntProperty("webui.content_disposition_threshold"); } protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { Bitstream bitstream = null; boolean displayLicense = ConfigurationManager.getBooleanProperty("webui.licence_bundle.show", false); boolean isLicense = false; // Get the ID from the URL String idString = request.getPathInfo(); if (idString != null) { // Remove leading slash if (idString.startsWith("/")) { idString = idString.substring(1); } // If there's a second slash, remove it and anything after it, // it might be a filename int slashIndex = idString.indexOf('/'); if (slashIndex != -1) { idString = idString.substring(0, slashIndex); } // Find the corresponding bitstream try { int id = Integer.parseInt(idString); bitstream = Bitstream.find(context, id); } catch (NumberFormatException nfe) { // Invalid ID - this will be dealt with below } } // Did we get a bitstream? if (bitstream != null) { // Check whether we got a License and if it should be displayed // (Note: list of bundles may be empty array, if a bitstream is a Community/Collection logo) Bundle bundle = bitstream.getBundles().length>0 ? bitstream.getBundles()[0] : null; if (bundle!=null && bundle.getName().equals(Constants.LICENSE_BUNDLE_NAME) && bitstream.getName().equals(Constants.LICENSE_BITSTREAM_NAME)) { isLicense = true; } if (isLicense && !displayLicense && !AuthorizeManager.isAdmin(context)) { throw new AuthorizeException(); } log.info(LogManager.getHeader(context, "view_bitstream", "bitstream_id=" + bitstream.getID())); new DSpace().getEventService().fireEvent( new UsageEvent( UsageEvent.Action.VIEW, request, context, bitstream)); //UsageEvent ue = new UsageEvent(); // ue.fire(request, context, AbstractUsageEvent.VIEW, //Constants.BITSTREAM, bitstream.getID()); // Pipe the bits InputStream is = bitstream.retrieve(); // Set the response MIME type response.setContentType(bitstream.getFormat().getMIMEType()); // Response length response.setHeader("Content-Length", String.valueOf(bitstream .getSize())); if(threshold != -1 && bitstream.getSize() >= threshold) { UIUtil.setBitstreamDisposition(bitstream.getName(), request, response); } Utils.bufferedCopy(is, response.getOutputStream()); is.close(); response.getOutputStream().flush(); } else { // No bitstream - we got an invalid ID log.info(LogManager.getHeader(context, "view_bitstream", "invalid_bitstream_id=" + idString)); JSPManager.showInvalidIDError(request, response, idString, Constants.BITSTREAM); } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.Authenticate; import org.dspace.app.webui.util.JSPManager; import org.dspace.authorize.AuthorizeException; import org.dspace.core.Context; import org.dspace.core.LogManager; /** * Servlet that logs out any current user if invoked. * * @author Robert Tansley * @version $Revision: 5845 $ */ public class LogoutServlet extends DSpaceServlet { /** log4j logger */ private static Logger log = Logger.getLogger(LogoutServlet.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { log.info(LogManager.getHeader(context, "logout", "")); Authenticate.loggedOut(context, request); // Display logged out message JSPManager.showJSP(request, response, "/login/logged-out.jsp"); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dspace.authorize.AuthorizeException; import org.dspace.core.Context; /** * Servlet that handles the controlled vocabulary * * @author Miguel Ferreira * @version $Revision: 5845 $ */ public class ControlledVocabularyServlet extends DSpaceServlet { // private static Logger log = // Logger.getLogger(ControlledVocabularyServlet.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String ID = ""; String filter = ""; String callerUrl = request.getParameter("callerUrl"); if (request.getParameter("ID") != null) { ID = request.getParameter("ID"); } if (request.getParameter("filter") != null) { filter = request.getParameter("filter"); } request.getSession() .setAttribute("controlledvocabulary.filter", filter); request.getSession().setAttribute("controlledvocabulary.ID", ID); response.sendRedirect(callerUrl); } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { doDSGet(context, request, response); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.app.bulkedit.MetadataExport; import org.dspace.app.bulkedit.DSpaceCSV; import org.dspace.authorize.AuthorizeException; import org.dspace.browse.*; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.content.ItemIterator; import org.apache.log4j.Logger; /** * Servlet for browsing through indices, as they are defined in * the configuration. This class can take a wide variety of inputs from * the user interface: * * - type: the type of browse (index name) being performed * - order: (ASC | DESC) the direction for result sorting * - value: A specific value to find items around. For example the author name or subject * - month: integer specification of the month of a date browse * - year: integer specification of the year of a date browse * - starts_with: string value at which to start browsing * - vfocus: start browsing with a value of this string * - focus: integer id of the item at which to start browsing * - rpp: integer number of results per page to display * - sort_by: integer specification of the field to search on * - etal: integer number to limit multiple value items specified in config to * * @author Richard Jones * @version $Revision: 6164 $ */ public class BrowserServlet extends AbstractBrowserServlet { /** log4j category */ private static Logger log = Logger.getLogger(AbstractBrowserServlet.class); /** * Do the usual DSpace GET method. You will notice that browse does not currently * respond to POST requests. */ @Override protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // all browse requests currently come to GET. BrowserScope scope = getBrowserScopeForRequest(context, request, response); if (scope.getBrowseIndex() == null) { throw new ServletException("There is no browse index for the request"); } // Is this a request to export the metadata, or a normal browse request? if ("submit_export_metadata".equals(UIUtil.getSubmitButton(request, "submit"))) { exportMetadata(context, request, response, scope); } else { // execute browse request processBrowse(context, scope, request, response); } } /** * Display the error page * * @param context * @param request * @param response * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ @Override protected void showError(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { JSPManager.showInternalError(request, response); } /** * Display the No Results page * * @param context * @param request * @param response * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ @Override protected void showNoResultsPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { JSPManager.showJSP(request, response, "/browse/no-results.jsp"); } /** * Display the single page. This is the page which lists just the single values of a * metadata browse, not individual items. Single values are links through to all the items * that match that metadata value * * @param context * @param request * @param response * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ @Override protected void showSinglePage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { JSPManager.showJSP(request, response, "/browse/single.jsp"); } /** * Display a full item listing. * * @param context * @param request * @param response * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ @Override protected void showFullPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { JSPManager.showJSP(request, response, "/browse/full.jsp"); } /** * Export the metadata from a browse * * @param context The DSpace context * @param request The request object * @param response The response object * @param scope The browse scope * @throws IOException * @throws ServletException */ protected void exportMetadata(Context context, HttpServletRequest request, HttpServletResponse response, BrowserScope scope) throws IOException, ServletException { try { // Log the attempt log.info(LogManager.getHeader(context, "metadataexport", "exporting_browse")); // Ensure we export all results scope.setOffset(0); scope.setResultsPerPage(Integer.MAX_VALUE); // Export a browse view BrowseEngine be = new BrowseEngine(context); BrowseInfo binfo = be.browse(scope); List<Integer> iids = new ArrayList<Integer>(); for (BrowseItem bi : binfo.getBrowseItemResults()) { iids.add(bi.getID()); } ItemIterator ii = new ItemIterator(context, iids); MetadataExport exporter = new MetadataExport(context, ii, false); // Perform the export DSpaceCSV csv = exporter.export(); // Return the csv file response.setContentType("text/csv; charset=UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=browse-result.csv"); PrintWriter out = response.getWriter(); out.write(csv.toString()); out.flush(); out.close(); log.info(LogManager.getHeader(context, "metadataexport", "exported_file:browse-results.csv")); return; } catch (BrowseException be) { // Not sure what happended here! JSPManager.showIntegrityError(request, response); } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException; import org.apache.log4j.Logger; import org.dspace.app.util.SubmissionInfo; import org.dspace.app.util.SubmissionStepConfig; import org.dspace.app.webui.submit.JSPStepManager; import org.dspace.app.webui.util.FileUploadRequest; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Bitstream; import org.dspace.content.Bundle; import org.dspace.content.WorkspaceItem; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.workflow.WorkflowItem; import org.dspace.submit.AbstractProcessingStep; /** * Submission Manager servlet for DSpace. Handles the initial submission of * items, as well as the editing of items further down the line. * <p> * Whenever the submit servlet receives a GET request, this is taken to indicate * the start of a fresh new submission, where no collection has been selected, * and the submission process is started from scratch. * <p> * All other interactions happen via POSTs. Part of the post will normally be a * (hidden) "step" parameter, which will correspond to the form that the user * has just filled out. If this is absent, step 0 (select collection) is * assumed, meaning that it's simple to place "Submit to this collection" * buttons on collection home pages. * <p> * According to the step number of the incoming form, the values posted from the * form are processed (using the process* methods), and the item updated as * appropriate. The servlet then forwards control of the request to the * appropriate JSP (from jsp/submit) to render the next stage of the process or * an error if appropriate. Each of these JSPs may require that attributes be * passed in. Check the comments at the top of a JSP to see which attributes are * needed. All submit-related forms require a properly initialised * SubmissionInfo object to be present in the the "submission.info" attribute. * This holds the core information relevant to the submission, e.g. the item, * personal workspace or workflow item, the submitting "e-person", and the * target collection. * <p> * When control of the request reaches a JSP, it is assumed that all checks, * interactions with the database and so on have been performed and that all * necessary information to render the form is in memory. e.g. The * SubmitFormInfo object passed in must be correctly filled out. Thus the JSPs * do no error or integrity checking; it is the servlet's responsibility to * ensure that everything is prepared. The servlet is fairly diligent about * ensuring integrity at each step. * <p> * Each step has an integer constant defined below. The main sequence of the * submission procedure always runs from 0 upwards, until SUBMISSION_COMPLETE. * Other, not-in-sequence steps (such as the cancellation screen and the * "previous version ID verification" screen) have numbers much higher than * SUBMISSION_COMPLETE. These conventions allow the progress bar component of * the submission forms to render the user's progress through the process. * * @see org.dspace.app.util.SubmissionInfo * @see org.dspace.app.util.SubmissionConfig * @see org.dspace.app.util.SubmissionStepConfig * @see org.dspace.app.webui.submit.JSPStepManager * * @author Tim Donohue * @version $Revision: 6158 $ */ public class SubmissionController extends DSpaceServlet { // Steps in the submission process /** Selection collection step */ public static final int SELECT_COLLECTION = 0; /** First step after "select collection" */ public static final int FIRST_STEP = 1; /** For workflows, first step is step #0 (since Select Collection is already filtered out) */ public static final int WORKFLOW_FIRST_STEP = 0; /** path to the JSP shown once the submission is completed */ private static final String COMPLETE_JSP = "/submit/complete.jsp"; /** log4j logger */ private static Logger log = Logger .getLogger(SubmissionController.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { /* * Possible GET parameters: * * resume= <workspace_item_id> - Resumes submitting the given workspace * item * * workflow= <workflow_id> - Starts editing the given workflow item in * workflow mode * * With no parameters, doDSGet() just calls doDSPost(), which continues * the current submission (if one exists in the Request), or creates a * new submission (if no existing submission can be found). */ // try to get a workspace ID or workflow ID String workspaceID = request.getParameter("resume"); String workflowID = request.getParameter("workflow"); // If resuming a workspace item if (workspaceID != null) { try { // load the workspace item WorkspaceItem wi = WorkspaceItem.find(context, Integer .parseInt(workspaceID)); //load submission information SubmissionInfo si = SubmissionInfo.load(request, wi); //TD: Special case - If a user is resuming a submission //where the submission process now has less steps, then //we will need to reset the stepReached in the database //(Hopefully this will never happen, but just in case!) if(getStepReached(si) >= si.getSubmissionConfig().getNumberOfSteps()) { //update Stage Reached to the last step in the Process int lastStep = si.getSubmissionConfig().getNumberOfSteps()-1; wi.setStageReached(lastStep); //flag that user is on last page of last step wi.setPageReached(AbstractProcessingStep.LAST_PAGE_REACHED); //commit all changes to database immediately wi.update(); context.commit(); //update submission info si.setSubmissionItem(wi); } // start over at beginning of first step setBeginningOfStep(request, true); doStep(context, request, response, si, FIRST_STEP); } catch (NumberFormatException nfe) { log.warn(LogManager.getHeader(context, "bad_workspace_id", "bad_id=" + workspaceID)); JSPManager.showInvalidIDError(request, response, workspaceID, -1); } } else if (workflowID != null) // if resuming a workflow item { try { // load the workflow item WorkflowItem wi = WorkflowItem.find(context, Integer .parseInt(workflowID)); //load submission information SubmissionInfo si = SubmissionInfo.load(request, wi); // start over at beginning of first workflow step setBeginningOfStep(request, true); doStep(context, request, response, si, WORKFLOW_FIRST_STEP); } catch (NumberFormatException nfe) { log.warn(LogManager.getHeader(context, "bad_workflow_id", "bad_id=" + workflowID)); JSPManager .showInvalidIDError(request, response, workflowID, -1); } } else { // otherwise, forward to doDSPost() to do usual processing doDSPost(context, request, response); } } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Configuration of current step in Item Submission Process SubmissionStepConfig currentStepConfig; //need to find out what type of form we are dealing with String contentType = request.getContentType(); // if multipart form, we have to wrap the multipart request // in order to be able to retrieve request parameters, etc. if ((contentType != null) && (contentType.indexOf("multipart/form-data") != -1)) { try { request = wrapMultipartRequest(request); } catch (FileSizeLimitExceededException e) { log.warn("Upload exceeded upload.max"); JSPManager.showFileSizeLimitExceededError(request, response, e.getMessage(), e.getActualSize(), e.getPermittedSize()); } //also, upload any files and save their contents to Request (for later processing by UploadStep) uploadFiles(context, request); } // Reload submission info from request parameters SubmissionInfo subInfo = getSubmissionInfo(context, request); // a submission info object is necessary to continue if (subInfo == null) { // Work around for problem where people select "is a thesis", see // the error page, and then use their "back" button thinking they // can start another submission - it's been removed so the ID in the // form is invalid. If we detect the "removed_thesis" attribute we // display a friendly message instead of an integrity error. if (request.getSession().getAttribute("removed_thesis") != null) { request.getSession().removeAttribute("removed_thesis"); JSPManager.showJSP(request, response, "/submit/thesis-removed-workaround.jsp"); return; } else { // If the submission info was invalid, throw an integrity error log.warn(LogManager.getHeader(context, "integrity_error", UIUtil.getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } } // First, check for a click on "Cancel/Save" button. if (UIUtil.getSubmitButton(request, "").equals(AbstractProcessingStep.CANCEL_BUTTON)) { // Get the current step currentStepConfig = getCurrentStepConfig(request, subInfo); // forward user to JSP which will confirm // the cancel/save request. doCancelOrSave(context, request, response, subInfo, currentStepConfig); } // Special case - no InProgressSubmission yet // If no submission, we assume we will be going // to the "select collection" step. else if (subInfo.getSubmissionItem() == null) { // we have just started this submission // (or we have just resumed a saved submission) // do the "Select Collection" step doStep(context, request, response, subInfo, SELECT_COLLECTION); } else // otherwise, figure out the next Step to call! { // Get the current step currentStepConfig = getCurrentStepConfig(request, subInfo); //if user already confirmed the cancel/save request if (UIUtil.getBoolParameter(request, "cancellation")) { // user came from the cancel/save page, // so we need to process that page before proceeding processCancelOrSave(context, request, response, subInfo, currentStepConfig); } //check for click on "<- Previous" button else if (UIUtil.getSubmitButton(request, "").startsWith( AbstractProcessingStep.PREVIOUS_BUTTON)) { // return to the previous step doPreviousStep(context, request, response, subInfo, currentStepConfig); } //check for click on Progress Bar else if (UIUtil.getSubmitButton(request, "").startsWith( AbstractProcessingStep.PROGRESS_BAR_PREFIX)) { // jumping to a particular step/page doStepJump(context, request, response, subInfo, currentStepConfig); } else { // by default, load step class to start // or continue its processing doStep(context, request, response, subInfo, currentStepConfig.getStepNumber()); } } } /** * Forward processing to the specified step. * * @param context * DSpace context * @param request * the request object * @param response * the response object * @param subInfo * SubmissionInfo pertaining to this submission * @param stepNumber * The number of the step to perform */ private void doStep(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo, int stepNumber) throws ServletException, IOException, SQLException, AuthorizeException { SubmissionStepConfig currentStepConfig = null; if (subInfo.getSubmissionConfig() != null) { // get step to perform currentStepConfig = subInfo.getSubmissionConfig().getStep(stepNumber); } else { log.fatal(LogManager.getHeader(context, "no_submission_process", "trying to load step=" + stepNumber + ", but submission process is null")); JSPManager.showInternalError(request, response); } // if this is the furthest step the user has been to, save that info if (!subInfo.isInWorkflow() && (currentStepConfig.getStepNumber() > getStepReached(subInfo))) { // update submission info userHasReached(subInfo, currentStepConfig.getStepNumber()); // commit changes to database context.commit(); // flag that we just started this step (for JSPStepManager class) setBeginningOfStep(request, true); } // save current step to request attribute saveCurrentStepConfig(request, currentStepConfig); log.debug("Calling Step Class: '" + currentStepConfig.getProcessingClassName() + "'"); try { JSPStepManager stepManager = JSPStepManager.loadStep(currentStepConfig); //tell the step class to do its processing boolean stepFinished = stepManager.processStep(context, request, response, subInfo); //if this step is finished, continue to next step if(stepFinished) { // If we finished up an upload, then we need to change // the FileUploadRequest object back to a normal HTTPServletRequest if(request instanceof FileUploadRequest) { request = ((FileUploadRequest)request).getOriginalRequest(); } //retrieve any changes to the SubmissionInfo object subInfo = getSubmissionInfo(context, request); //do the next step! doNextStep(context, request, response, subInfo, currentStepConfig); } else { //commit & close context context.complete(); } } catch (Exception e) { log.error("Error loading step class'" + currentStepConfig.getProcessingClassName() + "':", e); JSPManager.showInternalError(request, response); } } /** * Forward processing to the next step. * * @param context * DSpace context * @param request * the request object * @param response * the response object * @param subInfo * SubmissionInfo pertaining to this submission */ private void doNextStep(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo, SubmissionStepConfig currentStepConfig) throws ServletException, IOException, SQLException, AuthorizeException { // find current Step number int currentStepNum; if (currentStepConfig == null) { currentStepNum = -1; } else { currentStepNum = currentStepConfig.getStepNumber(); } // as long as there are more steps after the current step, // do the next step in the current Submission Process if (subInfo.getSubmissionConfig().hasMoreSteps(currentStepNum)) { // update the current step & do this step currentStepNum++; //flag that we are going to the start of this next step (for JSPStepManager class) setBeginningOfStep(request, true); doStep(context, request, response, subInfo, currentStepNum); } else { //if this submission is in the workflow process, //forward user back to relevant task page if(subInfo.isInWorkflow()) { request.setAttribute("workflow.item", subInfo.getSubmissionItem()); JSPManager.showJSP(request, response, "/mydspace/perform-task.jsp"); } else { // The Submission is COMPLETE!! // save our current Submission information into the Request object saveSubmissionInfo(request, subInfo); // forward to completion JSP showProgressAwareJSP(request, response, subInfo, COMPLETE_JSP); } } } /** * Forward processing to the previous step. This method is called if it is * determined that the "previous" button was pressed. * * @param context * DSpace context * @param request * the request object * @param response * the response object * @param subInfo * SubmissionInfo pertaining to this submission */ private void doPreviousStep(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo, SubmissionStepConfig currentStepConfig) throws ServletException, IOException, SQLException, AuthorizeException { int result = doSaveCurrentState(context, request, response, subInfo, currentStepConfig); // find current Step number int currentStepNum; if (currentStepConfig == null) { currentStepNum = -1; } else { currentStepNum = currentStepConfig.getStepNumber(); } int currPage=AbstractProcessingStep.getCurrentPage(request); double currStepAndPage = Double.parseDouble(currentStepNum+"."+currPage); // default value if we are in workflow double stepAndPageReached = -1; if (!subInfo.isInWorkflow()) { stepAndPageReached = Float.parseFloat(getStepReached(subInfo)+"."+JSPStepManager.getPageReached(subInfo)); } if (result != AbstractProcessingStep.STATUS_COMPLETE && currStepAndPage != stepAndPageReached) { doStep(context, request, response, subInfo, currentStepNum); } //Check to see if we are actually just going to a //previous PAGE within the same step. int currentPageNum = AbstractProcessingStep.getCurrentPage(request); boolean foundPrevious = false; //since there are pages before this one in this current step //just go backwards one page. if(currentPageNum > 1) { //decrease current page number AbstractProcessingStep.setCurrentPage(request, currentPageNum-1); foundPrevious = true; //send user back to the beginning of same step! //NOTE: the step should handle going back one page // in its doPreProcessing() method setBeginningOfStep(request, true); doStep(context, request, response, subInfo, currentStepNum); } // Since we cannot go back one page, // check if there is a step before this step. // If so, go backwards one step else if (currentStepNum > FIRST_STEP) { currentStepConfig = getPreviousVisibleStep(request, subInfo); if(currentStepConfig != null) { currentStepNum = currentStepConfig.getStepNumber(); foundPrevious = true; } if(foundPrevious) { //flag to JSPStepManager that we are going backwards //an entire step request.setAttribute("step.backwards", Boolean.TRUE); // flag that we are going back to the start of this step (for JSPStepManager class) setBeginningOfStep(request, true); doStep(context, request, response, subInfo, currentStepNum); } } //if there is no previous, visible step, throw an error! if(!foundPrevious) { log.error(LogManager .getHeader(context, "no_previous_visible_step", "Attempting to go to previous step for step=" + currentStepNum + "." + "NO PREVIOUS VISIBLE STEP OR PAGE FOUND!")); JSPManager.showIntegrityError(request, response); } } /** * Process a click on a button in the progress bar. This jumps to the step * whose button was pressed. * * @param context * DSpace context object * @param request * the request object * @param response * the response object * @param subInfo * SubmissionInfo pertaining to this submission */ private void doStepJump(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo, SubmissionStepConfig currentStepConfig) throws ServletException, IOException, SQLException, AuthorizeException { // Find the button that was pressed. It would start with // "submit_jump_". String buttonPressed = UIUtil.getSubmitButton(request, ""); int nextStep = -1; // next step to load int nextPage = -1; // page within the nextStep to load if (buttonPressed.startsWith("submit_jump_")) { // Button on progress bar pressed try { // get step & page info (in form: stepNum.pageNum) after // "submit_jump_" String stepAndPage = buttonPressed.substring(12); // split into stepNum and pageNum String[] fields = stepAndPage.split("\\."); // split on period nextStep = Integer.parseInt(fields[0]); nextPage = Integer.parseInt(fields[1]); } catch (NumberFormatException ne) { // mangled number nextStep = -1; nextPage = -1; } // Integrity check: make sure they aren't going // forward or backward too far if ((!subInfo.isInWorkflow() && nextStep < FIRST_STEP) || (subInfo.isInWorkflow() && nextStep < WORKFLOW_FIRST_STEP)) { nextStep = -1; nextPage = -1; } // if trying to jump to a step you haven't been to yet if (!subInfo.isInWorkflow() && (nextStep > getStepReached(subInfo))) { nextStep = -1; } } if (nextStep == -1) { // Either no button pressed, or an illegal stage // reached. UI doesn't allow this, so something's // wrong if that happens. log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); } else { int result = doSaveCurrentState(context, request, response, subInfo, currentStepConfig); // Now, if the request was a multi-part (file upload), we need to // get the original request back out, as the wrapper causes problems // further down the line. if (request instanceof FileUploadRequest) { FileUploadRequest fur = (FileUploadRequest) request; request = fur.getOriginalRequest(); } int currStep = currentStepConfig.getStepNumber(); int currPage = AbstractProcessingStep.getCurrentPage(request); double currStepAndPage = Float .parseFloat(currStep + "." + currPage); // default value if we are in workflow double stepAndPageReached = -1; if (!subInfo.isInWorkflow()) { stepAndPageReached = Float.parseFloat(getStepReached(subInfo)+"."+JSPStepManager.getPageReached(subInfo)); } if (result != AbstractProcessingStep.STATUS_COMPLETE && currStepAndPage != stepAndPageReached) { doStep(context, request, response, subInfo, currStep); } else { // save page info to request (for the step to access) AbstractProcessingStep.setCurrentPage(request, nextPage); // flag that we are going back to the start of this step (for // JSPStepManager class) setBeginningOfStep(request, true); log.debug("Jumping to Step " + nextStep + " and Page " + nextPage); // do the step (the step should take care of going to // the specified page) doStep(context, request, response, subInfo, nextStep); } } } /** * Respond to the user clicking "cancel/save" * from any of the steps. This method first calls * the "doPostProcessing()" method of the step, in * order to ensure any inputs are saved. * * @param context * DSpace context * @param request * current servlet request object * @param response * current servlet response object * @param subInfo * SubmissionInfo object * @param stepConfig * config of step who's page the user clicked "cancel" on. */ private void doCancelOrSave(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo, SubmissionStepConfig stepConfig) throws ServletException, IOException, SQLException, AuthorizeException { // If this is a workflow item, we need to return the // user to the "perform task" page if (subInfo.isInWorkflow()) { int result = doSaveCurrentState(context, request, response, subInfo, stepConfig); if (result == AbstractProcessingStep.STATUS_COMPLETE) { request.setAttribute("workflow.item", subInfo.getSubmissionItem()); JSPManager.showJSP(request, response, "/mydspace/perform-task.jsp"); } else { int currStep=stepConfig.getStepNumber(); doStep(context, request, response, subInfo, currStep); } } else { // if no submission has been started, if (subInfo.getSubmissionItem() == null) { // forward them to the 'cancelled' page, // since we haven't created an item yet. JSPManager.showJSP(request, response, "/submit/cancelled-removed.jsp"); } else { //tell the step class to do its processing (to save any inputs) //but, send flag that this is a "cancellation" setCancellationInProgress(request, true); int result = doSaveCurrentState(context, request, response, subInfo, stepConfig); int currStep=stepConfig.getStepNumber(); int currPage=AbstractProcessingStep.getCurrentPage(request); double currStepAndPage = Float.parseFloat(currStep+"."+currPage); double stepAndPageReached = Float.parseFloat(getStepReached(subInfo)+"."+JSPStepManager.getPageReached(subInfo)); if (result != AbstractProcessingStep.STATUS_COMPLETE && currStepAndPage < stepAndPageReached){ setReachedStepAndPage(subInfo, currStep, currPage); } //commit & close context context.complete(); // save changes to submission info & step info for JSP saveSubmissionInfo(request, subInfo); saveCurrentStepConfig(request, stepConfig); // forward to cancellation confirmation JSP showProgressAwareJSP(request, response, subInfo, "/submit/cancel.jsp"); } } } private int doSaveCurrentState(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo, SubmissionStepConfig stepConfig) throws ServletException { int result = -1; // As long as we're not uploading a file, go ahead and SAVE // all of the user's inputs for later try { // call post-processing on Step (to save any inputs from JSP) log .debug("Cancel/Save or Jump/Previous Request: calling processing for Step: '" + stepConfig.getProcessingClassName() + "'"); try { // load the step class (using the current class loader) ClassLoader loader = this.getClass().getClassLoader(); Class stepClass = loader.loadClass(stepConfig .getProcessingClassName()); // load the JSPStepManager object for this step AbstractProcessingStep step = (AbstractProcessingStep) stepClass .newInstance(); result = step.doProcessing(context, request, response, subInfo); } catch (Exception e) { log.error("Error loading step class'" + stepConfig.getProcessingClassName() + "':", e); JSPManager.showInternalError(request, response); } } catch(Exception e) { throw new ServletException(e); } return result; } /** * Process information from "submission cancelled" page. * This saves the item if the user decided to "cancel & save", * or removes the item if the user decided to "cancel & remove". * * @param context * current DSpace context * @param request * current servlet request object * @param response * current servlet response object * @param subInfo * submission info object */ private void processCancelOrSave(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo, SubmissionStepConfig currentStepConfig) throws ServletException, IOException, SQLException, AuthorizeException { String buttonPressed = UIUtil.getSubmitButton(request, "submit_back"); if (buttonPressed.equals("submit_back")) { // re-load current step at beginning setBeginningOfStep(request, true); doStep(context, request, response, subInfo, currentStepConfig .getStepNumber()); } else if (buttonPressed.equals("submit_remove")) { // User wants to cancel and remove // Cancellation page only applies to workspace items WorkspaceItem wi = (WorkspaceItem) subInfo.getSubmissionItem(); wi.deleteAll(); JSPManager.showJSP(request, response, "/submit/cancelled-removed.jsp"); context.complete(); } else if (buttonPressed.equals("submit_keep")) { // Save submission for later - just show message JSPManager.showJSP(request, response, "/submit/saved.jsp"); } else { doStepJump(context, request, response, subInfo, currentStepConfig); } } // **************************************************************** // **************************************************************** // MISCELLANEOUS CONVENIENCE METHODS // **************************************************************** // **************************************************************** /** * Show a JSP after setting attributes needed by progress bar * * @param request * the request object * @param response * the response object * @param subInfo * the SubmissionInfo object * @param jspPath * relative path to JSP */ private static void showProgressAwareJSP(HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo, String jspPath) throws ServletException, IOException { saveSubmissionInfo(request, subInfo); JSPManager.showJSP(request, response, jspPath); } /** * Reloads a filled-out submission info object from the parameters in the * current request. If there is a problem, <code>null</code> is returned. * * @param context * DSpace context * @param request * HTTP request * * @return filled-out submission info, or null */ public static SubmissionInfo getSubmissionInfo(Context context, HttpServletRequest request) throws SQLException, ServletException { SubmissionInfo info = null; // Is full Submission Info in Request Attribute? if (request.getAttribute("submission.info") != null) { // load from cache info = (SubmissionInfo) request.getAttribute("submission.info"); } else { // Need to rebuild Submission Info from Request Parameters if (request.getParameter("workflow_id") != null) { int workflowID = UIUtil.getIntParameter(request, "workflow_id"); info = SubmissionInfo.load(request, WorkflowItem.find(context, workflowID)); } else if(request.getParameter("workspace_item_id") != null) { int workspaceID = UIUtil.getIntParameter(request, "workspace_item_id"); info = SubmissionInfo.load(request, WorkspaceItem.find(context, workspaceID)); } else { //by default, initialize Submission Info with no item info = SubmissionInfo.load(request, null); } // We must have a submission object if after the first step, // otherwise something is wrong! if ((getStepReached(info) > FIRST_STEP) && (info.getSubmissionItem() == null)) { log.warn(LogManager.getHeader(context, "cannot_load_submission_info", "InProgressSubmission is null!")); return null; } if (request.getParameter("bundle_id") != null) { int bundleID = UIUtil.getIntParameter(request, "bundle_id"); info.setBundle(Bundle.find(context, bundleID)); } if (request.getParameter("bitstream_id") != null) { int bitstreamID = UIUtil.getIntParameter(request, "bitstream_id"); info.setBitstream(Bitstream.find(context, bitstreamID)); } // save to Request Attribute saveSubmissionInfo(request, info); }// end if unable to load SubInfo from Request Attribute return info; } /** * Saves the submission info object to the current request. * * @param request * HTTP request * @param si * the current submission info * */ public static void saveSubmissionInfo(HttpServletRequest request, SubmissionInfo si) { // save to request request.setAttribute("submission.info", si); } /** * Get the configuration of the current step from parameters in the request, * along with the current SubmissionInfo object. * If there is a problem, <code>null</code> is returned. * * @param request * HTTP request * @param si * The current SubmissionInfo object * * @return the current SubmissionStepConfig */ public static SubmissionStepConfig getCurrentStepConfig( HttpServletRequest request, SubmissionInfo si) { int stepNum = -1; SubmissionStepConfig step = (SubmissionStepConfig) request .getAttribute("step"); if (step == null) { // try and get it as a parameter stepNum = UIUtil.getIntParameter(request, "step"); // if something is wrong, return null if (stepNum < 0 || si == null || si.getSubmissionConfig() == null) { return null; } else { return si.getSubmissionConfig().getStep(stepNum); } } else { return step; } } /** * Saves the current step configuration into the request. * * @param request * HTTP request * @param step * The current SubmissionStepConfig */ public static void saveCurrentStepConfig(HttpServletRequest request, SubmissionStepConfig step) { // save to request request.setAttribute("step", step); } /** * Checks if the current step is also the first "visibile" step in the item submission * process. * * @param request * HTTP request * @param si * The current Submission Info * * @return whether or not the current step is the first step */ public static boolean isFirstStep(HttpServletRequest request, SubmissionInfo si) { SubmissionStepConfig step = getCurrentStepConfig(request, si); return ((step != null) && (getPreviousVisibleStep(request, si) == null)); } /** * Return the previous "visibile" step in the item submission * process if any, <code>null</code> otherwise. * * @param request * HTTP request * @param si * The current Submission Info * * @return the previous step in the item submission process if any */ public static SubmissionStepConfig getPreviousVisibleStep(HttpServletRequest request, SubmissionInfo si) { SubmissionStepConfig step = getCurrentStepConfig(request, si); SubmissionStepConfig currentStepConfig, previousStep = null; int currentStepNum = step.getStepNumber(); //need to find a previous step that is VISIBLE to the user! while(currentStepNum>FIRST_STEP) { // update the current step & do this previous step currentStepNum--; //get previous step currentStepConfig = si.getSubmissionConfig().getStep(currentStepNum); if(currentStepConfig.isVisible()) { previousStep = currentStepConfig; break; } } return previousStep; } /** * Get whether or not the current step has just begun. This helps determine * if we've done any pre-processing yet. If the step is just started, we * need to do pre-processing, otherwise we should be doing post-processing. * If there is a problem, <code>false</code> is returned. * * @param request * HTTP request * * @return true if the step has just started (and JSP has not been loaded * for this step), false otherwise. */ public static boolean isBeginningOfStep(HttpServletRequest request) { Boolean stepStart = (Boolean) request.getAttribute("step.start"); if (stepStart != null) { return stepStart.booleanValue(); } else { return false; } } /** * Get whether or not the current step has just begun. This helps determine * if we've done any pre-processing yet. If the step is just started, we * need to do pre-processing, otherwise we should be doing post-processing. * If there is a problem, <code>false</code> is returned. * * @param request * HTTP request * @param beginningOfStep * true if step just began */ public static void setBeginningOfStep(HttpServletRequest request, boolean beginningOfStep) { request.setAttribute("step.start", Boolean.valueOf(beginningOfStep)); } /** * Get whether or not a cancellation is in progress (i.e. the * user clicked on the "Cancel/Save" button from any submission * page). * * @param request * HTTP request * * @return true if a cancellation is in progress */ public static boolean isCancellationInProgress(HttpServletRequest request) { Boolean cancellation = (Boolean) request.getAttribute("submission.cancellation"); if (cancellation != null) { return cancellation.booleanValue(); } else { return false; } } /** * Sets whether or not a cancellation is in progress (i.e. the * user clicked on the "Cancel/Save" button from any submission * page). * * @param request * HTTP request * @param cancellationInProgress * true if cancellation is in progress */ private static void setCancellationInProgress(HttpServletRequest request, boolean cancellationInProgress) { request.setAttribute("submission.cancellation", Boolean.valueOf(cancellationInProgress)); } /** * Return the submission info as hidden parameters for an HTML form on a JSP * page. * * @param context * DSpace context * @param request * HTTP request * @return HTML hidden parameters */ public static String getSubmissionParameters(Context context, HttpServletRequest request) throws SQLException, ServletException { SubmissionInfo si = getSubmissionInfo(context, request); SubmissionStepConfig step = getCurrentStepConfig(request, si); String info = ""; if ((si.getSubmissionItem() != null) && si.isInWorkflow()) { info = info + "<input type=\"hidden\" name=\"workflow_id\" value=\"" + si.getSubmissionItem().getID() + "\"/>"; } else if (si.getSubmissionItem() != null) { info = info + "<input type=\"hidden\" name=\"workspace_item_id\" value=\"" + si.getSubmissionItem().getID() + "\"/>"; } if (si.getBundle() != null) { info = info + "<input type=\"hidden\" name=\"bundle_id\" value=\"" + si.getBundle().getID() + "\"/>"; } if (si.getBitstream() != null) { info = info + "<input type=\"hidden\" name=\"bitstream_id\" value=\"" + si.getBitstream().getID() + "\"/>"; } if (step != null) { info = info + "<input type=\"hidden\" name=\"step\" value=\"" + step.getStepNumber() + "\"/>"; } // save the current page from the current Step Servlet int page = AbstractProcessingStep.getCurrentPage(request); info = info + "<input type=\"hidden\" name=\"page\" value=\"" + page + "\"/>"; // save the current JSP name to a hidden variable String jspDisplayed = JSPStepManager.getLastJSPDisplayed(request); info = info + "<input type=\"hidden\" name=\"jsp\" value=\"" + jspDisplayed + "\"/>"; return info; } /** * Indicate the user has advanced to the given stage. This will only * actually do anything when it's a user initially entering a submission. It * will only increase the "stage reached" column - it will not "set back" * where a user has reached. Whenever the "stage reached" column is * increased, the "page reached" column is reset to 1, since you've now * reached page #1 of the next stage. * * @param subInfo * the SubmissionInfo object pertaining to the current submission * @param step * the step the user has just reached */ private void userHasReached(SubmissionInfo subInfo, int step) throws SQLException, AuthorizeException, IOException { if (!subInfo.isInWorkflow() && subInfo.getSubmissionItem() != null) { WorkspaceItem wi = (WorkspaceItem) subInfo.getSubmissionItem(); if (step > wi.getStageReached()) { wi.setStageReached(step); wi.setPageReached(1); // reset page reached back to 1 (since // it's page 1 of the new step) wi.update(); } } } /** * Set a specific step and page as reached. * It will also "set back" where a user has reached. * * @param subInfo * the SubmissionInfo object pertaining to the current submission * @param step the step to set as reached, can be also a previous reached step * @param page the page (within the step) to set as reached, can be also a previous reached page */ private void setReachedStepAndPage(SubmissionInfo subInfo, int step, int page) throws SQLException, AuthorizeException, IOException { if (!subInfo.isInWorkflow() && subInfo.getSubmissionItem() != null) { WorkspaceItem wi = (WorkspaceItem) subInfo.getSubmissionItem(); wi.setStageReached(step); wi.setPageReached(page); wi.update(); } } /** * Find out which step a user has reached in the submission process. If the * submission is in the workflow process, this returns -1. * * @param subInfo * submission info object * * @return step reached */ public static int getStepReached(SubmissionInfo subInfo) { if (subInfo == null || subInfo.isInWorkflow() || subInfo.getSubmissionItem() == null) { return -1; } else { WorkspaceItem wi = (WorkspaceItem) subInfo.getSubmissionItem(); int i = wi.getStageReached(); // Uninitialised workspace items give "-1" as the stage reached // this is a special value used by the progress bar, so we change // it to "FIRST_STEP" if (i == -1) { i = FIRST_STEP; } return i; } } /** * Wraps a multipart form request, so that its attributes and parameters can * still be accessed as normal. * * @return wrapped multipart request object * * @throws ServletException * if there are no more pages in this step */ private HttpServletRequest wrapMultipartRequest(HttpServletRequest request) throws ServletException, FileSizeLimitExceededException { HttpServletRequest wrappedRequest; try { // if not already wrapped if (!Class.forName("org.dspace.app.webui.util.FileUploadRequest") .isInstance(request)) { // Wrap multipart request wrappedRequest = new FileUploadRequest(request); return (HttpServletRequest) wrappedRequest; } else { // already wrapped return request; } } catch (FileSizeLimitExceededException e) { throw new FileSizeLimitExceededException(e.getMessage(),e.getActualSize(),e.getPermittedSize()); } catch (Exception e) { throw new ServletException(e); } } /** * Upload any files found on the Request, and save them back as * Request attributes, for further processing by the appropriate user interface. * * @param context * current DSpace context * @param request * current servlet request object */ public void uploadFiles(Context context, HttpServletRequest request) throws ServletException { FileUploadRequest wrapper = null; String filePath = null; InputStream fileInputStream = null; try { // if we already have a FileUploadRequest, use it if (Class.forName("org.dspace.app.webui.util.FileUploadRequest") .isInstance(request)) { wrapper = (FileUploadRequest) request; } else { // Wrap multipart request to get the submission info wrapper = new FileUploadRequest(request); } Enumeration fileParams = wrapper.getFileParameterNames(); while(fileParams.hasMoreElements()) { String fileName = (String) fileParams.nextElement(); File temp = wrapper.getFile(fileName); //if file exists and has a size greater than zero if (temp != null && temp.length() > 0) { // Read the temp file into an inputstream fileInputStream = new BufferedInputStream( new FileInputStream(temp)); filePath = wrapper.getFilesystemName(fileName); // cleanup our temp file if (!temp.delete()) { log.error("Unable to delete temporary file"); } //save this file's info to request (for UploadStep class) request.setAttribute(fileName + "-path", filePath); request.setAttribute(fileName + "-inputstream", fileInputStream); request.setAttribute(fileName + "-description", wrapper.getParameter("description")); } } } catch (Exception e) { // Problem with uploading log.warn(LogManager.getHeader(context, "upload_error", ""), e); throw new ServletException(e); } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.security.cert.X509Certificate; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.Authenticate; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.eperson.EPerson; /** * X509 certificate authentication servlet. This is an * access point for interactive certificate auth that will * not be implicit (i.e. not immediately performed * because the resource is being accessed via HTTP * * @author Robert Tansley * @author Mark Diggory * @version $Revision: 5845 $ */ public class X509CertificateServlet extends DSpaceServlet { /** serialization id */ private static final long serialVersionUID = -3571151231655696793L; /** log4j logger */ private static Logger log = Logger.getLogger(X509CertificateServlet.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Obtain the certificate from the request, if any X509Certificate[] certs = (X509Certificate[]) request .getAttribute("javax.servlet.request.X509Certificate"); if ((certs == null) || (certs.length == 0)) { log.info(LogManager.getHeader(context, "failed_login", "type=x509certificate")); JSPManager.showJSP(request, response, "/login/no-valid-cert.jsp"); } else { Context ctx = UIUtil.obtainContext(request); EPerson eperson = ctx.getCurrentUser(); // Do we have an active e-person now? if ((eperson != null) && eperson.canLogIn()) { // Everything OK - they should have already been logged in. // resume previous request Authenticate.resumeInterruptedRequest(request, response); return; } // If we get to here, no valid cert log.info(LogManager.getHeader(context, "failed_login", "type=x509certificate")); JSPManager.showJSP(request, response, "/login/no-valid-cert.jsp"); } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import java.util.LinkedList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.itemexport.ItemExport; import org.dspace.app.itemexport.ItemExportException; import org.dspace.app.util.SubmissionConfigReader; import org.dspace.app.util.SubmissionConfig; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.Item; import org.dspace.content.ItemIterator; import org.dspace.content.SupervisedItem; import org.dspace.content.WorkspaceItem; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.eperson.EPerson; import org.dspace.eperson.Group; import org.dspace.handle.HandleManager; import org.dspace.submit.AbstractProcessingStep; import org.dspace.workflow.WorkflowItem; import org.dspace.workflow.WorkflowManager; /** * Servlet for constructing the components of the "My DSpace" page * * @author Robert Tansley * @author Jay Paz * @version $Id: MyDSpaceServlet.java 5845 2010-11-12 05:34:07Z mdiggory $ */ public class MyDSpaceServlet extends DSpaceServlet { /** Logger */ private static Logger log = Logger.getLogger(MyDSpaceServlet.class); /** The main screen */ public static final int MAIN_PAGE = 0; /** The remove item page */ public static final int REMOVE_ITEM_PAGE = 1; /** The preview task page */ public static final int PREVIEW_TASK_PAGE = 2; /** The perform task page */ public static final int PERFORM_TASK_PAGE = 3; /** The "reason for rejection" page */ public static final int REJECT_REASON_PAGE = 4; /** The "request export archive for download" page */ public static final int REQUEST_EXPORT_ARCHIVE = 5; /** The "request export migrate archive for download" page */ public static final int REQUEST_MIGRATE_ARCHIVE = 6; protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // GET displays the main page - everthing else is a POST showMainPage(context, request, response); } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // First get the step int step = UIUtil.getIntParameter(request, "step"); switch (step) { case MAIN_PAGE: processMainPage(context, request, response); break; case REMOVE_ITEM_PAGE: processRemoveItem(context, request, response); break; case PREVIEW_TASK_PAGE: processPreviewTask(context, request, response); break; case PERFORM_TASK_PAGE: processPerformTask(context, request, response); break; case REJECT_REASON_PAGE: processRejectReason(context, request, response); break; case REQUEST_EXPORT_ARCHIVE: processExportArchive(context, request, response, false); break; case REQUEST_MIGRATE_ARCHIVE: processExportArchive(context, request, response, true); break; default: log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); } } // **************************************************************** // **************************************************************** // METHODS FOR PROCESSING POSTED FORMS // **************************************************************** // **************************************************************** protected void processMainPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String buttonPressed = UIUtil.getSubmitButton(request, "submit_own"); // Get workspace item, if any WorkspaceItem workspaceItem; try { int wsID = Integer.parseInt(request.getParameter("workspace_id")); workspaceItem = WorkspaceItem.find(context, wsID); } catch (NumberFormatException nfe) { workspaceItem = null; } // Get workflow item specified, if any WorkflowItem workflowItem; try { int wfID = Integer.parseInt(request.getParameter("workflow_id")); workflowItem = WorkflowItem.find(context, wfID); } catch (NumberFormatException nfe) { workflowItem = null; } // Respond to button press boolean ok = false; if (buttonPressed.equals("submit_new")) { // New submission: Redirect to submit response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/submit")); ok = true; } else if (buttonPressed.equals("submit_own")) { // Review own submissions showPreviousSubmissions(context, request, response); ok = true; } else if (buttonPressed.equals("submit_resume")) { // User clicked on a "Resume" button for a workspace item. String wsID = request.getParameter("workspace_id"); response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/submit?resume=" + wsID)); ok = true; } else if (buttonPressed.equals("submit_delete")) { // User clicked on a "Remove" button for a workspace item if (workspaceItem != null) { log.info(LogManager.getHeader(context, "confirm_removal", "workspace_item_id=" + workspaceItem.getID())); request.setAttribute("workspace.item", workspaceItem); JSPManager.showJSP(request, response, "/mydspace/remove-item.jsp"); } else { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil.getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); } ok = true; } else if (buttonPressed.equals("submit_claim")) { // User clicked "take task" button on workflow task if (workflowItem != null) { log.info(LogManager.getHeader(context, "view_workflow", "workflow_id=" + workflowItem.getID())); request.setAttribute("workflow.item", workflowItem); JSPManager.showJSP(request, response, "/mydspace/preview-task.jsp"); ok = true; } } else if (buttonPressed.equals("submit_perform")) { // User clicked "Do This Task" button on workflow task if (workflowItem != null) { log.info(LogManager.getHeader(context, "view_workflow", "workflow_id=" + workflowItem.getID())); request.setAttribute("workflow.item", workflowItem); JSPManager.showJSP(request, response, "/mydspace/perform-task.jsp"); ok = true; } } else if (buttonPressed.equals("submit_return")) { // User clicked "Return to pool" button on workflow task if (workflowItem != null) { log.info(LogManager.getHeader(context, "unclaim_workflow", "workflow_id=" + workflowItem.getID())); WorkflowManager.unclaim(context, workflowItem, context .getCurrentUser()); showMainPage(context, request, response); context.complete(); ok = true; } } if (!ok) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); } } /** * Process input from remove item page * * @param context * current context * @param request * current servlet request object * @param response * current servlet response object */ private void processRemoveItem(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String buttonPressed = UIUtil.getSubmitButton(request, "submit_cancel"); // Get workspace item WorkspaceItem workspaceItem; try { int wsID = Integer.parseInt(request.getParameter("workspace_id")); workspaceItem = WorkspaceItem.find(context, wsID); } catch (NumberFormatException nfe) { workspaceItem = null; } if (workspaceItem == null) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } // We have a workspace item if (buttonPressed.equals("submit_delete")) { // User has clicked on "delete" log.info(LogManager.getHeader(context, "remove_submission", "workspace_item_id=" + workspaceItem.getID() + ",item_id=" + workspaceItem.getItem().getID())); workspaceItem.deleteAll(); showMainPage(context, request, response); context.complete(); } else { // User has cancelled. Back to main page. showMainPage(context, request, response); } } /** * Process input from preview task page * * @param context * current context * @param request * current servlet request object * @param response * current servlet response object */ private void processPreviewTask(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String buttonPressed = UIUtil.getSubmitButton(request, "submit_cancel"); // Get workflow item WorkflowItem workflowItem; try { int wfID = Integer.parseInt(request.getParameter("workflow_id")); workflowItem = WorkflowItem.find(context, wfID); } catch (NumberFormatException nfe) { workflowItem = null; } if (workflowItem == null) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } if (buttonPressed.equals("submit_start")) { // User clicked "start" button to claim the task WorkflowManager.claim(context, workflowItem, context .getCurrentUser()); // Display "perform task" page request.setAttribute("workflow.item", workflowItem); JSPManager.showJSP(request, response, "/mydspace/perform-task.jsp"); context.complete(); } else { // Return them to main page showMainPage(context, request, response); } } /** * Process input from perform task page * * @param context * current context * @param request * current servlet request object * @param response * current servlet response object */ private void processPerformTask(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String buttonPressed = UIUtil.getSubmitButton(request, "submit_cancel"); // Get workflow item WorkflowItem workflowItem; try { int wfID = Integer.parseInt(request.getParameter("workflow_id")); workflowItem = WorkflowItem.find(context, wfID); } catch (NumberFormatException nfe) { workflowItem = null; } if (workflowItem == null) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } if (buttonPressed.equals("submit_approve")) { Item item = workflowItem.getItem(); // Advance the item along the workflow WorkflowManager.advance(context, workflowItem, context .getCurrentUser()); // FIXME: This should be a return value from advance() // See if that gave the item a Handle. If it did, // the item made it into the archive, so we // should display a suitable page. String handle = HandleManager.findHandle(context, item); if (handle != null) { String displayHandle = HandleManager.getCanonicalForm(handle); request.setAttribute("handle", displayHandle); JSPManager.showJSP(request, response, "/mydspace/in-archive.jsp"); } else { JSPManager.showJSP(request, response, "/mydspace/task-complete.jsp"); } context.complete(); } else if (buttonPressed.equals("submit_reject")) { // Submission rejected. Ask the user for a reason log.info(LogManager.getHeader(context, "get_reject_reason", "workflow_id=" + workflowItem.getID() + ",item_id=" + workflowItem.getItem().getID())); request.setAttribute("workflow.item", workflowItem); JSPManager .showJSP(request, response, "/mydspace/reject-reason.jsp"); } else if (buttonPressed.equals("submit_edit")) { // FIXME: Check auth log.info(LogManager.getHeader(context, "edit_workflow_item", "workflow_id=" + workflowItem.getID() + ",item_id=" + workflowItem.getItem().getID())); // Forward control to the submission interface // with the relevant item response.sendRedirect(response.encodeRedirectURL(request .getContextPath() + "/submit?workflow=" + workflowItem.getID())); } else if (buttonPressed.equals("submit_pool")) { // Return task to pool WorkflowManager.unclaim(context, workflowItem, context .getCurrentUser()); showMainPage(context, request, response); context.complete(); } else { // Cancelled. The user hasn't taken the task. // Just return to the main My DSpace page. showMainPage(context, request, response); } } /** * Process input from "reason for rejection" page * * @param context * current context * @param request * current servlet request object * @param response * current servlet response object */ private void processRejectReason(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String buttonPressed = UIUtil.getSubmitButton(request, "submit_cancel"); // Get workflow item WorkflowItem workflowItem; try { int wfID = Integer.parseInt(request.getParameter("workflow_id")); workflowItem = WorkflowItem.find(context, wfID); } catch (NumberFormatException nfe) { workflowItem = null; } if (workflowItem == null) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } if (buttonPressed.equals("submit_send")) { String reason = request.getParameter("reason"); WorkspaceItem wsi = WorkflowManager.reject(context, workflowItem, context.getCurrentUser(), reason); // Load the Submission Process for the collection this WSI is // associated with Collection c = wsi.getCollection(); SubmissionConfigReader subConfigReader = new SubmissionConfigReader(); SubmissionConfig subConfig = subConfigReader.getSubmissionConfig(c .getHandle(), false); // Set the "stage_reached" column on the workspace item // to the LAST page of the LAST step in the submission process // (i.e. the page just before "Complete") int lastStep = subConfig.getNumberOfSteps() - 2; wsi.setStageReached(lastStep); wsi.setPageReached(AbstractProcessingStep.LAST_PAGE_REACHED); wsi.update(); JSPManager .showJSP(request, response, "/mydspace/task-complete.jsp"); context.complete(); } else { request.setAttribute("workflow.item", workflowItem); JSPManager.showJSP(request, response, "/mydspace/perform-task.jsp"); } } private void processExportArchive(Context context, HttpServletRequest request, HttpServletResponse response, boolean migrate) throws ServletException, IOException{ if (request.getParameter("item_id") != null) { Item item = null; try { item = Item.find(context, Integer.parseInt(request .getParameter("item_id"))); } catch (Exception e) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } if (item == null) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } else { try { ItemExport.createDownloadableExport(item, context, migrate); } catch (ItemExportException iee) { log.warn(LogManager.getHeader(context, "export_too_large_error", UIUtil .getRequestLogInfo(request))); JSPManager.showJSP(request, response, "/mydspace/export-error.jsp"); return; } catch (Exception e) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } } // success JSPManager.showJSP(request, response, "/mydspace/task-complete.jsp"); } else if (request.getParameter("collection_id") != null) { Collection col = null; try { col = Collection.find(context, Integer.parseInt(request .getParameter("collection_id"))); } catch (Exception e) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } if (col == null) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } else { try { ItemExport.createDownloadableExport(col, context, migrate); } catch (ItemExportException iee) { log.warn(LogManager.getHeader(context, "export_too_large_error", UIUtil .getRequestLogInfo(request))); JSPManager.showJSP(request, response, "/mydspace/export-error.jsp"); return; } catch (Exception e) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } } JSPManager.showJSP(request, response, "/mydspace/task-complete.jsp"); } else if (request.getParameter("community_id") != null) { Community com = null; try { com = Community.find(context, Integer.parseInt(request .getParameter("community_id"))); } catch (Exception e) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } if (com == null) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } else { try { org.dspace.app.itemexport.ItemExport.createDownloadableExport(com, context, migrate); } catch (ItemExportException iee) { log.warn(LogManager.getHeader(context, "export_too_large_error", UIUtil .getRequestLogInfo(request))); JSPManager.showJSP(request, response, "/mydspace/export-error.jsp"); return; } catch (Exception e) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } } JSPManager.showJSP(request, response, "/mydspace/task-complete.jsp"); } } // **************************************************************** // **************************************************************** // METHODS FOR SHOWING FORMS // **************************************************************** // **************************************************************** /** * Show the main My DSpace page * * @param context * current context * @param request * current servlet request object * @param response * current servlet response object */ private void showMainPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { log.info(LogManager.getHeader(context, "view_mydspace", "")); EPerson currentUser = context.getCurrentUser(); // FIXME: WorkflowManager should return arrays List<WorkflowItem> ownedList = WorkflowManager.getOwnedTasks(context, currentUser); WorkflowItem[] owned = ownedList.toArray(new WorkflowItem[ownedList.size()]); // Pooled workflow items List<WorkflowItem> pooledList = WorkflowManager.getPooledTasks(context, currentUser); WorkflowItem[] pooled = pooledList.toArray(new WorkflowItem[pooledList.size()]); // User's WorkflowItems WorkflowItem[] workflowItems = WorkflowItem.findByEPerson(context, currentUser); // User's PersonalWorkspace WorkspaceItem[] workspaceItems = WorkspaceItem.findByEPerson(context, currentUser); // User's authorization groups Group[] memberships = Group.allMemberGroups(context, currentUser); // Should the group memberships be displayed boolean displayMemberships = ConfigurationManager.getBooleanProperty("webui.mydspace.showgroupmemberships", false); SupervisedItem[] supervisedItems = SupervisedItem.findbyEPerson( context, currentUser); // export archives available for download List<String> exportArchives = null; try{ exportArchives = ItemExport.getExportsAvailable(currentUser); } catch (Exception e) { // nothing to do they just have no export archives available for download } // Set attributes request.setAttribute("mydspace.user", currentUser); request.setAttribute("workspace.items", workspaceItems); request.setAttribute("workflow.items", workflowItems); request.setAttribute("workflow.owned", owned); request.setAttribute("workflow.pooled", pooled); request.setAttribute("group.memberships", memberships); request.setAttribute("display.groupmemberships", Boolean.valueOf(displayMemberships)); request.setAttribute("supervised.items", supervisedItems); request.setAttribute("export.archives", exportArchives); // Forward to main mydspace page JSPManager.showJSP(request, response, "/mydspace/main.jsp"); } /** * Show the user's previous submissions. * * @param context * current context * @param request * current servlet request object * @param response * current servlet response object */ private void showPreviousSubmissions(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Turn the iterator into a list List<Item> subList = new LinkedList<Item>(); ItemIterator subs = Item.findBySubmitter(context, context .getCurrentUser()); try { while (subs.hasNext()) { subList.add(subs.next()); } } finally { if (subs != null) { subs.close(); } } Item[] items = new Item[subList.size()]; for (int i = 0; i < subList.size(); i++) { items[i] = subList.get(i); } log.info(LogManager.getHeader(context, "view_own_submissions", "count=" + items.length)); request.setAttribute("user", context.getCurrentUser()); request.setAttribute("items", items); JSPManager.showJSP(request, response, "/mydspace/own-submissions.jsp"); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.sql.SQLException; import org.apache.log4j.Logger; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.content.Collection; import org.dspace.content.Item; import org.dspace.content.WorkspaceItem; /** * Class to deal with viewing workspace items during the authoring process. * Based heavily on the HandleServlet. * * @author Richard Jones * @version $Revision: 5845 $ */ public class ViewWorkspaceItemServlet extends DSpaceServlet { /** log4j logger */ private static Logger log = Logger.getLogger(ViewWorkspaceItemServlet.class); protected void doDSGet(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // pass all requests to the same place for simplicty doDSPost(c, request, response); } protected void doDSPost(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String button = UIUtil.getSubmitButton(request, "submit_error"); if (button.equals("submit_view") || button.equals("submit_full") || button.equals("submit_simple")) { showMainPage(c, request, response); } else { showErrorPage(c, request, response); } } /** * show the workspace item home page * * @param context the context of the request * @param request the servlet request * @param response the servlet response */ private void showMainPage(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // get the value from the request int wsItemID = UIUtil.getIntParameter(request,"workspace_id"); // get the workspace item, item and collections from the request value WorkspaceItem wsItem = WorkspaceItem.find(c, wsItemID); Item item = wsItem.getItem(); //Collection[] collections = item.getCollections(); Collection[] collections = {wsItem.getCollection()}; // Ensure the user has authorisation AuthorizeManager.authorizeAction(c, item, Constants.READ); log.info(LogManager.getHeader(c, "View Workspace Item Metadata", "workspace_item_id="+wsItemID)); // Full or simple display? boolean displayAll = false; String button = UIUtil.getSubmitButton(request, "submit_simple"); if (button.equalsIgnoreCase("submit_full")) { displayAll = true; } // FIXME: we need to synchronise with the handle servlet to use the // display item JSP for both handled and un-handled items // Set attributes and display // request.setAttribute("wsItem", wsItem); request.setAttribute("display.all", Boolean.valueOf(displayAll)); request.setAttribute("item", item); request.setAttribute("collections", collections); request.setAttribute("workspace_id", Integer.valueOf(wsItem.getID())); JSPManager.showJSP(request, response, "/display-item.jsp"); } /** * Show error page if nothing has been <code>POST</code>ed to servlet * * @param context the context of the request * @param request the servlet request * @param response the servlet response */ private void showErrorPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { int wsItemID = UIUtil.getIntParameter(request,"workspace_id"); log.error(LogManager.getHeader(context, "View Workspace Item Metadata Failed", "workspace_item_id="+wsItemID)); JSPManager.showJSP(request, response, "/workspace/wsv-error.jsp"); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dspace.app.webui.util.JSPManager; import org.dspace.authorize.AuthorizeException; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.eperson.Group; /** * This servlet provides an interface to the statistics reporting for a DSpace * repository * * @author Richard Jones * @version $Revision: 5845 $ */ public class StatisticsServlet extends org.dspace.app.webui.servlet.DSpaceServlet { protected void doDSGet(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // forward all requests to the post handler doDSPost(c, request, response); } protected void doDSPost(Context c, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // check to see if the statistics are restricted to administrators boolean publicise = ConfigurationManager.getBooleanProperty("report.public"); // determine the navigation bar to be displayed String navbar = (!publicise ? "admin" : "default"); request.setAttribute("navbar", navbar); // is the user a member of the Administrator (1) group boolean admin = Group.isMember(c, 1); if (publicise || admin) { showStatistics(c, request, response); } else { throw new AuthorizeException(); } } /** * show the default statistics page * * @param context current DSpace context * @param request current servlet request object * @param response current servlet response object */ private void showStatistics(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { StringBuffer report = new StringBuffer(); String date = (String) request.getParameter("date"); request.setAttribute("date", date); request.setAttribute("general", Boolean.FALSE); File reportDir = new File(ConfigurationManager.getProperty("report.dir")); File[] reports = reportDir.listFiles(); File reportFile = null; FileInputStream fir = null; InputStreamReader ir = null; BufferedReader br = null; try { List<Date> monthsList = new ArrayList<Date>(); Pattern monthly = Pattern.compile("report-([0-9][0-9][0-9][0-9]-[0-9]+)\\.html"); Pattern general = Pattern.compile("report-general-([0-9]+-[0-9]+-[0-9]+)\\.html"); // FIXME: this whole thing is horribly inflexible and needs serious // work; but as a basic proof of concept will suffice // if no date is passed then we want to get the most recent general // report if (date == null) { request.setAttribute("general", Boolean.TRUE); SimpleDateFormat sdf = new SimpleDateFormat("yyyy'-'M'-'dd"); Date mostRecentDate = null; for (int i = 0; i < reports.length; i++) { Matcher matchGeneral = general.matcher(reports[i].getName()); if (matchGeneral.matches()) { Date parsedDate = null; try { parsedDate = sdf.parse(matchGeneral.group(1).trim()); } catch (ParseException e) { // FIXME: currently no error handling } if (mostRecentDate == null) { mostRecentDate = parsedDate; reportFile = reports[i]; } if (parsedDate != null && parsedDate.compareTo(mostRecentDate) > 0) { mostRecentDate = parsedDate; reportFile = reports[i]; } } } } // if a date is passed then we want to get the file for that month if (date != null) { String desiredReport = "report-" + date + ".html"; for (int i = 0; i < reports.length; i++) { if (reports[i].getName().equals(desiredReport)) { reportFile = reports[i]; } } } if (reportFile == null) { JSPManager.showJSP(request, response, "statistics/no-report.jsp"); } // finally, build the list of report dates SimpleDateFormat sdf = new SimpleDateFormat("yyyy'-'M"); for (int i = 0; i < reports.length; i++) { Matcher matchReport = monthly.matcher(reports[i].getName()); if (matchReport.matches()) { Date parsedDate = null; try { parsedDate = sdf.parse(matchReport.group(1).trim()); } catch (ParseException e) { // FIXME: currently no error handling } monthsList.add(parsedDate); } } Date[] months = new Date[monthsList.size()]; months = (Date[]) monthsList.toArray(months); Arrays.sort(months); request.setAttribute("months", months); if (reportFile != null) { try { fir = new FileInputStream(reportFile.getPath()); ir = new InputStreamReader(fir, "UTF-8"); br = new BufferedReader(ir); } catch (IOException e) { // FIXME: no error handing yet throw new IllegalStateException(e.getMessage(),e); } // FIXME: there's got to be a better way of doing this String line = null; while ((line = br.readLine()) != null) { report.append(line); } } } finally { if (br != null) { try { br.close(); } catch (IOException ioe) { } } if (ir != null) { try { ir.close(); } catch (IOException ioe) { } } if (fir != null) { try { fir.close(); } catch (IOException ioe) { } } } // set the report to be displayed request.setAttribute("report", report.toString()); JSPManager.showJSP(request, response, "statistics/report.jsp"); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.Authenticate; import org.dspace.app.webui.util.JSPManager; import org.dspace.authorize.AuthorizeException; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.authenticate.AuthenticationManager; import org.dspace.authenticate.AuthenticationMethod; /** * Shibbolize dspace. Follow instruction at * http://mams.melcoe.mq.edu.au/zope/mams/pubs/Installation/dspace15 * * Pull information from the header as released by Shibboleth target. * The header required are: * <ol><li>user email</li> * <li>first name (optional)</li> * <li>last name (optional)</li> * <li>user roles</li> * </ol>. * * All these info are configurable from the configuration file (dspace.cfg). * * @author <a href="mailto:bliong@melcoe.mq.edu.au">Bruc Liong, MELCOE</a> * @author <a href="mailto:kli@melcoe.mq.edu.au">Xiang Kevin Li, MELCOE</a> * @version $Revision: 5845 $ */ public class ShibbolethServlet extends DSpaceServlet { /** log4j logger */ private static Logger log = Logger.getLogger(ShibbolethServlet.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { //debugging, show all headers java.util.Enumeration names = request.getHeaderNames(); String name; while(names.hasMoreElements()) { name = names.nextElement().toString(); log.info("header:" + name + "=" + request.getHeader(name)); } String jsp = null; // Locate the eperson int status = AuthenticationManager.authenticate(context, null, null, null, request); if (status == AuthenticationMethod.SUCCESS){ // Logged in OK. Authenticate.loggedIn(context, request, context.getCurrentUser()); log.info(LogManager.getHeader(context, "login", "type=shibboleth")); // resume previous request Authenticate.resumeInterruptedRequest(request, response); return; }else if (status == AuthenticationMethod.CERT_REQUIRED){ jsp = "/error/require-certificate.jsp"; }else if(status == AuthenticationMethod.NO_SUCH_USER){ jsp = "/login/no-single-sign-out.jsp"; }else if(status == AuthenticationMethod.BAD_ARGS){ jsp = "/login/no-email.jsp"; } // If we reach here, supplied email/password was duff. log.info(LogManager.getHeader(context, "failed_login","result="+String.valueOf(status))); JSPManager.showJSP(request, response, jsp); return; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import java.util.Locale; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.jstl.core.Config; import org.apache.log4j.Logger; import org.dspace.app.webui.util.Authenticate; import org.dspace.app.webui.util.JSPManager; import org.dspace.authenticate.AuthenticationManager; import org.dspace.authenticate.AuthenticationMethod; import org.dspace.authorize.AuthorizeException; import org.dspace.core.Context; import org.dspace.core.I18nUtil; import org.dspace.core.LogManager; /** * Simple username and password authentication servlet. Displays the login form * <code>/login/password.jsp</code> on a GET, otherwise process the parameters * as an email and password. * * Calls stackable authentication to give credentials to all * authentication methods that can make use of them, not just DSpace-internal. * * @author Robert Tansley * @version $Revision: 5845 $ */ public class PasswordServlet extends DSpaceServlet { /** log4j logger */ private static Logger log = Logger.getLogger(PasswordServlet.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Simply forward to the plain form JSPManager.showJSP(request, response, "/login/password.jsp"); } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Process the POSTed email and password String email = request.getParameter("login_email"); String password = request.getParameter("login_password"); String jsp = null; // Locate the eperson int status = AuthenticationManager.authenticate(context, email, password, null, request); if (status == AuthenticationMethod.SUCCESS) { // Logged in OK. Authenticate.loggedIn(context, request, context.getCurrentUser()); // Set the Locale according to user preferences Locale epersonLocale = I18nUtil.getEPersonLocale(context.getCurrentUser()); context.setCurrentLocale(epersonLocale); Config.set(request.getSession(), Config.FMT_LOCALE, epersonLocale); log.info(LogManager.getHeader(context, "login", "type=explicit")); // resume previous request Authenticate.resumeInterruptedRequest(request, response); return; } else if (status == AuthenticationMethod.CERT_REQUIRED) { jsp = "/error/require-certificate.jsp"; } else { jsp = "/login/incorrect.jsp"; } // If we reach here, supplied email/password was duff. log.info(LogManager.getHeader(context, "failed_login", "email=" + email + ", result=" + String.valueOf(status))); JSPManager.showJSP(request, response, jsp); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.bulkedit.MetadataExport; import org.dspace.app.bulkedit.DSpaceCSV; import org.dspace.app.webui.util.JSPManager; import org.dspace.authorize.AuthorizeException; import org.dspace.core.*; import org.dspace.content.DSpaceObject; import org.dspace.content.ItemIterator; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.handle.HandleManager; /** * Servlet to export metadata as CSV (comma separated values) * * @author Stuart Lewis */ public class MetadataExportServlet extends DSpaceServlet { /** log4j category */ private static Logger log = Logger.getLogger(MetadataExportServlet.class); /** * Respond to a post request * * @param context a DSpace Context object * @param request the HTTP request * @param response the HTTP response * * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Get the handle requested for the export String handle = request.getParameter("handle"); MetadataExport exporter = null; if (handle != null) { log.info(LogManager.getHeader(context, "metadataexport", "exporting_handle:" + handle)); DSpaceObject thing = HandleManager.resolveToObject(context, handle); if (thing != null) { if (thing.getType() == Constants.ITEM) { List<Integer> item = new ArrayList<Integer>(); item.add(thing.getID()); exporter = new MetadataExport(context, new ItemIterator(context, item), false); } else if (thing.getType() == Constants.COLLECTION) { Collection collection = (Collection)thing; ItemIterator toExport = collection.getAllItems(); exporter = new MetadataExport(context, toExport, false); } else if (thing.getType() == Constants.COMMUNITY) { exporter = new MetadataExport(context, (Community)thing, false); } if (exporter != null) { // Perform the export DSpaceCSV csv = exporter.export(); // Return the csv file response.setContentType("text/csv; charset=UTF-8"); String filename = handle.replaceAll("/", "-") + ".csv"; response.setHeader("Content-Disposition", "attachment; filename=" + filename); PrintWriter out = response.getWriter(); out.write(csv.toString()); out.flush(); out.close(); log.info(LogManager.getHeader(context, "metadataexport", "exported_file:" + filename)); return; } } } // Something has gone wrong JSPManager.showIntegrityError(request, response); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.net.InetAddress; import java.sql.SQLException; import java.util.MissingResourceException; import javax.mail.MessagingException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.dspace.app.webui.util.JSPManager; import org.dspace.authorize.AuthorizeException; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.core.Email; import org.dspace.core.I18nUtil; import org.dspace.core.LogManager; import org.dspace.eperson.EPerson; import org.dspace.handle.HandleManager; import org.dspace.content.Item; import org.dspace.content.Collection; import org.dspace.content.DCValue; /** * Servlet for handling user email recommendations * * @author Arnaldo Dantas * @version $Revision: 5845 $ */ public class SuggestServlet extends DSpaceServlet { /** log4j category */ private static Logger log = Logger.getLogger(SuggestServlet.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Obtain information from request // The page where the user came from String fromPage = request.getHeader("Referer"); // Prevent spammers and splogbots from poisoning the feedback page String host = ConfigurationManager.getProperty("dspace.hostname"); String basicHost = ""; if (host.equals("localhost") || host.equals("127.0.0.1") || host.equals(InetAddress.getLocalHost().getHostAddress())) { basicHost = host; } else { // cut off all but the hostname, to cover cases where more than one URL // arrives at the installation; e.g. presence or absence of "www" int lastDot = host.lastIndexOf('.'); basicHost = host.substring(host.substring(0, lastDot).lastIndexOf(".")); } if (fromPage == null || fromPage.indexOf(basicHost) == -1) { throw new AuthorizeException(); } // Obtain information from request String handle = request.getParameter("handle"); // Lookup Item title & collection String title = null; String collName = null; if (handle != null && !handle.equals("")) { Item item = (Item) HandleManager.resolveToObject(context, handle); if (item != null) { DCValue[] titleDC = item.getDC("title", null, Item.ANY); if (titleDC != null && titleDC.length > 0) { title = titleDC[0].value; } Collection[] colls = item.getCollections(); collName = colls[0].getMetadata("name"); } } else { String path = request.getPathInfo(); log.info(LogManager.getHeader(context, "invalid_id", "path=" + path)); JSPManager.showInvalidIDError(request, response, path, -1); return; } if (title == null) { title = ""; } if(collName == null) { collName = ""; } request.setAttribute("suggest.title", title); // User email from context EPerson currentUser = context.getCurrentUser(); String authEmail = null; String userName = null; if (currentUser != null) { authEmail = currentUser.getEmail(); userName = currentUser.getFullName(); } if (request.getParameter("submit") != null) { String recipAddr = request.getParameter("recip_email"); // the only required field is recipient email address if (recipAddr == null || recipAddr.equals("")) { log.info(LogManager.getHeader(context, "show_suggest_form", "problem=true")); request.setAttribute("suggest.problem", Boolean.TRUE); JSPManager.showJSP(request, response, "/suggest/suggest.jsp"); return; } String recipName = request.getParameter("recip_name"); if (recipName == null || "".equals(recipName)) { try { recipName = I18nUtil.getMessage("org.dspace.app.webui.servlet.SuggestServlet.recipient", context); } catch (MissingResourceException e) { log.warn(LogManager.getHeader(context, "show_suggest_form", "Missing Resource: org.dspace.app.webui.servlet.SuggestServlet.sender")); recipName = "colleague"; } } String senderName = request.getParameter("sender_name"); if (senderName == null || "".equals(senderName) ) { // use userName if available if (userName != null) { senderName = userName; } else { try { senderName = I18nUtil.getMessage("org.dspace.app.webui.servlet.SuggestServlet.sender", context); } catch (MissingResourceException e) { log.warn(LogManager.getHeader(context, "show_suggest_form", "Missing Resource: org.dspace.app.webui.servlet.SuggestServlet.sender")); senderName = "A DSpace User"; } } } String senderAddr = request.getParameter("sender_email"); if (StringUtils.isEmpty(senderAddr) && authEmail != null) { // use authEmail if available senderAddr = authEmail; } String itemUri = HandleManager.getCanonicalForm(handle); String itemUrl = HandleManager.resolveToURL(context,handle); String message = request.getParameter("message"); String siteName = ConfigurationManager.getProperty("dspace.name"); // All data is there, send the email try { Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "suggest")); email.addRecipient(recipAddr); // recipient address email.addArgument(recipName); // 1st arg - recipient name email.addArgument(senderName); // 2nd arg - sender name email.addArgument(siteName); // 3rd arg - repository name email.addArgument(title); // 4th arg - item title email.addArgument(itemUri); // 5th arg - item handle URI email.addArgument(itemUrl); // 6th arg - item local URL email.addArgument(collName); // 7th arg - collection name email.addArgument(message); // 8th arg - user comments // Set sender's address as 'reply-to' address if supplied if ( senderAddr != null && ! "".equals(senderAddr)) { email.setReplyTo(senderAddr); } // Only actually send the email if feature is enabled if (ConfigurationManager.getBooleanProperty("webui.suggest.enable", false)) { email.send(); } else { throw new MessagingException("Suggest item email not sent - webui.suggest.enable = false"); } log.info(LogManager.getHeader(context, "sent_suggest", "from=" + senderAddr)); JSPManager.showJSP(request, response, "/suggest/suggest_ok.jsp"); } catch (MessagingException me) { log.warn(LogManager.getHeader(context, "error_mailing_suggest", ""), me); JSPManager.showInternalError(request, response); } } else { // Display suggest form log.info(LogManager.getHeader(context, "show_suggest_form", "problem=false")); request.setAttribute("authenticated.email", authEmail); request.setAttribute("eperson.name", userName); JSPManager.showJSP(request, response, "/suggest/suggest.jsp"); //asd } } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Treat as a GET doDSGet(context, request, response); } }
Java