answer
stringlengths
17
10.2M
package com.jetbrains.python.psi.search; import com.intellij.ide.highlighter.HtmlFileType; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiReference; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.SearchScope; import com.intellij.psi.search.TextOccurenceProcessor; import com.intellij.psi.search.UsageSearchContext; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.util.Processor; import com.intellij.util.QueryExecutor; import com.jetbrains.django.lang.template.DjangoTemplateFileType; import com.jetbrains.django.lang.template.psi.impl.DjangoTemplateFileImpl; import com.jetbrains.django.util.PythonUtil; import com.jetbrains.python.PythonFileType; import com.jetbrains.python.psi.PyElement; import com.jetbrains.python.psi.PyFile; import org.jetbrains.annotations.NotNull; /** * @author traff */ public class PyStringReferenceSearch implements QueryExecutor<PsiReference, ReferencesSearch.SearchParameters> { public boolean execute(@NotNull final ReferencesSearch.SearchParameters params, @NotNull final Processor<PsiReference> consumer) { final PsiElement element = params.getElementToSearch(); if (!(element instanceof PyElement) && !(element instanceof PsiDirectory) && !(element instanceof DjangoTemplateFileImpl)) { return true; } SearchScope searchScope = params.getEffectiveSearchScope(); if (searchScope instanceof GlobalSearchScope) { searchScope = GlobalSearchScope.getScopeRestrictedByFileTypes((GlobalSearchScope)searchScope, PythonFileType.INSTANCE ); } return PythonUtil.searchElementStringReferences(consumer, element, searchScope); } }
package cn.cerc.db.core; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * HTTP * * @author ZhangGong * @version 1.0, 2018-1-1 */ //FIXME url new Curl(url); @Slf4j public class Curl { private String requestEncoding = "UTF-8"; private String recvEncoding = "UTF-8"; private int connectTimeOut = 5000; private int readTimeOut = 10000; private final Map<String, Object> parameters = new HashMap<>(); private String responseContent = null; public String sendGet(String reqUrl) { StringBuilder result = new StringBuilder(); BufferedReader in = null; try { StringBuilder builder = new StringBuilder(); builder.append(reqUrl); int i = 0; for (String key : parameters.keySet()) { i++; builder.append(i == 1 ? "?" : "&"); builder.append(key); builder.append("="); String value = parameters.get(key).toString(); if (value != null) { builder.append(encodeUTF8(value)); } } URL url = new URL(builder.toString()); // URL URLConnection connection = url.openConnection(); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.connect(); // BufferedReaderURL in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result.append(line); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (Exception e) { e.printStackTrace(); } } return result.toString(); } private String encodeUTF8(String value) { try { return URLEncoder.encode(value, requestEncoding); } catch (UnsupportedEncodingException e) { return value; } } // GETHTTP public String doGet(String reqUrl) { HttpURLConnection url_con = null; try { StringBuffer params = new StringBuffer(); for (Entry<String, Object> stringObjectEntry : parameters.entrySet()) { params.append(((Entry<?, ?>) stringObjectEntry).getKey().toString()); params.append("="); params.append(URLEncoder.encode(((Entry<?, ?>) stringObjectEntry).getValue().toString(), this.requestEncoding)); params.append("&"); } if (params.length() > 0) { params = params.deleteCharAt(params.length() - 1); } URL url = new URL(reqUrl); url_con = (HttpURLConnection) url.openConnection(); url_con.setRequestMethod("GET"); url_con.setDoOutput(true); byte[] b = params.toString().getBytes(); url_con.getOutputStream().write(b, 0, b.length); url_con.getOutputStream().flush(); url_con.getOutputStream().close(); int status = url_con.getResponseCode(); BufferedInputStream in; if (status >= 400) { in = new BufferedInputStream(url_con.getErrorStream()); } else { in = new BufferedInputStream(url_con.getInputStream()); } BufferedReader rd = new BufferedReader(new InputStreamReader(in, this.recvEncoding)); String tempLine = rd.readLine(); StringBuilder temp = new StringBuilder(); while (tempLine != null) { temp.append(tempLine); tempLine = rd.readLine(); } responseContent = temp.toString(); rd.close(); in.close(); } catch (IOException e) { log.error("network error", e); } finally { if (url_con != null) { url_con.disconnect(); } } return responseContent; } // GETHTTP, reqUrl HTTPURL return HTTP protected String doGet2(String reqUrl) { HttpURLConnection url_con = null; try { StringBuffer params = new StringBuffer(); String queryUrl = reqUrl; int paramIndex = reqUrl.indexOf("?"); if (paramIndex > 0) { queryUrl = reqUrl.substring(0, paramIndex); String parameters = reqUrl.substring(paramIndex + 1); String[] paramArray = parameters.split("&"); for (String string : paramArray) { int index = string.indexOf("="); if (index > 0) { String parameter = string.substring(0, index); String value = string.substring(index + 1); params.append(parameter); params.append("="); params.append(URLEncoder.encode(value, this.requestEncoding)); params.append("&"); } } params = params.deleteCharAt(params.length() - 1); } URL url = new URL(queryUrl); url_con = (HttpURLConnection) url.openConnection(); url_con.setRequestMethod("GET"); System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(this.connectTimeOut));// jdk1.4, System.setProperty("sun.net.client.defaultReadTimeout", String.valueOf(this.readTimeOut)); // jdk1.4, // url_con.setConnectTimeout(5000);//jdk // url_con.setReadTimeout(5000);//jdk 1.5, url_con.setDoOutput(true); byte[] b = params.toString().getBytes(); url_con.getOutputStream().write(b, 0, b.length); url_con.getOutputStream().flush(); url_con.getOutputStream().close(); InputStream in = url_con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(in, recvEncoding)); String tempLine = rd.readLine(); StringBuilder temp = new StringBuilder(); while (tempLine != null) { temp.append(tempLine); tempLine = rd.readLine(); } responseContent = temp.toString(); rd.close(); in.close(); } catch (IOException e) { log.error("network error", e); } finally { if (url_con != null) { url_con.disconnect(); } } return responseContent; } // POSTHTTP public String doPost(String reqUrl) { try { StringBuffer params = new StringBuffer(); for (Entry<String, Object> stringObjectEntry : parameters.entrySet()) { Object val = ((Entry<?, ?>) stringObjectEntry).getValue(); if (val != null) { params.append(((Entry<?, ?>) stringObjectEntry).getKey().toString()); params.append("="); params.append(URLEncoder.encode(val.toString(), this.requestEncoding)); params.append("&"); } } if (params.length() > 0) { params = params.deleteCharAt(params.length() - 1); } return doPost(reqUrl, params); } catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); throw new RuntimeException(e.getMessage()); } } public String doPost(String reqUrl, StringBuffer params) { HttpURLConnection url_con = null; try { reqUrl = new String(reqUrl.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); URL url = new URL(reqUrl); url_con = (HttpURLConnection) url.openConnection(); url_con.setRequestMethod("POST"); // System.setProperty("sun.net.client.defaultConnectTimeout", // String.valueOf(CURL.connectTimeOut));// jdk1.4, // System.setProperty("sun.net.client.defaultReadTimeout", // String.valueOf(CURL.readTimeOut)); // jdk1.4, url_con.setConnectTimeout(this.connectTimeOut);// jdk url_con.setReadTimeout(this.readTimeOut);// jdk 1.5, url_con.setDoOutput(true); byte[] b = params.toString().getBytes(); url_con.getOutputStream().write(b, 0, b.length); url_con.getOutputStream().flush(); url_con.getOutputStream().close(); int status = url_con.getResponseCode(); BufferedInputStream in; if (status >= 400) { in = new BufferedInputStream(url_con.getErrorStream()); } else { in = new BufferedInputStream(url_con.getInputStream()); } BufferedReader rd = new BufferedReader(new InputStreamReader(in, recvEncoding)); String tempLine = rd.readLine(); StringBuilder tempStr = new StringBuilder(); while (tempLine != null) { tempStr.append(tempLine); tempLine = rd.readLine(); } responseContent = tempStr.toString(); rd.close(); in.close(); } catch (IOException e) { log.error(e.getMessage(), e); } finally { if (url_con != null) { url_con.disconnect(); } } return responseContent; } public String doPost(String url, String json) { try { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Content-Type", "application/json"); httpPost.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON)); CloseableHttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); responseContent = EntityUtils.toString(entity, StandardCharsets.UTF_8); response.close(); httpClient.close(); } catch (IOException e) { log.error(e.getMessage(), e); throw new RuntimeException(e.getMessage()); } return responseContent; } public int getConnectTimeOut() { return this.connectTimeOut; } public void setConnectTimeOut(int connectTimeOut) { this.connectTimeOut = connectTimeOut; } public int getReadTimeOut() { return this.readTimeOut; } public void setReadTimeOut(int readTimeOut) { this.readTimeOut = readTimeOut; } public String getRequestEncoding() { return requestEncoding; } public void setRequestEncoding(String requestEncoding) { this.requestEncoding = requestEncoding; } public String getRecvEncoding() { return recvEncoding; } public void setRecvEncoding(String recvEncoding) { this.recvEncoding = recvEncoding; } public Map<String, Object> getParameters() { return parameters; } public String getResponseContent() { return responseContent; } @Deprecated // putParameter public Curl addParameter(String key, Object value) { this.parameters.put(key, value); return this; } public Curl put(String key, Object value) { this.parameters.put(key, value); return this; } /** * put * @param key * @param value * @return */ @Deprecated public Curl putParameter(String key, Object value) { return this.put(key, value); } }
package benchmarking; import datamodel.CpuUsageResults; import org.apache.commons.io.input.ReversedLinesFileReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; public class CpuMonitoring implements MonitoringInterface { private final static Logger logger = LoggerFactory.getLogger(CpuMonitoring.class); private Calendar startTimeOfMonitoring; private Calendar endTimeOfMonitoring; @Override public void startMonitoring() { startTimeOfMonitoring = Calendar.getInstance(); startTimeOfMonitoring.add(Calendar.SECOND, -1); } @Override public void stopMonitoring() { endTimeOfMonitoring = Calendar.getInstance(); endTimeOfMonitoring.add(Calendar.SECOND, 1); } public CpuUsageResults parseForPid(long pid) { BufferedReader br = null; String line; List<String> cpuUsageResults = new ArrayList<String>(); try { Thread.sleep(1500); String strpath="/tmp/performanceMonitoring.log"; ReversedLinesFileReader reverseFileReader = new ReversedLinesFileReader(new File(strpath));; do { line = reverseFileReader.readLine(); if (line == null) { continue; } String[] splitedLine = line.split("\\s+"); if ((splitedLine.length >= 6) && // at least a timestamp, a pid and a % splitedLine[1].trim().length() > 0 && // the PID length is > 0 (splitedLine[0].trim().length() > 18)) { // a valid timestamp (date + time) String[] dateAndTime = splitedLine[0].split("_"); String date = dateAndTime[0]; String time = dateAndTime[1]; if (date.trim().length() == 0 || time.trim().length() == 0) { continue; } String[] dateSplit = date.split("/"); String[] timeSplit = time.split(":"); Calendar timeFromLog = Calendar.getInstance(); timeFromLog.set(Calendar.SECOND, Integer.parseInt(timeSplit[2])); timeFromLog.set(Calendar.MINUTE, Integer.parseInt(timeSplit[1])); timeFromLog.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeSplit[0])); timeFromLog.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dateSplit[2])); timeFromLog.set(Calendar.MONTH, Integer.parseInt(dateSplit[1]) - 1); timeFromLog.set(Calendar.YEAR, Integer.parseInt(dateSplit[0])); if (timeFromLog.after(startTimeOfMonitoring) && timeFromLog.before(endTimeOfMonitoring) && isNumeric(splitedLine[1].trim())) { long resultsPid = Long.parseLong(splitedLine[1]); if (resultsPid == pid) { cpuUsageResults.add(splitedLine[2]); // PID is ok and time is ok } } // look untill the time read from log is before the process began if (timeFromLog.before(startTimeOfMonitoring)) { break; } } } while (line != null); reverseFileReader.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } Collections.reverse(cpuUsageResults); return new CpuUsageResults(pid, startTimeOfMonitoring, cpuUsageResults); } public CpuUsageResults parseForPidFromFileHead(long pid) { BufferedReader br = null; String line; List<String> cpuUsageResults = new ArrayList<String>(); try { // wait for 1 second before reading the file so that all data for PID is written in file Thread.sleep(1500); br = new BufferedReader(new FileReader("/tmp/everySecondMonitoring.txt")); while ((line = br.readLine()) != null) { String[] splitedLine = line.split("\\s+"); if ((splitedLine.length > 2) && // at least a timestamp, a pid and a % splitedLine[1].trim().length() > 0 && // the PID length is > 0 isNumeric(splitedLine[1].trim()) && // the PID is a number (splitedLine[0].trim().length() > 18)) { // a valid timestamp (date + time) long resultsPid = Long.parseLong(splitedLine[1]); if (resultsPid == pid) { String[] dateAndTime = splitedLine[0].split("_"); String date = dateAndTime[0]; String time = dateAndTime[1]; if (date.trim().length() == 0 || time.trim().length() == 0) { continue; } String[] dateSplit = date.split("/"); String[] timeSplit = time.split(":"); Calendar timeFromLog = Calendar.getInstance(); timeFromLog.set(Calendar.SECOND, Integer.parseInt(timeSplit[2])); timeFromLog.set(Calendar.MINUTE, Integer.parseInt(timeSplit[1])); timeFromLog.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeSplit[0])); timeFromLog.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dateSplit[2])); timeFromLog.set(Calendar.MONTH, Integer.parseInt(dateSplit[1]) - 1); timeFromLog.set(Calendar.YEAR, Integer.parseInt(dateSplit[0])); if (timeFromLog.after(startTimeOfMonitoring) && timeFromLog.before(endTimeOfMonitoring)) { cpuUsageResults.add(splitedLine[2]); // PID is ok and time is ok } if (timeFromLog.after(endTimeOfMonitoring)) { // it is useless to look after the time the monitoring was stopped break; } } } } } catch (FileNotFoundException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } catch (NumberFormatException e) { logger.error(e.getMessage(), e); } catch (ArrayIndexOutOfBoundsException e) { logger.error(e.getMessage(), e); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } finally { try { br.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } return new CpuUsageResults(pid, startTimeOfMonitoring, cpuUsageResults); } private boolean isNumeric(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isDigit(str.charAt(i)) == false) { return false; } } return true; } }
package net.java.sip.communicator.impl.protocol.yahoo; import java.io.*; import java.util.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.service.protocol.yahooconstants.*; import net.java.sip.communicator.util.*; import ymsg.support.*; import ymsg.network.*; import ymsg.network.event.*; /** * A straightforward implementation of the basic instant messaging operation * set. * * @author Damian Minkov */ public class OperationSetBasicInstantMessagingYahooImpl implements OperationSetBasicInstantMessaging { /** * Logger for this class */ private static final Logger logger = Logger.getLogger(OperationSetBasicInstantMessagingYahooImpl.class); /** * HTML content type */ private static final String CONTENT_TYPE_HTML = "text/html"; /** * Yahoo has limit of message length. If exceeded * message is not delivered and no notification is received for that. */ private static int MAX_MESSAGE_LENGTH = 800; // 949 /** * A list of listeneres registered for message events. */ private Vector messageListeners = new Vector(); /** * The provider that created us. */ private ProtocolProviderServiceYahooImpl yahooProvider = null; /** * A reference to the persistent presence operation set that we use * to match incoming messages to <tt>Contact</tt>s and vice versa. */ private OperationSetPersistentPresenceYahooImpl opSetPersPresence = null; /** * Creates an instance of this operation set. * @param provider a ref to the <tt>ProtocolProviderServiceImpl</tt> * that created us and that we'll use for retrieving the underlying aim * connection. */ OperationSetBasicInstantMessagingYahooImpl( ProtocolProviderServiceYahooImpl provider) { this.yahooProvider = provider; provider.addRegistrationStateChangeListener(new RegistrationStateListener()); } /** * Registeres a MessageListener with this operation set so that it gets * notifications of successful message delivery, failure or reception of * incoming messages.. * * @param listener the <tt>MessageListener</tt> to register. */ public void addMessageListener(MessageListener listener) { synchronized(messageListeners) { if(!messageListeners.contains(listener)) { this.messageListeners.add(listener); } } } /** * Unregisteres <tt>listener</tt> so that it won't receive any further * notifications upon successful message delivery, failure or reception of * incoming messages.. * * @param listener the <tt>MessageListener</tt> to unregister. */ public void removeMessageListener(MessageListener listener) { synchronized(messageListeners) { this.messageListeners.remove(listener); } } /** * Determines wheter the protocol provider (or the protocol itself) support * sending and receiving offline messages. Most often this method would * return true for protocols that support offline messages and false for * those that don't. It is however possible for a protocol to support these * messages and yet have a particular account that does not (i.e. feature * not enabled on the protocol server). In cases like this it is possible * for this method to return true even when offline messaging is not * supported, and then have the sendMessage method throw an * OperationFailedException with code - OFFLINE_MESSAGES_NOT_SUPPORTED. * * @return <tt>true</tt> if the protocol supports offline messages and * <tt>false</tt> otherwise. */ public boolean isOfflineMessagingSupported() { return true; } /** * Determines wheter the protocol supports the supplied content type * * @param contentType the type we want to check * @return <tt>true</tt> if the protocol supports it and * <tt>false</tt> otherwise. */ public boolean isContentTypeSupported(String contentType) { if(contentType.equals(DEFAULT_MIME_TYPE) || contentType.equals(CONTENT_TYPE_HTML)) return true; else return false; } /** * Create a Message instance for sending arbitrary MIME-encoding content. * * @param content content value * @param contentType the MIME-type for <tt>content</tt> * @param contentEncoding encoding used for <tt>content</tt> * @param subject a <tt>String</tt> subject or <tt>null</tt> for now subject. * @return the newly created message. */ public Message createMessage(byte[] content, String contentType, String contentEncoding, String subject) { return new MessageYahooImpl(new String(content), contentType , contentEncoding, subject); } /** * Create a Message instance for sending a simple text messages with * default (text/plain) content type and encoding. * * @param messageText the string content of the message. * @return Message the newly created message */ public Message createMessage(String messageText) { return new MessageYahooImpl( messageText, DEFAULT_MIME_TYPE, DEFAULT_MIME_ENCODING, null); } public void sendInstantMessage(Contact to, Message message) throws IllegalStateException, IllegalArgumentException { assertConnected(); if( !(to instanceof ContactYahooImpl) ) throw new IllegalArgumentException( "The specified contact is not a Yahoo contact." + to); try { String toUserID = ((ContactYahooImpl) to).getID(); byte[] msgBytesToBeSent = message.getContent().getBytes(); // split the message in parts with max allowed length // and send them all do { if(msgBytesToBeSent.length > MAX_MESSAGE_LENGTH) { byte[] tmp1 = new byte[MAX_MESSAGE_LENGTH]; System.arraycopy(msgBytesToBeSent, 0, tmp1, 0, MAX_MESSAGE_LENGTH); byte[] tmp2 = new byte[msgBytesToBeSent.length - MAX_MESSAGE_LENGTH]; System.arraycopy(msgBytesToBeSent, MAX_MESSAGE_LENGTH, tmp2, 0, tmp2.length); msgBytesToBeSent = tmp2; yahooProvider.getYahooSession().sendMessage( toUserID, new String(tmp1)); } else { yahooProvider.getYahooSession().sendMessage( toUserID, new String(msgBytesToBeSent)); } MessageDeliveredEvent msgDeliveredEvt = new MessageDeliveredEvent( message, to, new Date()); fireMessageEvent(msgDeliveredEvt); } while(msgBytesToBeSent.length > MAX_MESSAGE_LENGTH); } catch (IOException ex) { logger.fatal("Cannot Send Message! " + ex.getMessage()); MessageDeliveryFailedEvent evt = new MessageDeliveryFailedEvent( message, to, MessageDeliveryFailedEvent.NETWORK_FAILURE, new Date()); fireMessageEvent(evt); return; } } private void assertConnected() throws IllegalStateException { if (yahooProvider == null) throw new IllegalStateException( "The provider must be non-null and signed on the " +"service before being able to communicate."); if (!yahooProvider.isRegistered()) throw new IllegalStateException( "The provider must be signed on the service before " +"being able to communicate."); } /** * Our listener that will tell us when we're registered to */ private class RegistrationStateListener implements RegistrationStateChangeListener { /** * The method is called by a ProtocolProvider implementation whenver * a change in the registration state of the corresponding provider had * occurred. * @param evt ProviderStatusChangeEvent the event describing the status * change. */ public void registrationStateChanged(RegistrationStateChangeEvent evt) { logger.debug("The provider changed state from: " + evt.getOldState() + " to: " + evt.getNewState()); if (evt.getNewState() == RegistrationState.REGISTERED) { opSetPersPresence = (OperationSetPersistentPresenceYahooImpl) yahooProvider.getSupportedOperationSets() .get(OperationSetPersistentPresence.class.getName()); yahooProvider.getYahooSession(). addSessionListener(new YahooMessageListener()); } } } /** * Delivers the specified event to all registered message listeners. * @param evt the <tt>EventObject</tt> that we'd like delivered to all * registered message listerners. */ private void fireMessageEvent(EventObject evt) { Iterator listeners = null; synchronized (messageListeners) { listeners = new ArrayList(messageListeners).iterator(); } logger.debug("Dispatching msg evt. Listeners=" + messageListeners.size() + " evt=" + evt); while (listeners.hasNext()) { MessageListener listener = (MessageListener) listeners.next(); if (evt instanceof MessageDeliveredEvent) { listener.messageDelivered( (MessageDeliveredEvent) evt); } else if (evt instanceof MessageReceivedEvent) { listener.messageReceived( (MessageReceivedEvent) evt); } else if (evt instanceof MessageDeliveryFailedEvent) { listener.messageDeliveryFailed( (MessageDeliveryFailedEvent) evt); } } } /** * This class provides methods to listen for yahoo events which interest us. */ private class YahooMessageListener extends SessionAdapter { /** * Overrides <tt>messageReceived</tt> from <tt>SessionAdapter</tt>, * called when we receive a new intant message. * * @param ev Event with information on the received message */ public void messageReceived(SessionEvent ev) { handleNewMessage(ev); } /** * Overrides <tt>offlineMessageReceived</tt> from <tt>SessionAdapter</tt>, * called when we receive a message which has been sent to us * when we were offline. * * @param ev Event with information on the received message */ public void offlineMessageReceived(SessionEvent ev) { handleNewMessage(ev); } /** * Overrides <tt>newMailReceived</tt> from <tt>SessionAdapter</tt>, * called when yahoo alert us that there is a new message in our mailbox. * * @param ev Event with information on the received email */ public void newMailReceived(SessionNewMailEvent ev) { String myEmail = yahooProvider.getAccountID().getAccountAddress(); // this was intended to obtain the user server i.e. mail.yahoo.com, // or mail.yahoo.fr so that the login page is in the preferred user // language. but it always gives yahoo.com, even if the account // is registered with yahoo.fr ... // perhaps because the pps always login on yahoo.com ? String yahooMailLogon = "http://mail." + myEmail.substring(myEmail.indexOf("@") + 1); yahooMailLogon = "<a href=\"" + yahooMailLogon + "\">" + yahooMailLogon + "</a>"; String newMail = "<b>" + Resources.getString("newMail") + " : </b> " + ev.getSubject(); newMail += "\n<br /><b>" + Resources.getString("from") + " : </b> " + ev.getFrom() + " &lt;" + ev.getEmailAddress() + "&gt;"; newMail += "\n<br />&nbsp;&nbsp;&nbsp;&nbsp;" + yahooMailLogon; Message newMailMessage = new MessageYahooImpl( newMail, CONTENT_TYPE_HTML, DEFAULT_MIME_ENCODING, null); Contact sourceContact = opSetPersPresence. findContactByID(ev.getEmailAddress()); if (sourceContact == null) { logger.debug("received a new mail from an unknown contact: " + ev.getFrom()); //create the volatile contact sourceContact = opSetPersPresence .createVolatileContact(ev.getFrom()); } MessageReceivedEvent msgReceivedEvt = new MessageReceivedEvent( newMailMessage, sourceContact, new Date(), MessageReceivedEvent.SYSTEM_MESSAGE_RECEIVED); fireMessageEvent(msgReceivedEvt); } /** * Handle incoming message by creating an appropriate Sip Communicator * <tt>Message</tt> and firing a <tt>MessageReceivedEvent</tt> * to interested listeners. * * @param ev The original <tt>SessionEvent</tt> which noticed us * of an incoming message. */ private void handleNewMessage(SessionEvent ev) { logger.debug("Message received : " + ev); //As no indications in the protocol is it html or not. No harm //to set all messages html - doesn't affect the appearance of the gui Message newMessage = createMessage( new MessageDecoder().decodeToHTML(ev.getMessage()).getBytes(), CONTENT_TYPE_HTML, DEFAULT_MIME_ENCODING, null); Contact sourceContact = opSetPersPresence. findContactByID(ev.getFrom()); if(sourceContact == null) { logger.debug("received a message from an unknown contact: " + ev.getFrom()); //create the volatile contact sourceContact = opSetPersPresence .createVolatileContact(ev.getFrom()); } MessageReceivedEvent msgReceivedEvt = new MessageReceivedEvent( newMessage, sourceContact , new Date() ); fireMessageEvent(msgReceivedEvt); } } }
package org.openas2.app; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.concurrent.ExecutorService; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.http.HttpEntity; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import org.openas2.TestResource; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertThat; @RunWith(MockitoJUnitRunner.class) /** * * @author javier */ public class RestApiTest { private static final TestResource RESOURCE = TestResource.forGroup("SingleServerTest"); // private static File openAS2AHome; private static OpenAS2Server serverInstance; private static ExecutorService executorService; private static TemporaryFolder scratchpad = new TemporaryFolder(); private static CloseableHttpClient httpclient; @Rule public TemporaryFolder tmp = new TemporaryFolder(); @BeforeClass public static void startServer() throws Exception { // Set up some override properties so we can use the standard config in tests // to make sure the release package is fully tested scratchpad.create(); File customPropsFile = scratchpad.newFile("openas2.properties"); System.setProperty("openas2.properties.file", customPropsFile.getAbsolutePath()); FileOutputStream fos = new FileOutputStream(customPropsFile); fos.write("restapi.command.processor.enabled=true\n".getBytes()); fos.close(); try { System.setProperty("org.apache.commons.logging.Log", "org.openas2.logging.Log"); System.setProperty("org.openas2.logging.defaultlog", "TRACE"); // executorService = Executors.newFixedThreadPool(20); RestApiTest.serverInstance = new OpenAS2Server.Builder() .run(RESOURCE.get("MyCompany", "config", "config.xml").getAbsolutePath()); } catch (Throwable e) { // aid for debugging JUnit tests System.err.println("ERROR occurred: " + ExceptionUtils.getStackTrace(e)); throw new Exception(e); } } @BeforeClass public static void startClient() throws Exception { RestApiTest.httpclient = HttpClients.createDefault(); } @AfterClass public static void tearDown() throws Exception { serverInstance.shutdown(); // executorService.shutdown(); System.clearProperty("openas2.properties.file"); scratchpad.delete(); httpclient.close(); } protected String doRequest(HttpRequestBase request,boolean withAuth) throws IOException { String buffer=""; HttpClientContext context = HttpClientContext.create(); if(withAuth) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("userID", "pWd"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, creds); context.setCredentialsProvider(credsProvider); } CloseableHttpResponse response = RestApiTest.httpclient.execute(request,context); try { HttpEntity entity = response.getEntity(); if (entity != null) { long len = entity.getContentLength(); if (len != -1 && len < 2048) { buffer=EntityUtils.toString(entity); } else { throw new RuntimeException("Response too long"); } } } finally { response.close(); } return buffer; } @Test public void shouldRespondWithVersion() throws Exception { String buffer=this.doRequest(new HttpGet("http://127.0.0.1:8080/api/"), false); assertThat("Getting API version and server info", buffer, containsString(serverInstance.getSession().getAppTitle())); buffer = this.doRequest(new HttpPost("http://127.0.0.1:8080/api/partner/list"),false); assertThat("Getting API without user/pass", buffer, containsString("You cannot access this resource")); // assertThat("Getting API without user/pass", buffer, containsString("You cannot access this resource")); // assertThat("Getting API without user/pass", buffer, containsString("You cannot access this resource")); // assertThat("Getting Partners API ", buffer, containsString("\"type\":\"OK\"")); // assertThat("Getting Partnership API ", buffer, containsString("\"type\":\"OK\"")); // assertThat("Getting Certs API ", buffer, containsString("\"type\":\"OK\"")); } }
package com.repay.android.adddebt; import java.math.BigDecimal; import java.util.ArrayList; import com.repay.android.model.Friend; import com.repay.android.R; import com.repay.android.database.DatabaseHandler; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.SQLException; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.provider.ContactsContract; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.Toast; public class ChoosePersonFragment extends DebtFragment implements OnItemClickListener, OnClickListener { private static final String TAG = ChoosePersonFragment.class.getName(); public static final int PICK_CONTACT_REQUEST = 1; private ChoosePersonAdapter mAdapter; private ListView mListView; private RelativeLayout mEmptyState; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); // Tell the activity that we have ActionBar items } /* * Here we add the extra menu items needed into the ActionBar. Even with * implementing this method, we still need to tell the Activity that we * have menu items to add */ @Override public void onCreateOptionsMenu(Menu menu,MenuInflater inf){ super.onCreateOptionsMenu(menu, inf); if(menu.size()<=1){ // Stops Activity from receiving duplicate MenuItems // Solves GitHub bug inf.inflate(R.menu.chooseperson, menu); } } private void showAddFriendDialog(){ AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()); dialog.setTitle(R.string.enter_friends_name); dialog.setItems(new CharSequence[]{"Add From Contacts", "Add A Name"}, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which==0){ Intent pickContactIntent = new Intent(Intent.ACTION_GET_CONTENT); pickContactIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE); startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST); } else if(which==1){ addFriendByName(); } } }); dialog.show(); } public void addFriendByName(){ AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()); dialog.setTitle(R.string.enter_friends_name); final EditText nameEntry = new EditText(getActivity()); dialog.setView(nameEntry); dialog.setPositiveButton(R.string.add, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String name = nameEntry.getText().toString(); try { if(!TextUtils.isEmpty(nameEntry.getText().toString())){ Friend newFriend = new Friend(DatabaseHandler.generateRepayID(), null, name, new BigDecimal("0")); ((DebtActivity) getActivity()).getDBHandler().addFriend(newFriend); } } catch (SQLException e) { Toast.makeText(getActivity(), "Friend could not be added", Toast.LENGTH_SHORT).show(); } } }); dialog.show(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data){ super.onActivityResult(requestCode, resultCode, data); if (data != null && resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST){ try{ Log.i(TAG,"Closing contact picker"); Uri contactUri = data.getData(); String[] cols = {ContactsContract.Contacts.DISPLAY_NAME}; Cursor cursor = getActivity().getContentResolver().query(contactUri, cols, null, null, null); cursor.moveToFirst(); String result = cursor.getString(0).replaceAll("[-+.^:,']",""); Friend pickerResult = new Friend(DatabaseHandler.generateRepayID(), contactUri.toString(), result, new BigDecimal("0")); ((DebtActivity) getActivity()).getDBHandler().addFriend(pickerResult); } catch (IndexOutOfBoundsException e) { Toast.makeText(getActivity(), "Problem in getting result from your contacts", Toast.LENGTH_SHORT).show(); } catch (SQLException e) { // TODO Change this. It's pretty crap. e.printStackTrace(); new AlertDialog.Builder(getActivity()) .setMessage("This person already exists in Repay") .setTitle("Person Already Exists").show(); } } } @Override public boolean onOptionsItemSelected(MenuItem item){ super.onOptionsItemSelected(item); switch (item.getItemId()) { case R.id.action_addfriend: showAddFriendDialog(); return true; default: return true; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_friendchooser, container, false); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mListView = (ListView)getView().findViewById(R.id.activity_friendchooser_list); mListView.setOnItemClickListener(this); mEmptyState = (RelativeLayout)getView().findViewById(R.id.activity_friendchooser_emptystate); (getView().findViewById(R.id.activity_friendchooser_helpbtn)).setOnClickListener(this); new GetFriendsFromDB().execute(); } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Friend selectedFriend = (Friend)arg1.getTag(); Log.i(TAG, selectedFriend.getName()+ " selected ("+ selectedFriend.getRepayID() +")"); if(((DebtActivity) getActivity()).getDebtBuilder().getSelectedFriends().contains(selectedFriend)){ ((DebtActivity) getActivity()).getDebtBuilder().removeSelectedFriend(selectedFriend); arg1.setBackgroundColor(ChoosePersonAdapter.DESELECTED_COLOUR); } else { ((DebtActivity) getActivity()).getDebtBuilder().getSelectedFriends().add(selectedFriend); arg1.setBackgroundColor(ChoosePersonAdapter.SELECTED_COLOUR); } } @Override public void saveFields() { // No need to do anything here. This fragment uses the DebtBuilder object as storage. } private class GetFriendsFromDB extends AsyncTask<DatabaseHandler, Integer, ArrayList<Friend>> { @Override protected void onPreExecute() { mListView.setVisibility(ListView.INVISIBLE); mEmptyState.setVisibility(RelativeLayout.INVISIBLE); } @Override protected ArrayList<Friend> doInBackground(DatabaseHandler... params) { try{ ArrayList<Friend> friends = ((DebtActivity) getActivity()).getDBHandler().getAllFriends(); return friends; } catch (Throwable e){ return null; } } @Override protected void onPostExecute(ArrayList<Friend> result){ if (result != null) { mListView.setVisibility(ListView.VISIBLE); mAdapter = new ChoosePersonAdapter(getActivity(), R.layout.fragment_adddebt_friendslist_item, result, ((DebtActivity) getActivity()).getDebtBuilder().getSelectedFriends()); mListView.setAdapter(mAdapter); mAdapter.setSelectedFriends(((DebtActivity) getActivity()).getDebtBuilder().getSelectedFriends()); } else { mEmptyState.setVisibility(RelativeLayout.VISIBLE); } } } @Override public void onClick(View v) { if (v.getId()==R.id.activity_friendchooser_helpbtn) { showAddFriendDialog(); } } }
package adf.component.algorithm.cluster; import adf.agent.info.AgentInfo; import adf.agent.info.ScenarioInfo; import adf.agent.info.WorldInfo; import rescuecore2.standard.entities.StandardEntity; import rescuecore2.standard.entities.StandardEntityURN; import rescuecore2.worldmodel.EntityID; import java.util.Collection; public abstract class Clustering{ protected WorldInfo worldInfo; protected AgentInfo agentInfo; protected ScenarioInfo scenarioInfo; protected int clusterSize; protected Collection<StandardEntity> entityIDs; public Clustering(WorldInfo wi, AgentInfo ai, ScenarioInfo si, Collection<StandardEntity> elements) { this(wi, ai, si, elements, -1); } public Clustering(WorldInfo wi, AgentInfo ai, ScenarioInfo si, Collection<StandardEntity> elements, int size) { this.worldInfo = wi; this.agentInfo = ai; this.scenarioInfo = si; this.clusterSize = size; this.entityIDs = elements; } public Clustering calc() { return this; } public abstract int getClusterNumber(); public abstract int getClusterIndex(EntityID id); public abstract Collection<StandardEntity> getClusterEntities(int index); }
package org.openlmis.functional; import cucumber.api.java.After; import cucumber.api.java.Before; import cucumber.api.java.en.And; import cucumber.api.java.en.Then; import org.openlmis.UiUtils.CaptureScreenshotOnFailureListener; import org.openlmis.UiUtils.TestCaseHelper; import org.openlmis.UiUtils.TestWebDriver; import org.openlmis.pageobjects.ConvertOrderPage; import org.openlmis.pageobjects.HomePage; import org.openlmis.pageobjects.LoginPage; import org.openlmis.pageobjects.ViewOrdersPage; import org.openqa.selenium.ElementNotVisibleException; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import org.testng.annotations.*; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue; import static com.thoughtworks.selenium.SeleneseTestNgHelper.assertEquals; @TransactionConfiguration(defaultRollback = true) @Transactional @Listeners(CaptureScreenshotOnFailureListener.class) public class ConvertToOrderPagination extends TestCaseHelper { @BeforeMethod(groups = "requisition") @Before public void setUp() throws Exception { super.setup(); } @And("^I have \"([^\"]*)\" requisitions for convert to order$") public void haveRequisitionsToBeConvertedToOrder(String requisitions) throws IOException, SQLException { String userSIC = "storeIncharge"; setUpData("HIV", userSIC); dbWrapper.insertRequisitions(Integer.parseInt(requisitions), "MALARIA", true); dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "MALARIA"); dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "MALARIA"); dbWrapper.insertFulfilmentRoleAssignment(userSIC, "store in-charge", "F10"); } @And("^I select \"([^\"]*)\" requisition on page \"([^\"]*)\"$") public void selectRequisition(String numberOfRequisitions, String page) throws IOException, SQLException { testWebDriver.sleep(5000); testWebDriver.handleScrollByPixels(0, 1000); String url = ((JavascriptExecutor) TestWebDriver.getDriver()).executeScript("return window.location.href").toString(); url = url.substring(0, url.length() - 1) + page; testWebDriver.getUrl(url); selectRequisitionToBeConvertedToOrder(Integer.parseInt(numberOfRequisitions)); } @And("^I access convert to order$") public void accessConvertToOrder() throws IOException, SQLException { ConvertOrderPage convertOrderPage = new ConvertOrderPage(testWebDriver); convertToOrder(convertOrderPage); } @Then("^\"([^\"]*)\" requisition converted to order$") public void requisitionConvertedToOrder(String requisitions) throws IOException, SQLException { HomePage homePage = new HomePage(testWebDriver); ViewOrdersPage viewOrdersPage = homePage.navigateViewOrders(); int numberOfLineItems = viewOrdersPage.getNumberOfLineItems(); assertTrue("Number of line items on view order screen should be equal to " + Integer.parseInt(requisitions), numberOfLineItems == Integer.parseInt(requisitions)); } @Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function-Positive") public void shouldConvertOnlyCurrentPageRequisitions(String program, String userSIC, String password) throws Exception { setUpData(program, userSIC); dbWrapper.insertRequisitions(50, "MALARIA", true); dbWrapper.insertRequisitions(1, "TB", true); dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "MALARIA"); dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "TB"); dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "MALARIA"); dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "TB"); dbWrapper.insertFulfilmentRoleAssignment("storeIncharge", "store in-charge", "F10"); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); HomePage homePage = loginPage.loginAs(userSIC, password); ConvertOrderPage convertOrderPage = homePage.navigateConvertToOrder(); verifyNumberOfPageLinks(51, 50); verifyNextAndLastLinksEnabled(); verifyPreviousAndFirstLinksDisabled(); clickPageNumberLink(2); verifyPageLinksFromLastPage(); verifyPreviousAndFirstLinksEnabled(); verifyNextAndLastLinksDisabled(); selectRequisitionToBeConvertedToOrder(1); clickPageNumberLink(1); selectRequisitionToBeConvertedToOrder(1); convertToOrder(convertOrderPage); verifyNumberOfPageLinks(49, 50); ViewOrdersPage viewOrdersPage = homePage.navigateViewOrders(); int numberOfLineItems = viewOrdersPage.getNumberOfLineItems(); assertTrue("Number of line items on view order screen should be equal to 1", numberOfLineItems == 1); viewOrdersPage.verifyProgram(1, "MALARIA"); } private void clickPageNumberLink(int pageNumber) { testWebDriver.getElementByXpath("//a[contains(text(), '" + pageNumber + "') and @class='ng-binding']").click(); testWebDriver.sleep(2000); } @Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function-Positive") public void shouldVerifyIntroductionOfPagination(String program, String userSIC, String password) throws Exception { setUpData(program, userSIC); dbWrapper.insertRequisitions(49, "MALARIA", true); dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "MALARIA"); dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "MALARIA"); dbWrapper.insertFulfilmentRoleAssignment("storeIncharge", "store in-charge", "F10"); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); HomePage homePage = loginPage.loginAs(userSIC, password); homePage.navigateConvertToOrder(); verifyNumberOfPageLinks(49, 50); dbWrapper.insertRequisitions(2, "HIV", true); dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "HIV"); dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "HIV"); homePage.navigateHomePage(); homePage.navigateConvertToOrder(); verifyNumberOfPageLinks(51, 50); } @Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function-Positive") public void shouldVerifyIntroductionOfPaginationForBoundaryValue(String program, String userSIC, String password) throws Exception { setUpData(program, userSIC); dbWrapper.insertRequisitions(50, "MALARIA", true); dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "MALARIA"); dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "MALARIA"); dbWrapper.insertFulfilmentRoleAssignment("storeIncharge", "store in-charge", "F10"); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); HomePage homePage = loginPage.loginAs(userSIC, password); homePage.navigateConvertToOrder(); verifyNumberOfPageLinks(50, 50); verifyPageLinkNotPresent(2); dbWrapper.insertRequisitions(1, "HIV", true); dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "HIV"); dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "HIV"); homePage.navigateHomePage(); homePage.navigateConvertToOrder(); verifyNumberOfPageLinks(51, 50); } @Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function-Positive") public void shouldVerifySearch(String program, String userSIC, String password) throws Exception { setUpData(program, userSIC); dbWrapper.insertRequisitions(55, "MALARIA", true); dbWrapper.insertRequisitions(40, "TB", true); dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "MALARIA"); dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "TB"); dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "MALARIA"); dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "TB"); dbWrapper.insertFulfilmentRoleAssignment("storeIncharge", "store in-charge", "F10"); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); HomePage homePage = loginPage.loginAs(userSIC, password); ConvertOrderPage convertOrderPage = homePage.navigateConvertToOrder(); verifyNumberOfPageLinks(80, 50); convertOrderPage.searchWithOption("All", "TB"); verifyNumberOfPageLinks(40, 50); verifyProgramInGrid(40, 50, "TB"); verifyPageLinkNotPresent(2); convertOrderPage.searchWithOption("All", "MALARIA"); verifyNumberOfPageLinks(55, 50); verifyProgramInGrid(55, 50, "MALARIA"); } @Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function-Positive") public void shouldVerifySearchWithDifferentOptions(String program, String userSIC, String password) throws Exception { setUpData(program, userSIC); dbWrapper.insertRequisitions(55, "MALARIA", true); dbWrapper.insertRequisitions(40, "TB", false); dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "MALARIA"); dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "TB"); dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "MALARIA"); dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "TB"); dbWrapper.insertFulfilmentRoleAssignment("storeIncharge", "store in-charge", "F10"); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); HomePage homePage = loginPage.loginAs(userSIC, password); ConvertOrderPage convertOrderPage = homePage.navigateConvertToOrder(); convertOrderPage.searchWithIndex(5, "Village Dispensary"); verifyNumberOfPageLinks(55, 50); verifySupplyingDepotInGrid(55, 50, "Village Dispensary"); } private void setUpData(String program, String userSIC) throws SQLException, IOException { setupProductTestData("P10", "P11", program, "Lvl3 Hospital"); dbWrapper.insertFacilities("F10", "F11"); dbWrapper.configureTemplate(program); List<String> rightsList = new ArrayList<String>(); rightsList.add("CONVERT_TO_ORDER"); rightsList.add("VIEW_ORDER"); setupTestUserRoleRightsData("200", userSIC, rightsList); dbWrapper.insertSupervisoryNode("F10", "N1", "Node 1", "null"); dbWrapper.insertRoleAssignment("200", "store in-charge"); dbWrapper.insertSchedule("Q1stM", "QuarterMonthly", "QuarterMonth"); dbWrapper.insertSchedule("M", "Monthly", "Month"); dbWrapper.insertProcessingPeriod("Period1", "first period", "2012-12-01", "2013-01-15", 1, "Q1stM"); dbWrapper.insertProcessingPeriod("Period2", "second period", "2013-01-16", "2013-01-30", 1, "M"); setupRequisitionGroupData("RG1", "RG2", "N1", "N2", "F10", "F11"); dbWrapper.insertSupplyLines("N1", program, "F10", true); } public void selectRequisitionToBeConvertedToOrder(int whichRequisition) { testWebDriver.waitForPageToLoad(); List <WebElement> x= testWebDriver.getElementsByXpath("//input[@class='ngSelectionCheckbox']"); testWebDriver.waitForElementToAppear(x.get(whichRequisition - 1)); x.get(whichRequisition-1).click(); } private void convertToOrder(ConvertOrderPage convertOrderPage) { convertOrderPage.clickConvertToOrderButton(); convertOrderPage.clickOk(); } public void verifyProgramInGrid(int numberOfProducts, int numberOfLineItemsPerPage, String program) throws Exception { int numberOfPages = numberOfProducts / numberOfLineItemsPerPage; if (numberOfProducts % numberOfLineItemsPerPage != 0) { numberOfPages = numberOfPages + 1; } int trackPages = 0; while (numberOfPages != trackPages) { testWebDriver.getElementByXpath("//a[contains(text(), '" + (trackPages + 1) + "') and @class='ng-binding']").click(); testWebDriver.waitForPageToLoad(); for (int i = 1; i < testWebDriver.getElementsSizeByXpath("//div[@class='ngCanvas']/div"); i++) assertEquals(testWebDriver.getElementByXpath("//div[@class='ngCanvas']/div[" + i + "]/div[2]/div[2]/div/span").getText().trim(), program); trackPages++; } } public void verifySupplyingDepotInGrid(int numberOfProducts, int numberOfLineItemsPerPage, String supplyingDepot) throws Exception { int numberOfPages = numberOfProducts / numberOfLineItemsPerPage; if (numberOfProducts % numberOfLineItemsPerPage != 0) { numberOfPages = numberOfPages + 1; } int trackPages = 0; while (numberOfPages != trackPages) { testWebDriver.getElementByXpath("//a[contains(text(), '" + (trackPages + 1) + "') and @class='ng-binding']").click(); testWebDriver.waitForPageToLoad(); for (int i = 1; i < testWebDriver.getElementsSizeByXpath("//div[@class='ngCanvas']/div"); i++) assertEquals(testWebDriver.getElementByXpath("//div[@class='ngCanvas']/div[" + i + "]/div[9]/div[2]/div/span").getText().trim(), supplyingDepot); trackPages++; } } public void verifyPageLinkNotPresent(int i) throws Exception { boolean flag = false; try { testWebDriver.getElementByXpath("//a[contains(text(), '" + i + "') and @class='ng-binding']").click(); } catch (NoSuchElementException e) { flag = true; } catch (ElementNotVisibleException e) { flag = true; } assertTrue("Link number" + i + " should not appear", flag); } @Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function-Positive") public void VerifyConvertToOrderAccessOnRequisition(String program, String userSIC, String password) throws Exception { setUpData(program, userSIC); dbWrapper.insertRequisitions(50, "MALARIA", true); dbWrapper.insertRequisitions(1, "TB", true); dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "MALARIA"); dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "TB"); dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "MALARIA"); dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "TB"); dbWrapper.insertFulfilmentRoleAssignment("storeIncharge", "store in-charge", "F10"); dbWrapper.updateSupplyLines("F10", "F11"); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); HomePage homePage = loginPage.loginAs(userSIC, password); ConvertOrderPage convertOrderPage = homePage.navigateConvertToOrder(); assertEquals("No requisitions to be converted to orders", convertOrderPage.getNoRequisitionPendingMessage()); } @AfterMethod(groups = "requisition") @After public void tearDown() throws Exception { testWebDriver.sleep(500); if (!testWebDriver.getElementById("username").isDisplayed()) { HomePage homePage = new HomePage(testWebDriver); homePage.logout(baseUrlGlobal); dbWrapper.deleteData(); dbWrapper.closeConnection(); } } @DataProvider(name = "Data-Provider-Function-Positive") public Object[][] parameterIntTestProviderPositive() { return new Object[][]{ {"HIV", "storeIncharge", "Admin123"} }; } }
package org.jfree.experimental.swt; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.Image; import java.awt.Paint; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.RenderingHints.Key; import java.awt.Shape; import java.awt.Stroke; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.geom.AffineTransform; import java.awt.geom.PathIterator; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.awt.image.ImageObserver; import java.awt.image.RenderedImage; import java.awt.image.renderable.RenderableImage; import java.text.AttributedCharacterIterator; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.Path; import org.eclipse.swt.graphics.Resource; import org.eclipse.swt.graphics.Transform; import org.jfree.chart.util.ParamChecks; /** * This is a class utility to draw Graphics2D stuff on a swt composite. * It is presently developed to use JFreeChart with the Standard * Widget Toolkit but may be of a wider use later. */ public class SWTGraphics2D extends Graphics2D { /** The swt graphic composite */ private GC gc; /** * The rendering hints. For now, these are not used, but at least the * basic mechanism is present. */ private RenderingHints hints; /** A reference to the compositing rule to apply. This is necessary * due to the poor compositing interface of the SWT toolkit. */ private java.awt.Composite composite; /** A HashMap to store the Swt color resources. */ private Map colorsPool = new HashMap(); /** A HashMap to store the Swt font resources. */ private Map fontsPool = new HashMap(); /** A HashMap to store the Swt transform resources. */ private Map transformsPool = new HashMap(); /** A List to store the Swt resources. */ private List resourcePool = new ArrayList(); /** * Creates a new instance. * * @param gc the graphics context. */ public SWTGraphics2D(GC gc) { super(); this.gc = gc; this.hints = new RenderingHints(null); this.composite = AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f); } /** * Not implemented yet - see {@link Graphics#create()}. * * @return <code>null</code>. */ public Graphics create() { // TODO Auto-generated method stub return null; } /** * Not implemented yet - see {@link Graphics2D#getDeviceConfiguration()}. * * @return <code>null</code>. */ public GraphicsConfiguration getDeviceConfiguration() { // TODO Auto-generated method stub return null; } /** * Returns the current value for the specified hint key, or * <code>null</code> if no value is set. * * @param hintKey the hint key (<code>null</code> permitted). * * @return The hint value, or <code>null</code>. * * @see #setRenderingHint(RenderingHints.Key, Object) */ public Object getRenderingHint(Key hintKey) { return this.hints.get(hintKey); } public void setRenderingHint(Key hintKey, Object hintValue) { this.hints.put(hintKey, hintValue); } /** * Returns a copy of the hints collection for this graphics context. * * @return A copy of the hints collection. */ public RenderingHints getRenderingHints() { return (RenderingHints) this.hints.clone(); } /** * Adds the hints in the specified map to the graphics context, replacing * any existing hints. For now, this graphics context ignores all hints. * * @param hints the hints (<code>null</code> not permitted). * * @see #setRenderingHints(Map) */ public void addRenderingHints(Map hints) { this.hints.putAll(hints); } /** * Replaces the existing hints with those contained in the specified * map. Note that, for now, this graphics context ignores all hints. * * @param hints the hints (<code>null</code> not permitted). * * @see #addRenderingHints(Map) */ public void setRenderingHints(Map hints) { if (hints == null) { throw new NullPointerException("Null 'hints' argument."); } this.hints = new RenderingHints(hints); } /** * Returns the current paint for this graphics context. * * @return The current paint. * * @see #setPaint(Paint) */ public Paint getPaint() { // TODO: it might be a good idea to keep a reference to the color // specified in setPaint() or setColor(), rather than creating a // new object every time getPaint() is called. return SWTUtils.toAwtColor(this.gc.getForeground()); } /** * Sets the paint for this graphics context. For now, this graphics * context only supports instances of {@link Color} or * {@link GradientPaint} (in the latter case there is no real gradient * support, the paint used is the <code>Color</code> returned by * <code>getColor1()</code>). * * @param paint the paint (<code>null</code> not permitted). * * @see #getPaint() * @see #setColor(Color) */ public void setPaint(Paint paint) { if (paint instanceof Color) { setColor((Color) paint); } else if (paint instanceof GradientPaint) { GradientPaint gp = (GradientPaint) paint; setColor(gp.getColor1()); } else { throw new RuntimeException("Can only handle 'Color' at present."); } } /** * Returns the current color for this graphics context. * * @return The current color. * * @see #setColor(Color) */ public Color getColor() { // TODO: it might be a good idea to keep a reference to the color // specified in setPaint() or setColor(), rather than creating a // new object every time getPaint() is called. return SWTUtils.toAwtColor(this.gc.getForeground()); } /** * Sets the current color for this graphics context. * * @param color the color. * * @see #getColor() */ public void setColor(Color color) { org.eclipse.swt.graphics.Color swtColor = getSwtColorFromPool(color); this.gc.setForeground(swtColor); // handle transparency and compositing. if (this.composite instanceof AlphaComposite) { AlphaComposite acomp = (AlphaComposite) this.composite; switch (acomp.getRule()) { case AlphaComposite.SRC_OVER: this.gc.setAlpha((int) (color.getAlpha() * acomp.getAlpha())); break; default: this.gc.setAlpha(color.getAlpha()); break; } } } /** * Sets the background colour. * * @param color the colour. */ public void setBackground(Color color) { org.eclipse.swt.graphics.Color swtColor = getSwtColorFromPool(color); this.gc.setBackground(swtColor); } /** * Returns the background colour. * * @return The background colour. */ public Color getBackground() { return SWTUtils.toAwtColor(this.gc.getBackground()); } /** * Not implemented - see {@link Graphics#setPaintMode()}. */ public void setPaintMode() { // TODO Auto-generated method stub } /** * Not implemented - see {@link Graphics#setXORMode(Color)}. * * @param color the colour. */ public void setXORMode(Color color) { // TODO Auto-generated method stub } /** * Returns the current composite. * * @return The current composite. * * @see #setComposite(Composite) */ public Composite getComposite() { return this.composite; } /** * Sets the current composite. This implementation currently supports * only the {@link AlphaComposite} class. * * @param comp the composite. */ public void setComposite(Composite comp) { this.composite = comp; if (comp instanceof AlphaComposite) { AlphaComposite acomp = (AlphaComposite) comp; int alpha = (int) (acomp.getAlpha() * 0xFF); this.gc.setAlpha(alpha); } else { System.out.println("warning, can only handle alpha composite at the moment."); } } /** * Returns the current stroke for this graphics context. * * @return The current stroke. * * @see #setStroke(Stroke) */ public Stroke getStroke() { return new BasicStroke(this.gc.getLineWidth(), toAwtLineCap(this.gc.getLineCap()), toAwtLineJoin(this.gc.getLineJoin())); } /** * Sets the stroke for this graphics context. For now, this implementation * only recognises the {@link BasicStroke} class. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getStroke() */ public void setStroke(Stroke stroke) { if (stroke instanceof BasicStroke) { BasicStroke bs = (BasicStroke) stroke; this.gc.setLineWidth((int) bs.getLineWidth()); this.gc.setLineJoin(toSwtLineJoin(bs.getLineJoin())); this.gc.setLineCap(toSwtLineCap(bs.getEndCap())); // set the line style to solid by default this.gc.setLineStyle(SWT.LINE_SOLID); // apply dash style if any float[] dashes = bs.getDashArray(); if (dashes != null) { int[] swtDashes = new int[dashes.length]; for (int i = 0; i < swtDashes.length; i++) { swtDashes[i] = (int) dashes[i]; } this.gc.setLineDash(swtDashes); } } else { throw new RuntimeException( "Can only handle 'Basic Stroke' at present."); } } /** * Applies the specified clip. * * @param s the shape for the clip. */ public void clip(Shape s) { Path path = toSwtPath(s); this.gc.setClipping(path); path.dispose(); } /** * Returns the clip bounds. * * @return The clip bounds. */ public Rectangle getClipBounds() { org.eclipse.swt.graphics.Rectangle clip = this.gc.getClipping(); return new Rectangle(clip.x, clip.y, clip.width, clip.height); } /** * Sets the clipping to the intersection of the current clip region and * the specified rectangle. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. */ public void clipRect(int x, int y, int width, int height) { org.eclipse.swt.graphics.Rectangle clip = this.gc.getClipping(); clip.intersects(x, y, width, height); this.gc.setClipping(clip); } /** * Returns the current clip. * * @return The current clip. */ public Shape getClip() { return SWTUtils.toAwtRectangle(this.gc.getClipping()); } /** * Sets the clip region. * * @param clip the clip. */ public void setClip(Shape clip) { if (clip == null) { return; } Path clipPath = toSwtPath(clip); this.gc.setClipping(clipPath); clipPath.dispose(); } /** * Sets the clip region to the specified rectangle. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. */ public void setClip(int x, int y, int width, int height) { this.gc.setClipping(x, y, width, height); } /** * Returns the current transform. * * @return The current transform. */ public AffineTransform getTransform() { Transform swtTransform = new Transform(this.gc.getDevice()); this.gc.getTransform(swtTransform); AffineTransform awtTransform = toAwtTransform(swtTransform); swtTransform.dispose(); return awtTransform; } /** * Sets the current transform. * * @param t the transform. */ public void setTransform(AffineTransform t) { Transform transform = getSwtTransformFromPool(t); this.gc.setTransform(transform); } /** * Concatenates the specified transform to the existing transform. * * @param t the transform. */ public void transform(AffineTransform t) { Transform swtTransform = new Transform(this.gc.getDevice()); this.gc.getTransform(swtTransform); swtTransform.multiply(getSwtTransformFromPool(t)); this.gc.setTransform(swtTransform); swtTransform.dispose(); } /** * Applies a translation. * * @param x the translation along the x-axis. * @param y the translation along the y-axis. */ public void translate(int x, int y) { Transform swtTransform = new Transform(this.gc.getDevice()); this.gc.getTransform(swtTransform); swtTransform.translate(x, y); this.gc.setTransform(swtTransform); swtTransform.dispose(); } /** * Applies a translation. * * @param tx the translation along the x-axis. * @param ty the translation along the y-axis. */ public void translate(double tx, double ty) { translate((int) tx, (int) ty); } /** * Applies a rotation transform. * * @param theta the angle of rotation. */ public void rotate(double theta) { Transform swtTransform = new Transform(this.gc.getDevice()); this.gc.getTransform(swtTransform); swtTransform.rotate((float) (theta * 180 / Math.PI)); this.gc.setTransform(swtTransform); swtTransform.dispose(); } /** * Not implemented - see {@link Graphics2D#rotate(double, double, double)}. * * @see java.awt.Graphics2D#rotate(double, double, double) */ public void rotate(double theta, double x, double y) { // TODO Auto-generated method stub } /** * Applies a scale transform. * * @param scaleX the scale factor along the x-axis. * @param scaleY the scale factor along the y-axis. */ public void scale(double scaleX, double scaleY) { Transform swtTransform = new Transform(this.gc.getDevice()); this.gc.getTransform(swtTransform); swtTransform.scale((float) scaleX, (float) scaleY); this.gc.setTransform(swtTransform); swtTransform.dispose(); } /** * Applies a shear transform. * * @param shearX the x-factor. * @param shearY the y-factor. */ public void shear(double shearX, double shearY) { Transform swtTransform = new Transform(this.gc.getDevice()); this.gc.getTransform(swtTransform); Transform shear = new Transform(this.gc.getDevice(), 1f, (float) shearX, (float) shearY, 1f, 0, 0); swtTransform.multiply(shear); this.gc.setTransform(swtTransform); swtTransform.dispose(); } /** * Draws the outline of the specified shape using the current stroke and * paint settings. * * @param shape the shape (<code>null</code> not permitted). * * @see #getPaint() * @see #getStroke() * @see #fill(Shape) */ public void draw(Shape shape) { Path path = toSwtPath(shape); this.gc.drawPath(path); path.dispose(); } /** * Draws a line from (x1, y1) to (x2, y2) using the current stroke * and paint settings. * * @param x1 the x-coordinate for the starting point. * @param y1 the y-coordinate for the starting point. * @param x2 the x-coordinate for the ending point. * @param y2 the y-coordinate for the ending point. * * @see #draw(Shape) */ public void drawLine(int x1, int y1, int x2, int y2) { this.gc.drawLine(x1, y1, x2, y2); } /** * Draws the outline of the polygon specified by the given points, using * the current paint and stroke settings. * * @param xPoints the x-coordinates. * @param yPoints the y-coordinates. * @param npoints the number of points in the polygon. * * @see #draw(Shape) */ public void drawPolygon(int [] xPoints, int [] yPoints, int npoints) { drawPolyline(xPoints, yPoints, npoints); if (npoints > 1) { this.gc.drawLine(xPoints[npoints - 1], yPoints[npoints - 1], xPoints[0], yPoints[0]); } } /** * Draws a sequence of connected lines specified by the given points, using * the current paint and stroke settings. * * @param xPoints the x-coordinates. * @param yPoints the y-coordinates. * @param npoints the number of points in the polygon. * * @see #draw(Shape) */ public void drawPolyline(int [] xPoints, int [] yPoints, int npoints) { if (npoints > 1) { int x0 = xPoints[0]; int y0 = yPoints[0]; int x1 = 0, y1 = 0; for (int i = 1; i < npoints; i++) { x1 = xPoints[i]; y1 = yPoints[i]; this.gc.drawLine(x0, y0, x1, y1); x0 = x1; y0 = y1; } } } /** * Draws an oval that fits within the specified rectangular region. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the frame width. * @param height the frame height. * * @see #fillOval(int, int, int, int) * @see #draw(Shape) */ public void drawOval(int x, int y, int width, int height) { this.gc.drawOval(x, y, width - 1, height - 1); } /** * Draws an arc that is part of an ellipse that fits within the specified * framing rectangle. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the frame width. * @param height the frame height. * @param arcStart the arc starting point, in degrees. * @param arcAngle the extent of the arc. * * @see #fillArc(int, int, int, int, int, int) */ public void drawArc(int x, int y, int width, int height, int arcStart, int arcAngle) { this.gc.drawArc(x, y, width - 1, height - 1, arcStart, arcAngle); } /** * Draws a rectangle with rounded corners that fits within the specified * framing rectangle. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the frame width. * @param height the frame height. * @param arcWidth the width of the arc defining the roundedness of the * rectangle's corners. * @param arcHeight the height of the arc defining the roundedness of the * rectangle's corners. * * @see #fillRoundRect(int, int, int, int, int, int) */ public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { this.gc.drawRoundRectangle(x, y, width - 1, height - 1, arcWidth, arcHeight); } /** * Fills the specified shape using the current paint. * * @param shape the shape (<code>null</code> not permitted). * * @see #getPaint() * @see #draw(Shape) */ public void fill(Shape shape) { Path path = toSwtPath(shape); // Note that for consistency with the AWT implementation, it is // necessary to switch temporarily the foreground and background // colours switchColors(); this.gc.fillPath(path); switchColors(); path.dispose(); } /** * Fill a rectangle area on the swt graphic composite. * The <code>fillRectangle</code> method of the <code>GC</code> * class uses the background color so we must switch colors. * @see java.awt.Graphics#fillRect(int, int, int, int) */ public void fillRect(int x, int y, int width, int height) { this.switchColors(); this.gc.fillRectangle(x, y, width, height); this.switchColors(); } /** * Fills the specified rectangle with the current background colour. * * @param x the x-coordinate for the rectangle. * @param y the y-coordinate for the rectangle. * @param width the width. * @param height the height. * * @see #fillRect(int, int, int, int) */ public void clearRect(int x, int y, int width, int height) { Paint saved = getPaint(); setPaint(getBackground()); fillRect(x, y, width, height); setPaint(saved); } /** * Fills the specified polygon. * * @param xPoints the x-coordinates. * @param yPoints the y-coordinates. * @param npoints the number of points. */ public void fillPolygon(int[] xPoints, int[] yPoints, int npoints) { int[] pointArray = new int[npoints * 2]; for (int i = 0; i < npoints; i++) { pointArray[2 * i] = xPoints[i]; pointArray[2 * i + 1] = yPoints[i]; } switchColors(); this.gc.fillPolygon(pointArray); switchColors(); } /** * Draws a rectangle with rounded corners that fits within the specified * framing rectangle. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the frame width. * @param height the frame height. * @param arcWidth the width of the arc defining the roundedness of the * rectangle's corners. * @param arcHeight the height of the arc defining the roundedness of the * rectangle's corners. * * @see #drawRoundRect(int, int, int, int, int, int) */ public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { switchColors(); this.gc.fillRoundRectangle(x, y, width - 1, height - 1, arcWidth, arcHeight); switchColors(); } /** * Fills an oval that fits within the specified rectangular region. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the frame width. * @param height the frame height. * * @see #drawOval(int, int, int, int) * @see #fill(Shape) */ public void fillOval(int x, int y, int width, int height) { switchColors(); this.gc.fillOval(x, y, width - 1, height - 1); switchColors(); } /** * Fills an arc that is part of an ellipse that fits within the specified * framing rectangle. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the frame width. * @param height the frame height. * @param arcStart the arc starting point, in degrees. * @param arcAngle the extent of the arc. * * @see #drawArc(int, int, int, int, int, int) */ public void fillArc(int x, int y, int width, int height, int arcStart, int arcAngle) { switchColors(); this.gc.fillArc(x, y, width - 1, height - 1, arcStart, arcAngle); switchColors(); } /** * Returns the font in form of an awt font created * with the parameters of the font of the swt graphic * composite. * @see java.awt.Graphics#getFont() */ public Font getFont() { // retrieve the swt font description in an os indept way FontData[] fontData = this.gc.getFont().getFontData(); // create a new awt font with the appropiate data return SWTUtils.toAwtFont(this.gc.getDevice(), fontData[0], true); } /** * Set the font swt graphic composite from the specified * awt font. Be careful that the newly created swt font * must be disposed separately. * @see java.awt.Graphics#setFont(java.awt.Font) */ public void setFont(Font font) { org.eclipse.swt.graphics.Font swtFont = getSwtFontFromPool(font); this.gc.setFont(swtFont); } /** * Returns the font metrics. * * @param font the font. * * @return The font metrics. */ public FontMetrics getFontMetrics(Font font) { return SWTUtils.DUMMY_PANEL.getFontMetrics(font); } /** * Returns the font render context. * * @return The font render context. */ public FontRenderContext getFontRenderContext() { FontRenderContext fontRenderContext = new FontRenderContext( new AffineTransform(), true, true); return fontRenderContext; } /** * Not implemented - see {@link Graphics2D#drawGlyphVector(GlyphVector, * float, float)}. */ public void drawGlyphVector(GlyphVector g, float x, float y) { // TODO Auto-generated method stub } /** * Draws a string on the receiver. note that * to be consistent with the awt method, * the y has to be modified with the ascent of the font. * * @see java.awt.Graphics#drawString(java.lang.String, int, int) */ public void drawString(String text, int x, int y) { float fm = this.gc.getFontMetrics().getAscent(); this.gc.drawString(text, x, (int) (y - fm), true); } /** * Draws a string at the specified position. * * @param text the string. * @param x the x-coordinate. * @param y the y-coordinate. */ public void drawString(String text, float x, float y) { float fm = this.gc.getFontMetrics().getAscent(); this.gc.drawString(text, (int) x, (int) (y - fm), true); } /** * Draws a string at the specified position. * * @param iterator the string. * @param x the x-coordinate. * @param y the y-coordinate. */ public void drawString(AttributedCharacterIterator iterator, int x, int y) { // for now we simply want to extract the chars from the iterator // and call an unstyled text renderer StringBuffer sb = new StringBuffer(); int numChars = iterator.getEndIndex() - iterator.getBeginIndex(); char c = iterator.first(); for (int i = 0; i < numChars; i++) { sb.append(c); c = iterator.next(); } drawString(new String(sb),x,y); } /** * Draws a string at the specified position. * * @param iterator the string. * @param x the x-coordinate. * @param y the y-coordinate. */ public void drawString(AttributedCharacterIterator iterator, float x, float y) { drawString(iterator, (int) x, (int) y); } /** * Not implemented - see {@link Graphics2D#hit(Rectangle, Shape, boolean)}. * * @return <code>false</code>. */ public boolean hit(Rectangle rect, Shape text, boolean onStroke) { // TODO Auto-generated method stub return false; } /** * Not implemented - see {@link Graphics#copyArea(int, int, int, int, int, * int)}. */ public void copyArea(int x, int y, int width, int height, int dx, int dy) { // TODO Auto-generated method stub } /** * Not implemented - see {@link Graphics2D#drawImage(Image, * AffineTransform, ImageObserver)}. * * @param image the image. * @param xform the transform. * @param obs an image observer. * * @return A boolean. */ public boolean drawImage(Image image, AffineTransform xform, ImageObserver obs) { // TODO Auto-generated method stub return false; } /** * Draws an image. * * @param image the image. * @param op the image operation. * @param x the x-coordinate. * @param y the y-coordinate. */ public void drawImage(BufferedImage image, BufferedImageOp op, int x, int y) { org.eclipse.swt.graphics.Image im = new org.eclipse.swt.graphics.Image( this.gc.getDevice(), SWTUtils.convertToSWT(image)); this.gc.drawImage(im, x, y); im.dispose(); } /** * Draws an SWT image with the top left corner of the image aligned to the * point (x, y). * * @param image the image. * @param x the x-coordinate. * @param y the y-coordinate. */ public void drawImage(org.eclipse.swt.graphics.Image image, int x, int y) { this.gc.drawImage(image, x, y); } /** * Not implemented - see {@link Graphics2D#drawRenderedImage(RenderedImage, * AffineTransform)}. * * @param image the image. * @param xform the transform. */ public void drawRenderedImage(RenderedImage image, AffineTransform xform) { // TODO Auto-generated method stub } /** * Not implemented - see {@link Graphics2D#drawRenderableImage( * RenderableImage, AffineTransform)}. * * @param image the image. * @param xform the transform. */ public void drawRenderableImage(RenderableImage image, AffineTransform xform) { // TODO Auto-generated method stub } /** * Draws an image with the top left corner aligned to the point (x, y). * * @param image the image. * @param x the x-coordinate. * @param y the y-coordinate. * @param observer ignored here. * * @return <code>true</code> if the image has been drawn. */ public boolean drawImage(Image image, int x, int y, ImageObserver observer) { ImageData data = SWTUtils.convertAWTImageToSWT(image); if (data == null) { return false; } org.eclipse.swt.graphics.Image im = new org.eclipse.swt.graphics.Image( this.gc.getDevice(), data); this.gc.drawImage(im, x, y); im.dispose(); return true; } /** * Draws an image with the top left corner aligned to the point (x, y), * and scaled to the specified width and height. * * @param image the image. * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width for the rendered image. * @param height the height for the rendered image. * @param observer ignored here. * * @return <code>true</code> if the image has been drawn. */ public boolean drawImage(Image image, int x, int y, int width, int height, ImageObserver observer) { ImageData data = SWTUtils.convertAWTImageToSWT(image); if (data == null) { return false; } org.eclipse.swt.graphics.Image im = new org.eclipse.swt.graphics.Image( this.gc.getDevice(), data); org.eclipse.swt.graphics.Rectangle bounds = im.getBounds(); this.gc.drawImage(im, 0, 0, bounds.width, bounds.height, x, y, width, height); im.dispose(); return true; } /** * Draws an image. * * @param image (<code>null</code> not permitted). * @param x the x-coordinate. * @param y the y-coordinate. * @param bgcolor the background color. * @param observer an image observer. * * @return A boolean. */ public boolean drawImage(Image image, int x, int y, Color bgcolor, ImageObserver observer) { ParamChecks.nullNotPermitted(image, "image"); int w = image.getWidth(null); int h = image.getHeight(null); if (w == -1 || h == -1) { return false; } Paint savedPaint = getPaint(); fill(new Rectangle2D.Double(x, y, w, h)); setPaint(savedPaint); return drawImage(image, x, y, observer); } /** * Draws an image. * * @param image the image (<code>null</code> not permitted). * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * @param bgcolor the background colour. * @param observer an image observer. * * @return A boolean. */ public boolean drawImage(Image image, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) { ParamChecks.nullNotPermitted(image, "image"); int w = image.getWidth(null); int h = image.getHeight(null); if (w == -1 || h == -1) { return false; } Paint savedPaint = getPaint(); fill(new Rectangle2D.Double(x, y, w, h)); setPaint(savedPaint); return drawImage(image, x, y, width, height, observer); } /** * Not implemented - see {@link Graphics#drawImage(Image, int, int, int, * int, int, int, int, int, ImageObserver)}. * * @param image the image. * @param dx1 * @param dy1 * @param dx2 * @param dy2 * @param sx1 * @param sy1 * @param sx2 * @param sy2 * @param observer */ public boolean drawImage(Image image, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) { // TODO Auto-generated method stub return false; } /** * Not implemented - see {@link Graphics#drawImage(Image, int, int, int, * int, int, int, int, int, Color, ImageObserver)}. * * @param image the image. * @param dx1 * @param dy1 * @param dx2 * @param dy2 * @param sx1 * @param sy1 * @param sx2 * @param sy2 * @param bgcolor * @param observer */ public boolean drawImage(Image image, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer) { // TODO Auto-generated method stub return false; } /** * Releases resources held by this instance (but note that the caller * must dispose of the 'GC' passed to the constructor). * * @see java.awt.Graphics#dispose() */ public void dispose() { // we dispose resources we own but user must dispose gc disposeResourcePool(); } /** * Add given swt resource to the resource pool. All resources added * to the resource pool will be disposed when {@link #dispose()} is called. * * @param resource the resource to add to the pool. * @return the swt <code>Resource</code> just added. */ private Resource addToResourcePool(Resource resource) { this.resourcePool.add(resource); return resource; } /** * Dispose the resource pool. */ private void disposeResourcePool() { for (Iterator it = this.resourcePool.iterator(); it.hasNext();) { Resource resource = (Resource) it.next(); resource.dispose(); } this.fontsPool.clear(); this.colorsPool.clear(); this.transformsPool.clear(); this.resourcePool.clear(); } /** * Internal method to convert a AWT font object into * a SWT font resource. If a corresponding SWT font * instance is already in the pool, it will be used * instead of creating a new one. This is used in * {@link #setFont()} for instance. * * @param font The AWT font to convert. * @return The SWT font instance. */ private org.eclipse.swt.graphics.Font getSwtFontFromPool(Font font) { org.eclipse.swt.graphics.Font swtFont = (org.eclipse.swt.graphics.Font) this.fontsPool.get(font); if (swtFont == null) { swtFont = new org.eclipse.swt.graphics.Font(this.gc.getDevice(), SWTUtils.toSwtFontData(this.gc.getDevice(), font, true)); addToResourcePool(swtFont); this.fontsPool.put(font, swtFont); } return swtFont; } /** * Internal method to convert a AWT color object into * a SWT color resource. If a corresponding SWT color * instance is already in the pool, it will be used * instead of creating a new one. This is used in * {@link #setColor()} for instance. * * @param awtColor The AWT color to convert. * @return A SWT color instance. */ private org.eclipse.swt.graphics.Color getSwtColorFromPool(Color awtColor) { org.eclipse.swt.graphics.Color swtColor = (org.eclipse.swt.graphics.Color) // we can't use the following valueOf() method, because it // won't compile with JDK1.4 // this.colorsPool.get(Integer.valueOf(awtColor.getRGB())); this.colorsPool.get(new Integer(awtColor.getRGB())); if (swtColor == null) { swtColor = SWTUtils.toSwtColor(this.gc.getDevice(), awtColor); addToResourcePool(swtColor); // see comment above //this.colorsPool.put(Integer.valueOf(awtColor.getRGB()), swtColor); this.colorsPool.put(new Integer(awtColor.getRGB()), swtColor); } return swtColor; } /** * Internal method to convert a AWT transform object into * a SWT transform resource. If a corresponding SWT transform * instance is already in the pool, it will be used * instead of creating a new one. This is used in * {@link #setTransform()} for instance. * * @param awtTransform The AWT transform to convert. * @return A SWT transform instance. */ private Transform getSwtTransformFromPool(AffineTransform awtTransform) { Transform t = (Transform) this.transformsPool.get(awtTransform); if (t == null) { t = new Transform(this.gc.getDevice()); double[] matrix = new double[6]; awtTransform.getMatrix(matrix); t.setElements((float) matrix[0], (float) matrix[1], (float) matrix[2], (float) matrix[3], (float) matrix[4], (float) matrix[5]); addToResourcePool(t); this.transformsPool.put(awtTransform, t); } return t; } /** * Perform a switch between foreground and background * color of gc. This is needed for consistency with * the awt behaviour, and is required notably for the * filling methods. */ private void switchColors() { org.eclipse.swt.graphics.Color bg = this.gc.getBackground(); org.eclipse.swt.graphics.Color fg = this.gc.getForeground(); this.gc.setBackground(fg); this.gc.setForeground(bg); } /** * Converts an AWT <code>Shape</code> into a SWT <code>Path</code>. * * @param shape the shape (<code>null</code> not permitted). * * @return The path. */ private Path toSwtPath(Shape shape) { int type; float[] coords = new float[6]; Path path = new Path(this.gc.getDevice()); PathIterator pit = shape.getPathIterator(null); while (!pit.isDone()) { type = pit.currentSegment(coords); switch (type) { case (PathIterator.SEG_MOVETO): path.moveTo(coords[0], coords[1]); break; case (PathIterator.SEG_LINETO): path.lineTo(coords[0], coords[1]); break; case (PathIterator.SEG_QUADTO): path.quadTo(coords[0], coords[1], coords[2], coords[3]); break; case (PathIterator.SEG_CUBICTO): path.cubicTo(coords[0], coords[1], coords[2], coords[3], coords[4], coords[5]); break; case (PathIterator.SEG_CLOSE): path.close(); break; default: break; } pit.next(); } return path; } /** * Converts an SWT transform into the equivalent AWT transform. * * @param swtTransform the SWT transform. * * @return The AWT transform. */ private AffineTransform toAwtTransform(Transform swtTransform) { float[] elements = new float[6]; swtTransform.getElements(elements); AffineTransform awtTransform = new AffineTransform(elements); return awtTransform; } /** * Returns the AWT line cap corresponding to the specified SWT line cap. * * @param swtLineCap the SWT line cap. * * @return The AWT line cap. */ private int toAwtLineCap(int swtLineCap) { if (swtLineCap == SWT.CAP_FLAT) { return BasicStroke.CAP_BUTT; } else if (swtLineCap == SWT.CAP_ROUND) { return BasicStroke.CAP_ROUND; } else if (swtLineCap == SWT.CAP_SQUARE) { return BasicStroke.CAP_SQUARE; } else { throw new IllegalArgumentException("SWT LineCap " + swtLineCap + " not recognised"); } } /** * Returns the AWT line join corresponding to the specified SWT line join. * * @param swtLineJoin the SWT line join. * * @return The AWT line join. */ private int toAwtLineJoin(int swtLineJoin) { if (swtLineJoin == SWT.JOIN_BEVEL) { return BasicStroke.JOIN_BEVEL; } else if (swtLineJoin == SWT.JOIN_MITER) { return BasicStroke.JOIN_MITER; } else if (swtLineJoin == SWT.JOIN_ROUND) { return BasicStroke.JOIN_ROUND; } else { throw new IllegalArgumentException("SWT LineJoin " + swtLineJoin + " not recognised"); } } /** * Returns the SWT line cap corresponding to the specified AWT line cap. * * @param awtLineCap the AWT line cap. * * @return The SWT line cap. */ private int toSwtLineCap(int awtLineCap) { if (awtLineCap == BasicStroke.CAP_BUTT) { return SWT.CAP_FLAT; } else if (awtLineCap == BasicStroke.CAP_ROUND) { return SWT.CAP_ROUND; } else if (awtLineCap == BasicStroke.CAP_SQUARE) { return SWT.CAP_SQUARE; } else { throw new IllegalArgumentException("AWT LineCap " + awtLineCap + " not recognised"); } } /** * Returns the SWT line join corresponding to the specified AWT line join. * * @param awtLineJoin the AWT line join. * * @return The SWT line join. */ private int toSwtLineJoin(int awtLineJoin) { if (awtLineJoin == BasicStroke.JOIN_BEVEL) { return SWT.JOIN_BEVEL; } else if (awtLineJoin == BasicStroke.JOIN_MITER) { return SWT.JOIN_MITER; } else if (awtLineJoin == BasicStroke.JOIN_ROUND) { return SWT.JOIN_ROUND; } else { throw new IllegalArgumentException("AWT LineJoin " + awtLineJoin + " not recognised"); } } }
package net.runelite.client.game; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import java.util.Collection; import javax.annotation.Nullable; import lombok.Getter; import static net.runelite.api.ItemID.*; /** * Converts untradeable items to it's tradeable counterparts */ @Getter public enum ItemMapping { // Barrows equipment ITEM_AHRIMS_HOOD(AHRIMS_HOOD, AHRIMS_HOOD_25, AHRIMS_HOOD_50, AHRIMS_HOOD_75, AHRIMS_HOOD_100), ITEM_AHRIMS_ROBETOP(AHRIMS_ROBETOP, AHRIMS_ROBETOP_25, AHRIMS_ROBETOP_50, AHRIMS_ROBETOP_75, AHRIMS_ROBETOP_100), ITEM_AHRIMS_ROBEBOTTOM(AHRIMS_ROBESKIRT, AHRIMS_ROBESKIRT_25, AHRIMS_ROBESKIRT_50, AHRIMS_ROBESKIRT_75, AHRIMS_ROBESKIRT_100), ITEM_AHRIMS_STAFF(AHRIMS_STAFF, AHRIMS_STAFF_25, AHRIMS_STAFF_50, AHRIMS_STAFF_75, AHRIMS_STAFF_100), ITEM_KARILS_COIF(KARILS_COIF, KARILS_COIF_25, KARILS_COIF_50, KARILS_COIF_75, KARILS_COIF_100), ITEM_KARILS_LEATHERTOP(KARILS_LEATHERTOP, KARILS_LEATHERTOP_25, KARILS_LEATHERTOP_50, KARILS_LEATHERTOP_75, KARILS_LEATHERTOP_100), ITEM_KARILS_LEATHERSKIRT(KARILS_LEATHERSKIRT, KARILS_LEATHERSKIRT_25, KARILS_LEATHERSKIRT_50, KARILS_LEATHERSKIRT_75, KARILS_LEATHERSKIRT_100), ITEM_KARILS_CROSSBOW(KARILS_CROSSBOW, KARILS_CROSSBOW_25, KARILS_CROSSBOW_50, KARILS_CROSSBOW_75, KARILS_CROSSBOW_100), ITEM_DHAROKS_HELM(DHAROKS_HELM, DHAROKS_HELM_25, DHAROKS_HELM_50, DHAROKS_HELM_75, DHAROKS_HELM_100), ITEM_DHAROKS_PLATEBODY(DHAROKS_PLATEBODY, DHAROKS_PLATEBODY_25, DHAROKS_PLATEBODY_50, DHAROKS_PLATEBODY_75, DHAROKS_PLATEBODY_100), ITEM_DHAROKS_PLATELEGS(DHAROKS_PLATELEGS, DHAROKS_PLATELEGS_25, DHAROKS_PLATELEGS_50, DHAROKS_PLATELEGS_75, DHAROKS_PLATELEGS_100), ITEM_DHARKS_GREATEAXE(DHAROKS_GREATAXE, DHAROKS_GREATAXE_25, DHAROKS_GREATAXE_50, DHAROKS_GREATAXE_75, DHAROKS_GREATAXE_100), ITEM_GUTHANS_HELM(GUTHANS_HELM, GUTHANS_HELM_25, GUTHANS_HELM_50, GUTHANS_HELM_75, GUTHANS_HELM_100), ITEM_GUTHANS_PLATEBODY(GUTHANS_PLATEBODY, GUTHANS_PLATEBODY_25, GUTHANS_PLATEBODY_50, GUTHANS_PLATEBODY_75, GUTHANS_PLATEBODY_100), ITEM_GUTHANS_CHAINSKIRT(GUTHANS_CHAINSKIRT, GUTHANS_CHAINSKIRT_25, GUTHANS_CHAINSKIRT_50, GUTHANS_CHAINSKIRT_75, GUTHANS_CHAINSKIRT_100), ITEM_GUTHANS_WARSPEAR(GUTHANS_WARSPEAR, GUTHANS_WARSPEAR_25, GUTHANS_WARSPEAR_50, GUTHANS_WARSPEAR_75, GUTHANS_WARSPEAR_100), ITEM_TORAGS_HELM(TORAGS_HELM, TORAGS_HELM_25, TORAGS_HELM_50, TORAGS_HELM_75, TORAGS_HELM_100), ITEM_TORAGS_PLATEBODY(TORAGS_PLATEBODY, TORAGS_PLATEBODY_25, TORAGS_PLATEBODY_50, TORAGS_PLATEBODY_75, TORAGS_PLATEBODY_100), ITEM_TORAGS_PLATELEGS(TORAGS_PLATELEGS, TORAGS_PLATELEGS_25, TORAGS_PLATELEGS_50, TORAGS_PLATELEGS_75, TORAGS_PLATELEGS_100), ITEM_TORAGS_HAMMERS(TORAGS_HAMMERS, TORAGS_HAMMERS_25, TORAGS_HAMMERS_50, TORAGS_HAMMERS_75, TORAGS_HAMMERS_100), ITEM_VERACS_HELM(VERACS_HELM, VERACS_HELM_25, VERACS_HELM_50, VERACS_HELM_75, VERACS_HELM_100), ITEM_VERACS_BRASSARD(VERACS_BRASSARD, VERACS_BRASSARD_25, VERACS_BRASSARD_50, VERACS_BRASSARD_75, VERACS_BRASSARD_100), ITEM_VERACS_PLATESKIRT(VERACS_PLATESKIRT, VERACS_PLATESKIRT_25, VERACS_PLATESKIRT_50, VERACS_PLATESKIRT_75, VERACS_PLATESKIRT_100), ITEM_VERACS_FLAIL(VERACS_FLAIL, VERACS_FLAIL_25, VERACS_FLAIL_50, VERACS_FLAIL_75, VERACS_FLAIL_100), // Dragon equipment ornament kits ITEM_DRAGON_SCIMITAR(DRAGON_SCIMITAR, DRAGON_SCIMITAR_OR), ITEM_DRAGON_SCIMITAR_ORNAMENT_KIT(DRAGON_SCIMITAR_ORNAMENT_KIT, DRAGON_SCIMITAR_OR), ITEM_DRAGON_DEFENDER(DRAGON_DEFENDER_ORNAMENT_KIT, DRAGON_DEFENDER_T), ITEM_DRAGON_PICKAXE(DRAGON_PICKAXE, DRAGON_PICKAXE_12797, DRAGON_PICKAXE_OR, DRAGON_PICKAXE_OR_25376), ITEM_DRAGON_PICKAXE_OR(ZALCANO_SHARD, DRAGON_PICKAXE_OR), ITEM_DRAGON_AXE(DRAGON_AXE, DRAGON_AXE_OR), ITEM_DRAGON_HARPOON(DRAGON_HARPOON, DRAGON_HARPOON_OR), ITEM_INFERNAL_PICKAXE_OR(INFERNAL_PICKAXE, INFERNAL_PICKAXE_OR), ITEM_INFERNAL_PICKAXE_OR_UNCHARGED(INFERNAL_PICKAXE_UNCHARGED, INFERNAL_PICKAXE_UNCHARGED_25369), ITEM_INFERNAL_AXE_OR(INFERNAL_AXE, INFERNAL_AXE_OR), ITEM_INFERNAL_AXE_OR_UNCHARGED(INFERNAL_AXE_UNCHARGED, INFERNAL_AXE_UNCHARGED_25371), ITEM_INFERNAL_HARPOON_OR(INFERNAL_HARPOON, INFERNAL_HARPOON_OR), ITEM_INFERNAL_HARPOON_OR_UNCHARGED(INFERNAL_HARPOON_UNCHARGED, INFERNAL_HARPOON_UNCHARGED_25367), ITEM_TRAILBLAZER_TOOL_ORNAMENT_KIT(TRAILBLAZER_TOOL_ORNAMENT_KIT, DRAGON_PICKAXE_OR_25376, DRAGON_AXE_OR, DRAGON_HARPOON_OR, INFERNAL_PICKAXE_OR, INFERNAL_AXE_OR, INFERNAL_HARPOON_OR, INFERNAL_PICKAXE_UNCHARGED_25369, INFERNAL_AXE_UNCHARGED_25371, INFERNAL_HARPOON_UNCHARGED_25367), ITEM_DRAGON_KITESHIELD(DRAGON_KITESHIELD, DRAGON_KITESHIELD_G), ITEM_DRAGON_KITESHIELD_ORNAMENT_KIT(DRAGON_KITESHIELD_ORNAMENT_KIT, DRAGON_KITESHIELD_G), ITEM_DRAGON_FULL_HELM(DRAGON_FULL_HELM, DRAGON_FULL_HELM_G), ITEM_DRAGON_FULL_HELM_ORNAMENT_KIT(DRAGON_FULL_HELM_ORNAMENT_KIT, DRAGON_FULL_HELM_G), ITEM_DRAGON_CHAINBODY(DRAGON_CHAINBODY_3140, DRAGON_CHAINBODY_G), ITEM_DRAGON_CHAINBODY_ORNAMENT_KIT(DRAGON_CHAINBODY_ORNAMENT_KIT, DRAGON_CHAINBODY_G), ITEM_DRAGON_PLATEBODY(DRAGON_PLATEBODY, DRAGON_PLATEBODY_G), ITEM_DRAGON_PLATEBODY_ORNAMENT_KIT(DRAGON_PLATEBODY_ORNAMENT_KIT, DRAGON_PLATEBODY_G), ITEM_DRAGON_PLATESKIRT(DRAGON_PLATESKIRT, DRAGON_PLATESKIRT_G), ITEM_DRAGON_SKIRT_ORNAMENT_KIT(DRAGON_LEGSSKIRT_ORNAMENT_KIT, DRAGON_PLATESKIRT_G), ITEM_DRAGON_PLATELEGS(DRAGON_PLATELEGS, DRAGON_PLATELEGS_G), ITEM_DRAGON_LEGS_ORNAMENT_KIT(DRAGON_LEGSSKIRT_ORNAMENT_KIT, DRAGON_PLATELEGS_G), ITEM_DRAGON_SQ_SHIELD(DRAGON_SQ_SHIELD, DRAGON_SQ_SHIELD_G), ITEM_DRAGON_SQ_SHIELD_ORNAMENT_KIT(DRAGON_SQ_SHIELD_ORNAMENT_KIT, DRAGON_SQ_SHIELD_G), ITEM_DRAGON_BOOTS(DRAGON_BOOTS, DRAGON_BOOTS_G), ITEM_DRAGON_BOOTS_ORNAMENT_KIT(DRAGON_BOOTS_ORNAMENT_KIT, DRAGON_BOOTS_G), // Rune ornament kits ITEM_RUNE_SCIMITAR_GUTHIX(RUNE_SCIMITAR, RUNE_SCIMITAR_23330), ITEM_RUNE_SCIMITAR_ORNAMENT_KIT_GUTHIX(RUNE_SCIMITAR_ORNAMENT_KIT_GUTHIX, RUNE_SCIMITAR_23330), ITEM_RUNE_SCIMITAR_SARADOMIN(RUNE_SCIMITAR, RUNE_SCIMITAR_23332), ITEM_RUNE_SCIMITAR_ORNAMENT_KIT_SARADOMIN(RUNE_SCIMITAR_ORNAMENT_KIT_SARADOMIN, RUNE_SCIMITAR_23332), ITEM_RUNE_SCIMITAR_ZAMORAK(RUNE_SCIMITAR, RUNE_SCIMITAR_23334), ITEM_RUNE_SCIMITAR_ORNAMENT_KIT_ZAMORAK(RUNE_SCIMITAR_ORNAMENT_KIT_ZAMORAK, RUNE_SCIMITAR_23334), ITEM_RUNE_DEFENDER(RUNE_DEFENDER, RUNE_DEFENDER_T, RUNE_DEFENDER_LT), ITEM_RUNE_DEFENDER_ORNAMENT_KIT(RUNE_DEFENDER_ORNAMENT_KIT, RUNE_DEFENDER_T, RUNE_DEFENDER_LT), ITEM_RUNE_CROSSBOW(RUNE_CROSSBOW, RUNE_CROSSBOW_OR), // Godsword ornament kits ITEM_ARMADYL_GODSWORD(ARMADYL_GODSWORD, ARMADYL_GODSWORD_OR), ITEM_ARMADYL_GODSWORD_ORNAMENT_KIT(ARMADYL_GODSWORD_ORNAMENT_KIT, ARMADYL_GODSWORD_OR), ITEM_BANDOS_GODSWORD(BANDOS_GODSWORD, BANDOS_GODSWORD_OR), ITEM_BANDOS_GODSWORD_ORNAMENT_KIT(BANDOS_GODSWORD_ORNAMENT_KIT, BANDOS_GODSWORD_OR), ITEM_ZAMORAK_GODSWORD(ZAMORAK_GODSWORD, ZAMORAK_GODSWORD_OR), ITEM_ZAMORAK_GODSWORD_ORNAMENT_KIT(ZAMORAK_GODSWORD_ORNAMENT_KIT, ZAMORAK_GODSWORD_OR), ITEM_SARADOMIN_GODSWORD(SARADOMIN_GODSWORD, SARADOMIN_GODSWORD_OR), ITEM_SARADOMIN_GODSWORD_ORNAMENT_KIT(SARADOMIN_GODSWORD_ORNAMENT_KIT, SARADOMIN_GODSWORD_OR), // Jewellery ornament kits ITEM_AMULET_OF_TORTURE(AMULET_OF_TORTURE, AMULET_OF_TORTURE_OR), ITEM_TORTURE_ORNAMENT_KIT(TORTURE_ORNAMENT_KIT, AMULET_OF_TORTURE_OR), ITEM_NECKLACE_OF_ANGUISH(NECKLACE_OF_ANGUISH, NECKLACE_OF_ANGUISH_OR), ITEM_ANGUISH_ORNAMENT_KIT(ANGUISH_ORNAMENT_KIT, NECKLACE_OF_ANGUISH_OR), ITEM_OCCULT_NECKLACE(OCCULT_NECKLACE, OCCULT_NECKLACE_OR), ITEM_OCCULT_ORNAMENT_KIT(OCCULT_ORNAMENT_KIT, OCCULT_NECKLACE_OR), ITEM_AMULET_OF_FURY(AMULET_OF_FURY, AMULET_OF_FURY_OR, AMULET_OF_BLOOD_FURY), ITEM_FURY_ORNAMENT_KIT(FURY_ORNAMENT_KIT, AMULET_OF_FURY_OR), ITEM_TORMENTED_BRACELET(TORMENTED_BRACELET, TORMENTED_BRACELET_OR), ITEM_TORMENTED_ORNAMENT_KIT(TORMENTED_ORNAMENT_KIT, TORMENTED_BRACELET_OR), ITEM_BERSERKER_NECKLACE(BERSERKER_NECKLACE, BERSERKER_NECKLACE_OR), ITEM_BERSERKER_NECKLACE_ORNAMENT_KIT(BERSERKER_NECKLACE_ORNAMENT_KIT, BERSERKER_NECKLACE_OR), // Other ornament kits ITEM_SHATTERED_RELICS_VARIETY_ORNAMENT_KIT(SHATTERED_RELICS_VARIETY_ORNAMENT_KIT, RUNE_CROSSBOW_OR, ABYSSAL_TENTACLE_OR, ABYSSAL_WHIP_OR, BOOK_OF_BALANCE_OR, BOOK_OF_DARKNESS_OR, BOOK_OF_LAW_OR, BOOK_OF_WAR_OR, HOLY_BOOK_OR, UNHOLY_BOOK_OR), ITEM_SHATTERED_RELICS_VOID_ORNAMENT_KIT(SHATTERED_RELICS_VOID_ORNAMENT_KIT, ELITE_VOID_TOP_OR, ELITE_VOID_ROBE_OR, VOID_KNIGHT_TOP_OR, VOID_KNIGHT_ROBE_OR, VOID_KNIGHT_GLOVES_OR, VOID_MAGE_HELM_OR, VOID_MELEE_HELM_OR, VOID_RANGER_HELM_OR, VOID_KNIGHT_TOP_LOR, VOID_KNIGHT_ROBE_LOR, VOID_KNIGHT_GLOVES_LOR, ELITE_VOID_TOP_LOR, ELITE_VOID_ROBE_LOR, VOID_MAGE_HELM_LOR, VOID_RANGER_HELM_LOR, VOID_MELEE_HELM_LOR), ITEM_MYSTIC_BOOTS(MYSTIC_BOOTS, MYSTIC_BOOTS_OR), ITEM_MYSTIC_GLOVES(MYSTIC_GLOVES, MYSTIC_GLOVES_OR), ITEM_MYSTIC_HAT(MYSTIC_HAT, MYSTIC_HAT_OR), ITEM_MYSTIC_ROBE_BOTTOM(MYSTIC_ROBE_BOTTOM, MYSTIC_ROBE_BOTTOM_OR), ITEM_MYSTIC_ROBE_TOP(MYSTIC_ROBE_TOP, MYSTIC_ROBE_TOP_OR), ITEM_SHATTERED_RELICS_MYSTIC_ORNAMENT_KIT(SHATTERED_RELICS_MYSTIC_ORNAMENT_KIT, MYSTIC_BOOTS_OR, MYSTIC_GLOVES_OR, MYSTIC_HAT_OR, MYSTIC_ROBE_BOTTOM_OR, MYSTIC_ROBE_TOP_OR), ITEM_CANNON_BARRELS(CANNON_BARRELS, CANNON_BARRELS_OR), ITEM_CANNON_BASE(CANNON_BASE, CANNON_BASE_OR), ITEM_CANNON_FURNACE(CANNON_FURNACE, CANNON_FURNACE_OR), ITEM_CANNON_STAND(CANNON_STAND, CANNON_STAND_OR), ITEM_SHATTERED_CANNON_ORNAMENT_KIT(SHATTERED_CANNON_ORNAMENT_KIT, CANNON_BARRELS_OR, CANNON_BASE_OR, CANNON_FURNACE_OR, CANNON_STAND_OR), // Ensouled heads ITEM_ENSOULED_GOBLIN_HEAD(ENSOULED_GOBLIN_HEAD_13448, ENSOULED_GOBLIN_HEAD), ITEM_ENSOULED_MONKEY_HEAD(ENSOULED_MONKEY_HEAD_13451, ENSOULED_MONKEY_HEAD), ITEM_ENSOULED_IMP_HEAD(ENSOULED_IMP_HEAD_13454, ENSOULED_IMP_HEAD), ITEM_ENSOULED_MINOTAUR_HEAD(ENSOULED_MINOTAUR_HEAD_13457, ENSOULED_MINOTAUR_HEAD), ITEM_ENSOULED_SCORPION_HEAD(ENSOULED_SCORPION_HEAD_13460, ENSOULED_SCORPION_HEAD), ITEM_ENSOULED_BEAR_HEAD(ENSOULED_BEAR_HEAD_13463, ENSOULED_BEAR_HEAD), ITEM_ENSOULED_UNICORN_HEAD(ENSOULED_UNICORN_HEAD_13466, ENSOULED_UNICORN_HEAD), ITEM_ENSOULED_DOG_HEAD(ENSOULED_DOG_HEAD_13469, ENSOULED_DOG_HEAD), ITEM_ENSOULED_CHAOS_DRUID_HEAD(ENSOULED_CHAOS_DRUID_HEAD_13472, ENSOULED_CHAOS_DRUID_HEAD), ITEM_ENSOULED_GIANT_HEAD(ENSOULED_GIANT_HEAD_13475, ENSOULED_GIANT_HEAD), ITEM_ENSOULED_OGRE_HEAD(ENSOULED_OGRE_HEAD_13478, ENSOULED_OGRE_HEAD), ITEM_ENSOULED_ELF_HEAD(ENSOULED_ELF_HEAD_13481, ENSOULED_ELF_HEAD), ITEM_ENSOULED_TROLL_HEAD(ENSOULED_TROLL_HEAD_13484, ENSOULED_TROLL_HEAD), ITEM_ENSOULED_HORROR_HEAD(ENSOULED_HORROR_HEAD_13487, ENSOULED_HORROR_HEAD), ITEM_ENSOULED_KALPHITE_HEAD(ENSOULED_KALPHITE_HEAD_13490, ENSOULED_KALPHITE_HEAD), ITEM_ENSOULED_DAGANNOTH_HEAD(ENSOULED_DAGANNOTH_HEAD_13493, ENSOULED_DAGANNOTH_HEAD), ITEM_ENSOULED_BLOODVELD_HEAD(ENSOULED_BLOODVELD_HEAD_13496, ENSOULED_BLOODVELD_HEAD), ITEM_ENSOULED_TZHAAR_HEAD(ENSOULED_TZHAAR_HEAD_13499, ENSOULED_TZHAAR_HEAD), ITEM_ENSOULED_DEMON_HEAD(ENSOULED_DEMON_HEAD_13502, ENSOULED_DEMON_HEAD), ITEM_ENSOULED_HELLHOUND_HEAD(ENSOULED_HELLHOUND_HEAD_26997, ENSOULED_HELLHOUND_HEAD), ITEM_ENSOULED_AVIANSIE_HEAD(ENSOULED_AVIANSIE_HEAD_13505, ENSOULED_AVIANSIE_HEAD), ITEM_ENSOULED_ABYSSAL_HEAD(ENSOULED_ABYSSAL_HEAD_13508, ENSOULED_ABYSSAL_HEAD), ITEM_ENSOULED_DRAGON_HEAD(ENSOULED_DRAGON_HEAD_13511, ENSOULED_DRAGON_HEAD), // Imbued rings ITEM_BERSERKER_RING(BERSERKER_RING, true, 1L, BERSERKER_RING_I), ITEM_SEERS_RING(SEERS_RING, true, 1L, SEERS_RING_I), ITEM_WARRIOR_RING(WARRIOR_RING, true, 1L, WARRIOR_RING_I), ITEM_ARCHERS_RING(ARCHERS_RING, true, 1L, ARCHERS_RING_I), ITEM_TREASONOUS_RING(TREASONOUS_RING, true, 1L, TREASONOUS_RING_I), ITEM_TYRANNICAL_RING(TYRANNICAL_RING, true, 1L, TYRANNICAL_RING_I), ITEM_RING_OF_THE_GODS(RING_OF_THE_GODS, true, 1L, RING_OF_THE_GODS_I), ITEM_RING_OF_SUFFERING(RING_OF_SUFFERING, true, 1L, RING_OF_SUFFERING_I), ITEM_GRANITE_RING(GRANITE_RING, true, 1L, GRANITE_RING_I), // Bounty hunter ITEM_GRANITE_MAUL(GRANITE_MAUL, GRANITE_MAUL_12848), ITEM_MAGIC_SHORTBOW(MAGIC_SHORTBOW, MAGIC_SHORTBOW_I), ITEM_MAGIC_SHORTBOW_SCROLL(MAGIC_SHORTBOW_SCROLL, MAGIC_SHORTBOW_I), ITEM_SARADOMINS_BLESSED_SWORD(SARADOMINS_TEAR, SARADOMINS_BLESSED_SWORD), // Jewellery with charges ITEM_RING_OF_WEALTH(RING_OF_WEALTH, true, 1L, RING_OF_WEALTH_1), ITEM_RING_OF_WEALTH_SCROLL(RING_OF_WEALTH_SCROLL, RING_OF_WEALTH_I, RING_OF_WEALTH_I1, RING_OF_WEALTH_I2, RING_OF_WEALTH_I3, RING_OF_WEALTH_I4, RING_OF_WEALTH_I5), ITEM_AMULET_OF_GLORY(AMULET_OF_GLORY, AMULET_OF_GLORY1, AMULET_OF_GLORY2, AMULET_OF_GLORY3, AMULET_OF_GLORY5), ITEM_AMULET_OF_GLORY_T(AMULET_OF_GLORY_T, AMULET_OF_GLORY_T1, AMULET_OF_GLORY_T2, AMULET_OF_GLORY_T3, AMULET_OF_GLORY_T5), ITEM_SKILLS_NECKLACE(SKILLS_NECKLACE, SKILLS_NECKLACE1, SKILLS_NECKLACE2, SKILLS_NECKLACE3, SKILLS_NECKLACE5), ITEM_RING_OF_DUELING(RING_OF_DUELING8, RING_OF_DUELING1, RING_OF_DUELING2, RING_OF_DUELING3, RING_OF_DUELING4, RING_OF_DUELING5, RING_OF_DUELING6, RING_OF_DUELING7), ITEM_GAMES_NECKLACE(GAMES_NECKLACE8, GAMES_NECKLACE1, GAMES_NECKLACE2, GAMES_NECKLACE3, GAMES_NECKLACE4, GAMES_NECKLACE5, GAMES_NECKLACE6, GAMES_NECKLACE7), // Degradable/charged weaponry/armour ITEM_ABYSSAL_WHIP(ABYSSAL_WHIP, VOLCANIC_ABYSSAL_WHIP, FROZEN_ABYSSAL_WHIP, ABYSSAL_WHIP_OR), ITEM_KRAKEN_TENTACLE(KRAKEN_TENTACLE, ABYSSAL_TENTACLE, ABYSSAL_TENTACLE_OR), ITEM_TRIDENT_OF_THE_SEAS(UNCHARGED_TRIDENT, TRIDENT_OF_THE_SEAS), ITEM_TRIDENT_OF_THE_SEAS_E(UNCHARGED_TRIDENT_E, TRIDENT_OF_THE_SEAS_E), ITEM_TRIDENT_OF_THE_SWAMP(UNCHARGED_TOXIC_TRIDENT, TRIDENT_OF_THE_SWAMP), ITEM_TRIDENT_OF_THE_SWAMP_E(UNCHARGED_TOXIC_TRIDENT_E, TRIDENT_OF_THE_SWAMP_E), ITEM_TOXIC_BLOWPIPE(TOXIC_BLOWPIPE_EMPTY, TOXIC_BLOWPIPE), ITEM_TOXIC_STAFF_OFF_THE_DEAD(TOXIC_STAFF_UNCHARGED, TOXIC_STAFF_OF_THE_DEAD), ITEM_SERPENTINE_HELM(SERPENTINE_HELM_UNCHARGED, SERPENTINE_HELM, TANZANITE_HELM_UNCHARGED, TANZANITE_HELM, MAGMA_HELM_UNCHARGED, MAGMA_HELM), ITEM_DRAGONFIRE_SHIELD(DRAGONFIRE_SHIELD_11284, DRAGONFIRE_SHIELD), ITEM_DRAGONFIRE_WARD(DRAGONFIRE_WARD_22003, DRAGONFIRE_WARD), ITEM_ANCIENT_WYVERN_SHIELD(ANCIENT_WYVERN_SHIELD_21634, ANCIENT_WYVERN_SHIELD), ITEM_SANGUINESTI_STAFF(SANGUINESTI_STAFF_UNCHARGED, SANGUINESTI_STAFF, HOLY_SANGUINESTI_STAFF_UNCHARGED, HOLY_SANGUINESTI_STAFF), ITEM_SCYTHE_OF_VITUR(SCYTHE_OF_VITUR_UNCHARGED, SCYTHE_OF_VITUR, HOLY_SCYTHE_OF_VITUR_UNCHARGED, HOLY_SCYTHE_OF_VITUR, SANGUINE_SCYTHE_OF_VITUR_UNCHARGED, SANGUINE_SCYTHE_OF_VITUR), ITEM_TOME_OF_FIRE(TOME_OF_FIRE_EMPTY, TOME_OF_FIRE), ITEM_TOME_OF_WATER(TOME_OF_WATER_EMPTY, TOME_OF_WATER), ITEM_CRAWS_BOW(CRAWS_BOW_U, CRAWS_BOW), ITEM_VIGGORAS_CHAINMACE(VIGGORAS_CHAINMACE_U, VIGGORAS_CHAINMACE), ITEM_THAMMARONS_SCEPTRE(THAMMARONS_SCEPTRE_U, THAMMARONS_SCEPTRE), ITEM_BRYOPHYTAS_STAFF(BRYOPHYTAS_STAFF_UNCHARGED, BRYOPHYTAS_STAFF), ITEM_RING_OF_ENDURANCE(RING_OF_ENDURANCE_UNCHARGED_24844, RING_OF_ENDURANCE), ITEM_TUMEKENS_SHADOW(TUMEKENS_SHADOW_UNCHARGED, TUMEKENS_SHADOW), ITEM_PHARAOHS_SCEPTRE(PHARAOHS_SCEPTRE_UNCHARGED, true, 1L, PHARAOHS_SCEPTRE), // Tombs of Amascut gear ITEM_ELIDINIS_WARD(ELIDINIS_WARD, ELIDINIS_WARD_F, ELIDINIS_WARD_OR), ITEM_OSMUMTENS_FANG(OSMUMTENS_FANG, OSMUMTENS_FANG_OR), // Infinity colour kits ITEM_INFINITY_TOP(INFINITY_TOP, INFINITY_TOP_20574, DARK_INFINITY_TOP, LIGHT_INFINITY_TOP), ITEM_INFINITY_TOP_LIGHT_COLOUR_KIT(LIGHT_INFINITY_COLOUR_KIT, LIGHT_INFINITY_TOP), ITEM_INFINITY_TOP_DARK_COLOUR_KIT(DARK_INFINITY_COLOUR_KIT, DARK_INFINITY_TOP), ITEM_INFINITY_BOTTOMS(INFINITY_BOTTOMS, INFINITY_BOTTOMS_20575, DARK_INFINITY_BOTTOMS, LIGHT_INFINITY_BOTTOMS), ITEM_INFINITY_BOTTOMS_LIGHT_COLOUR_KIT(LIGHT_INFINITY_COLOUR_KIT, LIGHT_INFINITY_BOTTOMS), ITEM_INFINITY_BOTTOMS_DARK_COLOUR_KIT(DARK_INFINITY_COLOUR_KIT, DARK_INFINITY_BOTTOMS), ITEM_INFINITY_HAT(INFINITY_HAT, DARK_INFINITY_HAT, LIGHT_INFINITY_HAT), ITEM_INFINITY_HAT_LIGHT_COLOUR_KIT(LIGHT_INFINITY_COLOUR_KIT, LIGHT_INFINITY_HAT), ITEM_INFINITY_HAT_DARK_COLOUR_KIT(DARK_INFINITY_COLOUR_KIT, DARK_INFINITY_HAT), // Miscellaneous ornament kits ITEM_DARK_BOW(DARK_BOW, DARK_BOW_12765, DARK_BOW_12766, DARK_BOW_12767, DARK_BOW_12768, DARK_BOW_20408), ITEM_ODIUM_WARD(ODIUM_WARD, ODIUM_WARD_12807), ITEM_MALEDICTION_WARD(MALEDICTION_WARD, MALEDICTION_WARD_12806), ITEM_STEAM_BATTLESTAFF(STEAM_BATTLESTAFF, STEAM_BATTLESTAFF_12795), ITEM_LAVA_BATTLESTAFF(LAVA_BATTLESTAFF, LAVA_BATTLESTAFF_21198), ITEM_TZHAARKETOM(TZHAARKETOM, TZHAARKETOM_T), ITEM_TZHAARKETOM_ORNAMENT_KIT(TZHAARKETOM_ORNAMENT_KIT, TZHAARKETOM_T), ITEM_DRAGON_HUNTER_CROSSBOW(DRAGON_HUNTER_CROSSBOW, DRAGON_HUNTER_CROSSBOW_B, DRAGON_HUNTER_CROSSBOW_T), // Slayer helm/black mask ITEM_BLACK_MASK(BLACK_MASK, true, 1L, BLACK_MASK, SLAYER_HELMET), // Revertible items ITEM_HYDRA_LEATHER(HYDRA_LEATHER, FEROCIOUS_GLOVES), ITEM_HYDRA_TAIL(HYDRA_TAIL, BONECRUSHER_NECKLACE), ITEM_DRAGONBONE_NECKLACE(DRAGONBONE_NECKLACE, BONECRUSHER_NECKLACE), ITEM_BOTTOMLESS_COMPOST_BUCKET(BOTTOMLESS_COMPOST_BUCKET, BOTTOMLESS_COMPOST_BUCKET_22997), ITEM_BASILISK_JAW(BASILISK_JAW, NEITIZNOT_FACEGUARD), ITEM_HELM_OF_NEITIZNOT(HELM_OF_NEITIZNOT, NEITIZNOT_FACEGUARD), ITEM_TWISTED_HORNS(TWISTED_HORNS, TWISTED_SLAYER_HELMET, TWISTED_SLAYER_HELMET_I, TWISTED_SLAYER_HELMET_I_25191, TWISTED_SLAYER_HELMET_I_26681), ITEM_ELDRITCH_ORB(ELDRITCH_ORB, ELDRITCH_NIGHTMARE_STAFF), ITEM_HARMONISED_ORB(HARMONISED_ORB, HARMONISED_NIGHTMARE_STAFF), ITEM_VOLATILE_ORB(VOLATILE_ORB, VOLATILE_NIGHTMARE_STAFF), ITEM_NIGHTMARE_STAFF(NIGHTMARE_STAFF, ELDRITCH_NIGHTMARE_STAFF, HARMONISED_NIGHTMARE_STAFF, VOLATILE_NIGHTMARE_STAFF), ITEM_GHARZI_RAPIER(GHRAZI_RAPIER, HOLY_GHRAZI_RAPIER), ITEM_MASTER_SCROLL_BOOK(MASTER_SCROLL_BOOK_EMPTY, MASTER_SCROLL_BOOK), ITEM_ARCANE_SIGIL(ARCANE_SIGIL, ELIDINIS_WARD_F, ELIDINIS_WARD_OR), // Trouver Parchment ITEM_TROUVER_PARCHMENT( TROUVER_PARCHMENT, INFERNAL_MAX_CAPE_L, FIRE_MAX_CAPE_L, ASSEMBLER_MAX_CAPE_L, BRONZE_DEFENDER_L, IRON_DEFENDER_L, STEEL_DEFENDER_L, BLACK_DEFENDER_L, MITHRIL_DEFENDER_L, ADAMANT_DEFENDER_L, RUNE_DEFENDER_L, DRAGON_DEFENDER_L, DECORATIVE_SWORD_L, DECORATIVE_ARMOUR_L, DECORATIVE_ARMOUR_L_24159, DECORATIVE_HELM_L, DECORATIVE_SHIELD_L, DECORATIVE_ARMOUR_L_24162, DECORATIVE_ARMOUR_L_24163, DECORATIVE_ARMOUR_L_24164, DECORATIVE_ARMOUR_L_24165, DECORATIVE_ARMOUR_L_24166, DECORATIVE_ARMOUR_L_24167, DECORATIVE_ARMOUR_L_24168, SARADOMIN_HALO_L, ZAMORAK_HALO_L, GUTHIX_HALO_L, HEALER_HAT_L, FIGHTER_HAT_L, RANGER_HAT_L, FIGHTER_TORSO_L, PENANCE_SKIRT_L, VOID_KNIGHT_TOP_L, ELITE_VOID_TOP_L, VOID_KNIGHT_ROBE_L, ELITE_VOID_ROBE_L, VOID_KNIGHT_MACE_L, VOID_KNIGHT_GLOVES_L, VOID_MAGE_HELM_L, VOID_RANGER_HELM_L, VOID_MELEE_HELM_L, AVERNIC_DEFENDER_L, ARMADYL_HALO_L, BANDOS_HALO_L, SEREN_HALO_L, ANCIENT_HALO_L, BRASSICA_HALO_L, AVAS_ASSEMBLER_L, FIRE_CAPE_L, INFERNAL_CAPE_L, IMBUED_SARADOMIN_MAX_CAPE_L, IMBUED_ZAMORAK_MAX_CAPE_L, IMBUED_GUTHIX_MAX_CAPE_L, IMBUED_SARADOMIN_CAPE_L, IMBUED_ZAMORAK_CAPE_L, IMBUED_GUTHIX_CAPE_L, RUNE_POUCH_L, RUNNER_HAT_L, DECORATIVE_BOOTS_L, DECORATIVE_FULL_HELM_L, MASORI_ASSEMBLER_L, MASORI_ASSEMBLER_MAX_CAPE_L, RUNE_DEFENDER_LT, VOID_KNIGHT_TOP_LOR, VOID_KNIGHT_ROBE_LOR, VOID_KNIGHT_GLOVES_LOR, ELITE_VOID_TOP_LOR, ELITE_VOID_ROBE_LOR, VOID_MAGE_HELM_LOR, VOID_RANGER_HELM_LOR, VOID_MELEE_HELM_LOR, BARRONITE_MACE_L), ITEM_TROUVER_PARCHMENT_REFUND_LARGE( COINS_995, 475000L, INFERNAL_MAX_CAPE_L, FIRE_MAX_CAPE_L, ASSEMBLER_MAX_CAPE_L, RUNE_DEFENDER_L, DRAGON_DEFENDER_L, DECORATIVE_SWORD_L, DECORATIVE_ARMOUR_L, DECORATIVE_ARMOUR_L_24159, DECORATIVE_HELM_L, DECORATIVE_SHIELD_L, DECORATIVE_ARMOUR_L_24162, DECORATIVE_ARMOUR_L_24163, DECORATIVE_ARMOUR_L_24164, DECORATIVE_ARMOUR_L_24165, DECORATIVE_ARMOUR_L_24166, DECORATIVE_ARMOUR_L_24167, DECORATIVE_ARMOUR_L_24168, SARADOMIN_HALO_L, ZAMORAK_HALO_L, GUTHIX_HALO_L, HEALER_HAT_L, FIGHTER_HAT_L, RANGER_HAT_L, FIGHTER_TORSO_L, PENANCE_SKIRT_L, VOID_KNIGHT_TOP_L, ELITE_VOID_TOP_L, VOID_KNIGHT_ROBE_L, ELITE_VOID_ROBE_L, VOID_KNIGHT_MACE_L, VOID_KNIGHT_GLOVES_L, VOID_MAGE_HELM_L, VOID_RANGER_HELM_L, VOID_MELEE_HELM_L, AVERNIC_DEFENDER_L, ARMADYL_HALO_L, BANDOS_HALO_L, SEREN_HALO_L, ANCIENT_HALO_L, BRASSICA_HALO_L, AVAS_ASSEMBLER_L, FIRE_CAPE_L, INFERNAL_CAPE_L, IMBUED_SARADOMIN_MAX_CAPE_L, IMBUED_ZAMORAK_MAX_CAPE_L, IMBUED_GUTHIX_MAX_CAPE_L, IMBUED_SARADOMIN_CAPE_L, IMBUED_ZAMORAK_CAPE_L, IMBUED_GUTHIX_CAPE_L, RUNE_POUCH_L, RUNNER_HAT_L, DECORATIVE_BOOTS_L, DECORATIVE_FULL_HELM_L, MASORI_ASSEMBLER_L, MASORI_ASSEMBLER_MAX_CAPE_L, RUNE_DEFENDER_LT, VOID_KNIGHT_TOP_LOR, VOID_KNIGHT_ROBE_LOR, VOID_KNIGHT_GLOVES_LOR, ELITE_VOID_TOP_LOR, ELITE_VOID_ROBE_LOR, VOID_MAGE_HELM_LOR, VOID_RANGER_HELM_LOR, VOID_MELEE_HELM_LOR, BARRONITE_MACE_L), ITEM_TROUVER_PARCHMENT_REFUND_SMALL(COINS_995, 47500L, BRONZE_DEFENDER_L, IRON_DEFENDER_L, STEEL_DEFENDER_L, BLACK_DEFENDER_L, MITHRIL_DEFENDER_L, ADAMANT_DEFENDER_L), // Crystal items ITEM_CRYSTAL_TOOL_SEED(CRYSTAL_TOOL_SEED, CRYSTAL_AXE, CRYSTAL_AXE_INACTIVE, CRYSTAL_HARPOON, CRYSTAL_HARPOON_INACTIVE, CRYSTAL_PICKAXE, CRYSTAL_PICKAXE_INACTIVE), ITEM_CRYSTAL_AXE(DRAGON_AXE, CRYSTAL_AXE, CRYSTAL_AXE_INACTIVE), ITEM_CRYSTAL_HARPOON(DRAGON_HARPOON, CRYSTAL_HARPOON, CRYSTAL_HARPOON_INACTIVE), ITEM_CRYSTAL_PICKAXE(DRAGON_PICKAXE, CRYSTAL_PICKAXE, CRYSTAL_PICKAXE_INACTIVE), ITEM_BLADE_OF_SAELDOR(BLADE_OF_SAELDOR_INACTIVE, true, 1L, BLADE_OF_SAELDOR), ITEM_CRYSTAL_BOW(CRYSTAL_WEAPON_SEED, CRYSTAL_BOW, CRYSTAL_BOW_24123, CRYSTAL_BOW_INACTIVE), ITEM_CRYSTAL_HALBERD(CRYSTAL_WEAPON_SEED, CRYSTAL_HALBERD, CRYSTAL_HALBERD_24125, CRYSTAL_HALBERD_INACTIVE), ITEM_CRYSTAL_SHIELD(CRYSTAL_WEAPON_SEED, CRYSTAL_SHIELD, CRYSTAL_SHIELD_24127, CRYSTAL_SHIELD_INACTIVE), ITEM_CRYSTAL_HELMET(CRYSTAL_ARMOUR_SEED, CRYSTAL_HELM, CRYSTAL_HELM_INACTIVE), ITEM_CRYSTAL_LEGS(CRYSTAL_ARMOUR_SEED, 2L, CRYSTAL_LEGS, CRYSTAL_LEGS_INACTIVE), ITEM_CRYSTAL_BODY(CRYSTAL_ARMOUR_SEED, 3L, CRYSTAL_BODY, CRYSTAL_BODY_INACTIVE), ITEM_BOW_OF_FAERDHINEN(BOW_OF_FAERDHINEN_INACTIVE, true, 1L, BOW_OF_FAERDHINEN), // Bird nests ITEM_BIRD_NEST(BIRD_NEST_5075, BIRD_NEST, BIRD_NEST_5071, BIRD_NEST_5072, BIRD_NEST_5073, BIRD_NEST_5074, BIRD_NEST_7413, BIRD_NEST_13653, BIRD_NEST_22798, BIRD_NEST_22800, CLUE_NEST_EASY, CLUE_NEST_MEDIUM, CLUE_NEST_HARD, CLUE_NEST_ELITE), // Ancestral robes ITEM_ANCESTRAL_HAT(ANCESTRAL_HAT, TWISTED_ANCESTRAL_HAT), ITEM_ANCESTRAL_ROBE_TOP(ANCESTRAL_ROBE_TOP, TWISTED_ANCESTRAL_ROBE_TOP), ITEM_ANCESTRAL_ROBE_BOTTOM(ANCESTRAL_ROBE_BOTTOM, TWISTED_ANCESTRAL_ROBE_BOTTOM), // Graceful ITEM_MARK_OF_GRACE(AMYLASE_CRYSTAL, true, 10L, MARK_OF_GRACE), ITEM_GRACEFUL_HOOD(MARK_OF_GRACE, true, 28L, GRACEFUL_HOOD), ITEM_GRACEFUL_TOP(MARK_OF_GRACE, true, 44L, GRACEFUL_TOP), ITEM_GRACEFUL_LEGS(MARK_OF_GRACE, true, 48L, GRACEFUL_LEGS), ITEM_GRACEFUL_GLOVES(MARK_OF_GRACE, true, 24L, GRACEFUL_GLOVES), ITEM_GRACEFUL_BOOTS(MARK_OF_GRACE, true, 32L, GRACEFUL_BOOTS), ITEM_GRACEFUL_CAPE(MARK_OF_GRACE, true, 32L, GRACEFUL_CAPE), // Trailblazer Graceful Ornament Kit ITEM_TRAILBLAZER_GRACEFUL_HOOD(TRAILBLAZER_GRACEFUL_ORNAMENT_KIT, GRACEFUL_HOOD_25069), ITEM_TRAILBLAZER_GRACEFUL_TOP(TRAILBLAZER_GRACEFUL_ORNAMENT_KIT, GRACEFUL_TOP_25075), ITEM_TRAILBLAZER_GRACEFUL_LEGS(TRAILBLAZER_GRACEFUL_ORNAMENT_KIT, GRACEFUL_LEGS_25078), ITEM_TRAILBLAZER_GRACEFUL_GLOVES(TRAILBLAZER_GRACEFUL_ORNAMENT_KIT, GRACEFUL_GLOVES_25081), ITEM_TRAILBLAZER_GRACEFUL_BOOTS(TRAILBLAZER_GRACEFUL_ORNAMENT_KIT, GRACEFUL_BOOTS_25084), ITEM_TRAILBLAZER_GRACEFUL_CAPE(TRAILBLAZER_GRACEFUL_ORNAMENT_KIT, GRACEFUL_CAPE_25072), // 10 golden nuggets = 100 soft clay ITEM_GOLDEN_NUGGET(SOFT_CLAY, true, 10L, GOLDEN_NUGGET), ITEM_PROSPECTOR_HELMET(GOLDEN_NUGGET, true, 32L, PROSPECTOR_HELMET), ITEM_PROSPECTOR_JACKET(GOLDEN_NUGGET, true, 48L, PROSPECTOR_JACKET), ITEM_PROSPECTOR_LEGS(GOLDEN_NUGGET, true, 40L, PROSPECTOR_LEGS), ITEM_PROSPECTOR_BOOTS(GOLDEN_NUGGET, true, 24L, PROSPECTOR_BOOTS), // 10 unidentified minerals = 100 soft clay ITEM_UNIDENTIFIED_MINERALS(SOFT_CLAY, true, 10L, UNIDENTIFIED_MINERALS), // Converted to coins ITEM_TATTERED_PAGE(COINS_995, true, 1000L, TATTERED_MOON_PAGE, TATTERED_SUN_PAGE, TATTERED_TEMPLE_PAGE), ITEM_LONG_BONE(COINS_995, true, 1000L, LONG_BONE), ITEM_CURVED_BONE(COINS_995, true, 2000L, CURVED_BONE), ITEM_PERFECT_SHELL(COINS_995, true, 600L, PERFECT_SHELL), ITEM_PERFECT_SNAIL_SHELL(COINS_995, true, 600L, PERFECT_SNAIL_SHELL), ITEM_SNAIL_SHELL(COINS_995, true, 600L, SNAIL_SHELL), ITEM_TORTOISE_SHELL(COINS_995, true, 250L, TORTOISE_SHELL); @VisibleForTesting static final Multimap<Integer, ItemMapping> MAPPINGS = HashMultimap.create(); private final int tradeableItem; private final int[] untradableItems; private final long quantity; private final boolean untradeable; static { for (final ItemMapping item : values()) { for (int itemId : item.untradableItems) { if (item.untradeable) { for (final Integer variation : ItemVariationMapping.getVariations(itemId)) { if (variation != item.tradeableItem) { MAPPINGS.put(variation, item); } } } else { MAPPINGS.put(itemId, item); } } } } ItemMapping(int tradeableItem, boolean untradeable, long quantity, int... untradableItems) { this.tradeableItem = tradeableItem; this.untradableItems = untradableItems; this.quantity = quantity; this.untradeable = untradeable; } ItemMapping(int tradeableItem, long quantity, int... untradableItems) { this(tradeableItem, false, quantity, untradableItems); } ItemMapping(int tradeableItem, int... untradableItems) { this(tradeableItem, 1L, untradableItems); } /** * Get collection of items that are mapped from single item id. * * @param itemId the item id * @return the collection */ @Nullable public static Collection<ItemMapping> map(int itemId) { final Collection<ItemMapping> mapping = MAPPINGS.get(itemId); if (mapping.isEmpty()) { return null; } return mapping; } }
package net.runelite.client.game; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import java.util.Collection; import java.util.Collections; import static net.runelite.api.ItemID.*; /** * Converts untradeable items to it's tradeable counterparts */ public enum ItemMapping { // Barrows equipment ITEM_AHRIMS_HOOD(AHRIMS_HOOD, AHRIMS_HOOD_25, AHRIMS_HOOD_50, AHRIMS_HOOD_75, AHRIMS_HOOD_100), ITEM_AHRIMS_ROBETOP(AHRIMS_ROBETOP, AHRIMS_ROBETOP_25, AHRIMS_ROBETOP_50, AHRIMS_ROBETOP_75, AHRIMS_ROBETOP_100), ITEM_AHRIMS_ROBEBOTTOM(AHRIMS_ROBESKIRT, AHRIMS_ROBESKIRT_25, AHRIMS_ROBESKIRT_50, AHRIMS_ROBESKIRT_75, AHRIMS_ROBESKIRT_100), ITEM_AHRIMS_STAFF(AHRIMS_STAFF, AHRIMS_STAFF_25, AHRIMS_STAFF_50, AHRIMS_STAFF_75, AHRIMS_STAFF_100), ITEM_KARILS_COIF(KARILS_COIF, KARILS_COIF_25, KARILS_COIF_50, KARILS_COIF_75, KARILS_COIF_100), ITEM_KARILS_LEATHERTOP(KARILS_LEATHERTOP, KARILS_LEATHERTOP_25, KARILS_LEATHERTOP_50, KARILS_LEATHERTOP_75, KARILS_LEATHERTOP_100), ITEM_KARILS_LEATHERSKIRT(KARILS_LEATHERSKIRT, KARILS_LEATHERSKIRT_25, KARILS_LEATHERSKIRT_50, KARILS_LEATHERSKIRT_75, KARILS_LEATHERSKIRT_100), ITEM_KARILS_CROSSBOW(KARILS_CROSSBOW, KARILS_CROSSBOW_25, KARILS_CROSSBOW_50, KARILS_CROSSBOW_75, KARILS_CROSSBOW_100), ITEM_DHAROKS_HELM(DHAROKS_HELM, DHAROKS_HELM_25, DHAROKS_HELM_50, DHAROKS_HELM_75, DHAROKS_HELM_100), ITEM_DHAROKS_PLATEBODY(DHAROKS_PLATEBODY, DHAROKS_PLATEBODY_25, DHAROKS_PLATEBODY_50, DHAROKS_PLATEBODY_75, DHAROKS_PLATEBODY_100), ITEM_DHAROKS_PLATELEGS(DHAROKS_PLATELEGS, DHAROKS_PLATELEGS_25, DHAROKS_PLATELEGS_50, DHAROKS_PLATELEGS_75, DHAROKS_PLATELEGS_100), ITEM_DHARKS_GREATEAXE(DHAROKS_GREATAXE, DHAROKS_GREATAXE_25, DHAROKS_GREATAXE_50, DHAROKS_GREATAXE_75, DHAROKS_GREATAXE_100), ITEM_GUTHANS_HELM(GUTHANS_HELM, GUTHANS_HELM_25, GUTHANS_HELM_50, GUTHANS_HELM_75, GUTHANS_HELM_100), ITEM_GUTHANS_PLATEBODY(GUTHANS_PLATEBODY, GUTHANS_PLATEBODY_25, GUTHANS_PLATEBODY_50, GUTHANS_PLATEBODY_75, GUTHANS_PLATEBODY_100), ITEM_GUTHANS_CHAINSKIRT(GUTHANS_CHAINSKIRT, GUTHANS_CHAINSKIRT_25, GUTHANS_CHAINSKIRT_50, GUTHANS_CHAINSKIRT_75, GUTHANS_CHAINSKIRT_100), ITEM_GUTHANS_WARSPEAR(GUTHANS_WARSPEAR, GUTHANS_WARSPEAR_25, GUTHANS_WARSPEAR_50, GUTHANS_WARSPEAR_75, GUTHANS_WARSPEAR_100), ITEM_TORAGS_HELM(TORAGS_HELM, TORAGS_HELM_25, TORAGS_HELM_50, TORAGS_HELM_75, TORAGS_HELM_100), ITEM_TORAGS_PLATEBODY(TORAGS_PLATEBODY, TORAGS_PLATEBODY_25, TORAGS_PLATEBODY_50, TORAGS_PLATEBODY_75, TORAGS_PLATEBODY_100), ITEM_TORAGS_PLATELEGS(TORAGS_PLATELEGS, TORAGS_PLATELEGS_25, TORAGS_PLATELEGS_50, TORAGS_PLATELEGS_75, TORAGS_PLATELEGS_100), ITEM_TORAGS_HAMMERS(TORAGS_HAMMERS, TORAGS_HAMMERS_25, TORAGS_HAMMERS_50, TORAGS_HAMMERS_75, TORAGS_HAMMERS_100), ITEM_VERACS_HELM(VERACS_HELM, VERACS_HELM_25, VERACS_HELM_50, VERACS_HELM_75, VERACS_HELM_100), ITEM_VERACS_BRASSARD(VERACS_BRASSARD, VERACS_BRASSARD_25, VERACS_BRASSARD_50, VERACS_BRASSARD_75, VERACS_BRASSARD_100), ITEM_VERACS_PLATESKIRT(VERACS_PLATESKIRT, VERACS_PLATESKIRT_25, VERACS_PLATESKIRT_50, VERACS_PLATESKIRT_75, VERACS_PLATESKIRT_100), ITEM_VERACS_FLAIL(VERACS_FLAIL, VERACS_FLAIL_25, VERACS_FLAIL_50, VERACS_FLAIL_75, VERACS_FLAIL_100), // Dragon equipment ornament kits ITEM_DRAGON_SCIMITAR(DRAGON_SCIMITAR, DRAGON_SCIMITAR_OR), ITEM_DRAGON_SCIMITAR_ORNAMENT_KIT(DRAGON_SCIMITAR_ORNAMENT_KIT, DRAGON_SCIMITAR_OR), ITEM_DRAGON_DEFENDER(DRAGON_DEFENDER_ORNAMENT_KIT, DRAGON_DEFENDER_T), ITEM_DRAGON_PICKAXE(DRAGON_PICKAXE, DRAGON_PICKAXE_12797), ITEM_DRAGON_KITESHIELD(DRAGON_KITESHIELD, DRAGON_KITESHIELD_G), ITEM_DRAGON_KITESHIELD_ORNAMENT_KIT(DRAGON_KITESHIELD_ORNAMENT_KIT, DRAGON_KITESHIELD_G), ITEM_DRAGON_FULL_HELM(DRAGON_FULL_HELM, DRAGON_FULL_HELM_G), ITEM_DRAGON_FULL_HELM_ORNAMENT_KIT(DRAGON_FULL_HELM_ORNAMENT_KIT, DRAGON_FULL_HELM_G), ITEM_DRAGON_CHAINBODY(DRAGON_CHAINBODY_3140, DRAGON_CHAINBODY_G), ITEM_DRAGON_CHAINBODY_ORNAMENT_KIT(DRAGON_CHAINBODY_ORNAMENT_KIT, DRAGON_CHAINBODY_G), ITEM_DRAGON_PLATEBODY(DRAGON_PLATEBODY, DRAGON_PLATEBODY_G), ITEM_DRAGON_PLATEBODY_ORNAMENT_KIT(DRAGON_PLATEBODY_ORNAMENT_KIT, DRAGON_PLATEBODY_G), ITEM_DRAGON_PLATESKIRT(DRAGON_PLATESKIRT, DRAGON_PLATESKIRT_G), ITEM_DRAGON_SKIRT_ORNAMENT_KIT(DRAGON_LEGSSKIRT_ORNAMENT_KIT, DRAGON_PLATESKIRT_G), ITEM_DRAGON_PLATELEGS(DRAGON_PLATELEGS, DRAGON_PLATELEGS_G), ITEM_DRAGON_LEGS_ORNAMENT_KIT(DRAGON_LEGSSKIRT_ORNAMENT_KIT, DRAGON_PLATELEGS_G), ITEM_DRAGON_SQ_SHIELD(DRAGON_SQ_SHIELD, DRAGON_SQ_SHIELD_G), ITEM_DRAGON_SQ_SHIELD_ORNAMENT_KIT(DRAGON_SQ_SHIELD_ORNAMENT_KIT, DRAGON_SQ_SHIELD_G), ITEM_DRAGON_BOOTS(DRAGON_BOOTS, DRAGON_BOOTS_G), ITEM_DRAGON_BOOTS_ORNAMENT_KIT(DRAGON_BOOTS_ORNAMENT_KIT, DRAGON_BOOTS_G), // Godsword ornament kits ITEM_ARMADYL_GODSWORD(ARMADYL_GODSWORD, ARMADYL_GODSWORD_OR), ITEM_ARMADYL_GODSWORD_ORNAMENT_KIT(ARMADYL_GODSWORD_ORNAMENT_KIT, ARMADYL_GODSWORD_OR), ITEM_BANDOS_GODSWORD(BANDOS_GODSWORD, BANDOS_GODSWORD_OR), ITEM_BANDOS_GODSWORD_ORNAMENT_KIT(BANDOS_GODSWORD_ORNAMENT_KIT, BANDOS_GODSWORD_OR), ITEM_ZAMORAK_GODSWORD(ZAMORAK_GODSWORD, ZAMORAK_GODSWORD_OR), ITEM_ZAMORAK_GODSWORD_ORNAMENT_KIT(ZAMORAK_GODSWORD_ORNAMENT_KIT, ZAMORAK_GODSWORD_OR), ITEM_SARADOMIN_GODSWORD(SARADOMIN_GODSWORD, SARADOMIN_GODSWORD_OR), ITEM_SARADOMIN_GODSWORD_ORNAMENT_KIT(SARADOMIN_GODSWORD_ORNAMENT_KIT, SARADOMIN_GODSWORD_OR), // Jewellery ornament kits ITEM_AMULET_OF_TORTURE(AMULET_OF_TORTURE, AMULET_OF_TORTURE_OR), ITEM_TORTURE_ORNAMENT_KIT(TORTURE_ORNAMENT_KIT, AMULET_OF_TORTURE_OR), ITEM_NECKLACE_OF_ANGUISH(NECKLACE_OF_ANGUISH, NECKLACE_OF_ANGUISH_OR), ITEM_ANGUISH_ORNAMENT_KIT(ANGUISH_ORNAMENT_KIT, NECKLACE_OF_ANGUISH_OR), ITEM_OCCULT_NECKLACE(OCCULT_NECKLACE, OCCULT_NECKLACE_OR), ITEM_OCCULT_ORNAMENT_KIT(OCCULT_ORNAMENT_KIT, OCCULT_NECKLACE_OR), ITE_AMULET_OF_FURY(AMULET_OF_FURY, AMULET_OF_FURY_OR), ITE_FURY_ORNAMENT_KIT(FURY_ORNAMENT_KIT, AMULET_OF_FURY_OR), // Ensouled heads ITEM_ENSOULED_GOBLIN_HEAD(ENSOULED_GOBLIN_HEAD_13448, ENSOULED_GOBLIN_HEAD), ITEM_ENSOULED_MONKEY_HEAD(ENSOULED_MONKEY_HEAD_13451, ENSOULED_MONKEY_HEAD), ITEM_ENSOULED_IMP_HEAD(ENSOULED_IMP_HEAD_13454, ENSOULED_IMP_HEAD), ITEM_ENSOULED_MINOTAUR_HEAD(ENSOULED_MINOTAUR_HEAD_13457, ENSOULED_MINOTAUR_HEAD), ITEM_ENSOULED_SCORPION_HEAD(ENSOULED_SCORPION_HEAD_13460, ENSOULED_SCORPION_HEAD), ITEM_ENSOULED_BEAR_HEAD(ENSOULED_BEAR_HEAD_13463, ENSOULED_BEAR_HEAD), ITEM_ENSOULED_UNICORN_HEAD(ENSOULED_UNICORN_HEAD_13466, ENSOULED_UNICORN_HEAD), ITEM_ENSOULED_DOG_HEAD(ENSOULED_DOG_HEAD_13469, ENSOULED_DOG_HEAD), ITEM_ENSOULED_CHAOS_DRUID_HEAD(ENSOULED_CHAOS_DRUID_HEAD_13472, ENSOULED_CHAOS_DRUID_HEAD), ITEM_ENSOULED_GIANT_HEAD(ENSOULED_GIANT_HEAD_13475, ENSOULED_GIANT_HEAD), ITEM_ENSOULED_OGRE_HEAD(ENSOULED_OGRE_HEAD_13478, ENSOULED_OGRE_HEAD), ITEM_ENSOULED_ELF_HEAD(ENSOULED_ELF_HEAD_13481, ENSOULED_ELF_HEAD), ITEM_ENSOULED_TROLL_HEAD(ENSOULED_TROLL_HEAD_13484, ENSOULED_TROLL_HEAD), ITEM_ENSOULED_HORROR_HEAD(ENSOULED_HORROR_HEAD_13487, ENSOULED_HORROR_HEAD), ITEM_ENSOULED_KALPHITE_HEAD(ENSOULED_KALPHITE_HEAD_13490, ENSOULED_KALPHITE_HEAD), ITEM_ENSOULED_DAGANNOTH_HEAD(ENSOULED_DAGANNOTH_HEAD_13493, ENSOULED_DAGANNOTH_HEAD), ITEM_ENSOULED_BLOODVELD_HEAD(ENSOULED_BLOODVELD_HEAD_13496, ENSOULED_BLOODVELD_HEAD), ITEM_ENSOULED_TZHAAR_HEAD(ENSOULED_TZHAAR_HEAD_13499, ENSOULED_TZHAAR_HEAD), ITEM_ENSOULED_DEMON_HEAD(ENSOULED_DEMON_HEAD_13502, ENSOULED_DEMON_HEAD), ITEM_ENSOULED_AVIANSIE_HEAD(ENSOULED_AVIANSIE_HEAD_13505, ENSOULED_AVIANSIE_HEAD), ITEM_ENSOULED_ABYSSAL_HEAD(ENSOULED_ABYSSAL_HEAD_13508, ENSOULED_ABYSSAL_HEAD), ITEM_ENSOULED_DRAGON_HEAD(ENSOULED_DRAGON_HEAD_13511, ENSOULED_DRAGON_HEAD), // Imbued rings ITEM_BERSERKER_RING(BERSERKER_RING, BERSERKER_RING_I), ITEM_SEERS_RING(SEERS_RING, SEERS_RING_I), ITEM_WARRIOR_RING(WARRIOR_RING, WARRIOR_RING_I), ITEM_ARCHERS_RING(ARCHERS_RING, ARCHERS_RING_I), ITEM_TREASONOUS_RING(TREASONOUS_RING, TREASONOUS_RING_I), ITEM_TYRANNICAL_RING(TYRANNICAL_RING, TYRANNICAL_RING_I), ITEM_RING_OF_THE_GODS(RING_OF_THE_GODS, RING_OF_THE_GODS_I), ITEM_RING_OF_SUFFERING(RING_OF_SUFFERING, RING_OF_SUFFERING_I, RING_OF_SUFFERING_R, RING_OF_SUFFERING_RI), ITEM_GRANITE_RING(GRANITE_RING, GRANITE_RING_I), // Bounty hunter ITEM_GRANITE_MAUL(GRANITE_MAUL, GRANITE_MAUL_12848), ITEM_MAGIC_SHORTBOW(MAGIC_SHORTBOW, MAGIC_SHORTBOW_I), ITEM_SARADOMINS_SWORD(SARADOMIN_SWORD, SARADOMINS_TEAR), // Jewellery with charges ITEM_RING_OF_WEALTH(RING_OF_WEALTH, RING_OF_WEALTH_I, RING_OF_WEALTH_1, RING_OF_WEALTH_I1, RING_OF_WEALTH_2, RING_OF_WEALTH_I2, RING_OF_WEALTH_3, RING_OF_WEALTH_I3, RING_OF_WEALTH_4, RING_OF_WEALTH_I4, RING_OF_WEALTH_I5), ITEM_AMULET_OF_GLORY(AMULET_OF_GLORY, AMULET_OF_GLORY1, AMULET_OF_GLORY2, AMULET_OF_GLORY3, AMULET_OF_GLORY5), ITEM_AMULET_OF_GLORY_T(AMULET_OF_GLORY_T, AMULET_OF_GLORY_T1, AMULET_OF_GLORY_T2, AMULET_OF_GLORY_T3, AMULET_OF_GLORY_T5), ITEM_SKILLS_NECKLACE(SKILLS_NECKLACE, SKILLS_NECKLACE1, SKILLS_NECKLACE2, SKILLS_NECKLACE3, SKILLS_NECKLACE5), ITEM_RING_OF_DUELING(RING_OF_DUELING8, RING_OF_DUELING1, RING_OF_DUELING2, RING_OF_DUELING3, RING_OF_DUELING4, RING_OF_DUELING5, RING_OF_DUELING6, RING_OF_DUELING7), ITEM_GAMES_NECKLACE(GAMES_NECKLACE8, GAMES_NECKLACE1, GAMES_NECKLACE2, GAMES_NECKLACE3, GAMES_NECKLACE4, GAMES_NECKLACE5, GAMES_NECKLACE6, GAMES_NECKLACE7), // Degradable/charged weaponry/armour ITEM_ABYSSAL_WHIP(ABYSSAL_WHIP, VOLCANIC_ABYSSAL_WHIP, FROZEN_ABYSSAL_WHIP), ITEM_KRAKEN_TENTACLE(KRAKEN_TENTACLE, ABYSSAL_TENTACLE), ITEM_TRIDENT_OF_THE_SEAS(UNCHARGED_TRIDENT, TRIDENT_OF_THE_SEAS), ITEM_TRIDENT_OF_THE_SEAS_E(UNCHARGED_TRIDENT_E, TRIDENT_OF_THE_SEAS_E), ITEM_TRIDENT_OF_THE_SWAMP(UNCHARGED_TOXIC_TRIDENT, TRIDENT_OF_THE_SWAMP), ITEM_TRIDENT_OF_THE_SWAMP_E(UNCHARGED_TOXIC_TRIDENT_E, TRIDENT_OF_THE_SWAMP_E), ITEM_TOXIC_BLOWPIPE(TOXIC_BLOWPIPE_EMPTY, TOXIC_BLOWPIPE), ITEM_SERPENTINE_HELM(SERPENTINE_HELM_UNCHARGED, SERPENTINE_HELM, TANZANITE_HELM_UNCHARGED, TANZANITE_HELM, MAGMA_HELM_UNCHARGED, MAGMA_HELM), ITEM_DRAGONFIRE_SHIELD(DRAGONFIRE_SHIELD_11284, DRAGONFIRE_SHIELD), ITEM_DRAGONFIRE_WARD(DRAGONFIRE_WARD_22003, DRAGONFIRE_WARD), ITEM_ANCIENT_WYVERN_SHIELD(ANCIENT_WYVERN_SHIELD_21634, ANCIENT_WYVERN_SHIELD), ITEM_SANGUINESTI_STAFF(SANGUINESTI_STAFF_UNCHARGED, SANGUINESTI_STAFF), // Infinity colour kits ITEM_INFINITY_TOP(INFINITY_TOP, INFINITY_TOP_10605, INFINITY_TOP_20574, DARK_INFINITY_TOP, LIGHT_INFINITY_TOP), ITEM_INFINITY_TOP_LIGHT_COLOUR_KIT(LIGHT_INFINITY_COLOUR_KIT, LIGHT_INFINITY_TOP), ITEM_INFINITY_TOP_DARK_COLOUR_KIT(DARK_INFINITY_COLOUR_KIT, DARK_INFINITY_TOP), ITEM_INFINITY_BOTTOMS(INFINITY_BOTTOMS, INFINITY_BOTTOMS_20575, DARK_INFINITY_BOTTOMS, LIGHT_INFINITY_BOTTOMS), ITEM_INFINITY_BOTTOMS_LIGHT_COLOUR_KIT(LIGHT_INFINITY_COLOUR_KIT, LIGHT_INFINITY_BOTTOMS), ITEM_INFINITY_BOTTOMS_DARK_COLOUR_KIT(DARK_INFINITY_COLOUR_KIT, DARK_INFINITY_BOTTOMS), ITEM_INFINITY_HAT(INFINITY_HAT, DARK_INFINITY_HAT, LIGHT_INFINITY_HAT), ITEM_INFINITY_HAT_LIGHT_COLOUR_KIT(LIGHT_INFINITY_COLOUR_KIT, LIGHT_INFINITY_HAT), ITEM_INFINITY_HAT_DARK_COLOUR_KIT(DARK_INFINITY_COLOUR_KIT, DARK_INFINITY_HAT), // Miscellaneous ornament kits ITEM_DARK_BOW(DARK_BOW, DARK_BOW_12765, DARK_BOW_12766, DARK_BOW_12767, DARK_BOW_12768, DARK_BOW_20408), ITEM_ODIUM_WARD(ODIUM_WARD, ODIUM_WARD_12807), ITEM_MALEDICTION_WARD(MALEDICTION_WARD, MALEDICTION_WARD_12806), ITEM_STEAM_BATTLESTAFF(STEAM_BATTLESTAFF, STEAM_BATTLESTAFF_12795), ITEM_LAVA_BATTLESTAFF(LAVA_BATTLESTAFF, LAVA_BATTLESTAFF_21198), // Slayer helm/black mask ITEM_BLACK_MASK( BLACK_MASK, BLACK_MASK_I, BLACK_MASK_1, BLACK_MASK_1_I, BLACK_MASK_2, BLACK_MASK_2_I, BLACK_MASK_3, BLACK_MASK_3_I, BLACK_MASK_4, BLACK_MASK_4_I, BLACK_MASK_5, BLACK_MASK_5_I, BLACK_MASK_6, BLACK_MASK_6_I, BLACK_MASK_7, BLACK_MASK_7_I, BLACK_MASK_8, BLACK_MASK_8_I, BLACK_MASK_9, BLACK_MASK_9_I, BLACK_MASK_10_I, SLAYER_HELMET, SLAYER_HELMET_I, BLACK_SLAYER_HELMET, BLACK_SLAYER_HELMET_I, PURPLE_SLAYER_HELMET, PURPLE_SLAYER_HELMET_I, RED_SLAYER_HELMET, RED_SLAYER_HELMET_I, GREEN_SLAYER_HELMET, GREEN_SLAYER_HELMET_I, TURQUOISE_SLAYER_HELMET, TURQUOISE_SLAYER_HELMET_I); private static final Multimap<Integer, Integer> MAPPINGS = HashMultimap.create(); private final int tradeableItem; private final int[] untradableItems; static { for (final ItemMapping item : values()) { for (int itemId : item.untradableItems) { MAPPINGS.put(itemId, item.tradeableItem); } } } ItemMapping(int tradeableItem, int... untradableItems) { this.tradeableItem = tradeableItem; this.untradableItems = untradableItems; } /** * Get collection of items that are mapped from single item id. * * @param itemId the item id * @return the collection */ public static Collection<Integer> map(int itemId) { final Collection<Integer> mapping = MAPPINGS.get(itemId); if (mapping == null || mapping.isEmpty()) { return Collections.singleton(itemId); } return mapping; } /** * Map an item from its untradeable version to its tradeable version * * @param itemId * @return */ public static int mapFirst(int itemId) { final Collection<Integer> mapping = MAPPINGS.get(itemId); if (mapping == null || mapping.isEmpty()) { return itemId; } return mapping.iterator().next(); } }
package com.marcobehler.saito.core.files; import com.marcobehler.saito.core.pagination.PaginationException; import com.marcobehler.saito.core.rendering.RenderingModel; import com.marcobehler.saito.core.configuration.SaitoConfig; import com.marcobehler.saito.core.domain.FrontMatter; import com.marcobehler.saito.core.domain.TemplateContent; import com.marcobehler.saito.core.rendering.RenderingEngine; import com.marcobehler.saito.core.util.PathUtils; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Map; /** * @author Marco Behler <marco@marcobehler.com> */ @Slf4j @EqualsAndHashCode(callSuper = true) public class Template extends SaitoFile { private static final String TEMPLATE_FILE_EXTENSION = ".ftl"; @Getter private final FrontMatter frontmatter; @Getter private final TemplateContent content; // can be HTML, asciidoc, md @Setter @Getter private Layout layout; public Template(Path sourceDirectory, Path relativePath) { super(sourceDirectory, relativePath); this.frontmatter = FrontMatter.of(getDataAsString()); this.content = TemplateContent.of(getDataAsString()); } public void process(RenderingModel renderingModel, Path targetDir, RenderingEngine engine) { if (layout == null) { throw new IllegalStateException("Layout must not be null"); } String relativePath = PathUtils.stripExtension(getRelativePath(), TEMPLATE_FILE_EXTENSION); Path targetFile = getTargetFile(renderingModel, targetDir, relativePath); ThreadLocal<Path> tl = (ThreadLocal<Path>) renderingModel.getParameters().get(RenderingModel.TEMPLATE_OUTPUT_PATH); tl.set(targetFile); try { engine.render(this, targetFile, renderingModel); } catch (PaginationException e) { log.info("Starting to paginate ", e); int pages = e.getPages(); for (int i = 1; i < pages; i++ ) { // TODO refactor targetFile = isDirectoryIndexEnabled(renderingModel.getSaitoConfig(), relativePath) ? getDirectoryIndexTargetFile(targetDir.resolve( i == 1 ? "" : "page" + i), relativePath) : getTargetFile(targetDir, relativePath + ((i == 1) ? "" : "page=" + i)); engine.render(this, targetFile, renderingModel); } } } protected Path getTargetFile(final RenderingModel renderingModel, final Path targetDir, final String relativePath) { return isDirectoryIndexEnabled(renderingModel.getSaitoConfig(), relativePath) ? getDirectoryIndexTargetFile(targetDir, relativePath) : getTargetFile(targetDir, relativePath); } @SneakyThrows private Path getDirectoryIndexTargetFile(Path targetDir, String relativePath) { relativePath = PathUtils.stripExtension(Paths.get(relativePath), ".html"); Path dir = targetDir.resolve(relativePath); Path targetSubDir = Files.createDirectories(dir); return targetSubDir.resolve("index.html"); } private Path getTargetFile(Path targetDir, String relativePath) { Path targetFile = targetDir.resolve(relativePath); if (!Files.exists(targetFile.getParent())) { try { Files.createDirectories(targetFile.getParent()); } catch (IOException e) { log.error("Error creating directory", e); } } return targetFile; } private boolean isDirectoryIndexEnabled(SaitoConfig config, String relativePath) { return config.isDirectoryIndexes() && !relativePath.endsWith("index.html"); // if the file is already called index.html, skip it } public String getLayoutName() { Map<String, Object> frontMatter = getFrontmatter(); return (String) frontMatter.getOrDefault("layout", "layout"); } }
package gov.va.isaac; import gov.va.isaac.dialog.ErrorDialog; import java.net.URL; import javafx.application.Application; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.stage.WindowEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.javafx.tk.Toolkit; /** * Taxonomy viewer app class. * * @author ocarlsen */ public class App extends Application { private static final Logger LOG = LoggerFactory.getLogger(App.class); private AppController controller; private ErrorDialog errorDialog; @Override public void start(Stage primaryStage) throws Exception { URL fxmlURL = this.getClass().getResource("App.fxml"); FXMLLoader loader = new FXMLLoader(fxmlURL); Parent root = (Parent) loader.load(); this.controller = loader.getController(); controller.setApp(this); primaryStage.setTitle("Taxonomy Viewer"); primaryStage.setScene(new Scene(root)); primaryStage.sizeToScene(); primaryStage.show(); // Set minimum dimensions. primaryStage.setMinHeight(primaryStage.getHeight()); primaryStage.setMinWidth(primaryStage.getWidth()); // Handle window close event. primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { shutdown(); } }); // Reusable error dialog. this.errorDialog = new ErrorDialog(primaryStage); } public void showErrorDialog(final String title, final String message, final String details) { // Make sure in application thread. Toolkit.getToolkit().checkFxUserThread(); errorDialog.setVariables(title, message, details); errorDialog.showAndWait(); } private void shutdown() { LOG.info("Shutting down"); try { controller.shutdown(); } catch (Exception ex) { String message = "Trouble shutting down"; LOG.warn(message, ex); showErrorDialog("Oops!", message, ex.getMessage()); } LOG.info("Finished shutting down"); //System.exit(0); } public static void main(String[] args) { Application.launch(args); } }
package xyz.bingesurfing; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ThreadLocalRandom; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.concurrent.Worker.State; import javafx.fxml.FXML; import javafx.scene.control.TextArea; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; public class WebViewController { private Feeder f; private List<String> urls; private Timer timer; @FXML private WebView webView; @FXML private TextArea textArea; private void logging(String s) { System.out.println(s); textArea.appendText(s+"\n"); } public void destroy() { System.out.println("destroy"); if(null != timer) timer.cancel(); } @FXML private void initialize() { timer = new Timer(); f = new Feeder(); f.read(); urls = f.getUrls(); webView.setZoom(Defaults.ZOOM); WebEngine engine = webView.getEngine(); engine.getLoadWorker().stateProperty().addListener( new ChangeListener<State>() { @Override public void changed(@SuppressWarnings("rawtypes") ObservableValue ov, State oldState, State newState) { boolean doNextURL=false; switch(newState) { case SUCCEEDED: logging("called"); doNextURL=true; break; case CANCELLED: logging("cancelled"); doNextURL=true; break; case FAILED: logging("failed"); doNextURL=true; break; case READY: logging("ready"); break; case RUNNING: logging("running"); break; case SCHEDULED: textArea.clear(); logging("scheduled"); break; default: logging("??"); break; } // switch if(doNextURL) { if(urls.isEmpty()) { logging("fetching new feed data ..."); f.read(); urls = f.getUrls(); } int waitSeconds = ThreadLocalRandom.current().nextInt(Defaults.WAITSECONDSFROM, Defaults.WAITSECONDSTO); logging("wait " + waitSeconds + " seconds for loading next page."); timer.schedule(new TimerTask() { @Override public void run() { Platform.runLater(() -> { if(!urls.isEmpty()) { engine.loadContent(""); System.gc(); engine.load(urls.remove(0)); } }); } // run }, waitSeconds*1000); } } }); engine.load(urls.remove(0)); } }
package com.jme3.material; import com.jme3.asset.TextureKey; import com.jme3.export.InputCapsule; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.export.OutputCapsule; import com.jme3.export.Savable; import com.jme3.math.ColorRGBA; import com.jme3.math.Quaternion; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.math.Vector4f; import com.jme3.renderer.GL1Renderer; import com.jme3.renderer.Renderer; import com.jme3.shader.VarType; import com.jme3.texture.Texture; import com.jme3.texture.Texture.WrapMode; import java.io.IOException; public class MatParam implements Savable, Cloneable { protected VarType type; protected String name; protected Object value; protected FixedFuncBinding ffBinding; public MatParam(VarType type, String name, Object value, FixedFuncBinding ffBinding){ this.type = type; this.name = name; this.value = value; this.ffBinding = ffBinding; } public MatParam(){ } public FixedFuncBinding getFixedFuncBinding() { return ffBinding; } public VarType getVarType() { return type; } public String getName(){ return name; } public void setName(String name){ this.name=name; } public Object getValue(){ return value; } public void setValue(Object value){ this.value = value; } /** * Returns the material parameter value as it would appear in a J3M * file. E.g.<br/> * <code> * MaterialParameters {<br/> * ABC : 1 2 3 4<br/> * }<br/> * </code> * Assuming "ABC" is a Vector4 parameter, then the value * "1 2 3 4" would be returned by this method. * <br/><br/> * @return material parameter value as it would appear in a J3M file. */ public String getValueAsString(){ switch (type){ case Boolean: case Float: case Int: return value.toString(); case Vector2: Vector2f v2 = (Vector2f) value; return v2.getX() + " " + v2.getY(); case Vector3: Vector3f v3 = (Vector3f) value; return v3.getX() + " " + v3.getY() + " " + v3.getZ(); case Vector4: // can be either ColorRGBA, Vector4f or Quaternion if (value instanceof Vector4f){ Vector4f v4 = (Vector4f) value; return v4.getX() + " " + v4.getY() + " " + v4.getZ() + " " + v4.getW(); }else if (value instanceof ColorRGBA){ ColorRGBA color = (ColorRGBA) value; return color.getRed() + " " + color.getGreen() + " " + color.getBlue() + " " + color.getAlpha(); }else if (value instanceof Quaternion){ Quaternion quat = (Quaternion) value; return quat.getX() + " " + quat.getY() + " " + quat.getZ() + " " + quat.getW(); }else{ throw new UnsupportedOperationException("Unexpected Vector4 type: " + value); } case Texture2D: case Texture3D: case TextureArray: case TextureBuffer: case TextureCubeMap: Texture texVal = (Texture) value; TextureKey texKey = (TextureKey) texVal.getKey(); String ret = ""; if (texKey.isFlipY()) ret += "Flip "; if (texVal.getWrap(Texture.WrapAxis.S) == WrapMode.Repeat) ret += "Repeat "; return ret + texKey.getName(); default: return null; // parameter type not supported in J3M } } @Override public MatParam clone(){ try{ MatParam param = (MatParam) super.clone(); return param; }catch (CloneNotSupportedException ex){ throw new AssertionError(); } } public void write(JmeExporter ex) throws IOException{ OutputCapsule oc = ex.getCapsule(this); oc.write(type, "varType", null); oc.write(name, "name", null); oc.write(ffBinding, "ff_binding", null); if (value instanceof Savable){ Savable s = (Savable) value; oc.write(s, "value_savable", null); }else if (value instanceof Float){ Float f = (Float) value; oc.write(f.floatValue(), "value_float", 0f); }else if (value instanceof Integer){ Integer i = (Integer) value; oc.write(i.intValue(), "value_int", 0); }else if (value instanceof Boolean){ Boolean b = (Boolean) value; oc.write(b.booleanValue(), "value_bool", false); } } public void read(JmeImporter im) throws IOException{ InputCapsule ic = im.getCapsule(this); type = ic.readEnum("varType", VarType.class, null); name = ic.readString("name", null); ffBinding = ic.readEnum("ff_binding", FixedFuncBinding.class, null); switch (getVarType()){ case Boolean: value = ic.readBoolean("value_bool", false); break; case Float: value = ic.readFloat("value_float", 0f); break; case Int: value = ic.readInt("value_int", 0); break; default: value = ic.readSavable("value_savable", null); break; } } @Override public boolean equals(Object other){ if (!(other instanceof MatParam)) return false; MatParam otherParam = (MatParam) other; return otherParam.type == type && otherParam.name.equals(name); } @Override public String toString(){ return type.name()+" "+name; } public void apply(Renderer r, Technique technique) { TechniqueDef techDef = technique.getDef(); if (techDef.isUsingShaders()) { technique.updateUniformParam(getName(), getVarType(), getValue(), true); } if (ffBinding != null && r instanceof GL1Renderer){ ((GL1Renderer)r).setFixedFuncBinding(ffBinding, getValue()); } } }
package com.gallatinsystems.image; public class ImageUtils { /* * Utility method to return the parts of an image path for S3 * Position 0 = web domain with bucket ends with / * Position 1 = middle path elements ends with / * Position 2 = file name */ public static String[] parseImageParts(String url) { String[] parts = new String[3]; url = url.replace("http: if(url.contains("?")){ url = url.substring(0, url.indexOf("?")); } String[] items = url.split("/"); if (items.length == 3) { // no country in path parts[0]=("http://:" + items[0] + "/"); parts[1]=(items[1] + "/"); parts[2]=(items[2]); } else if (items.length > 3) { parts[0]=("http://:" + items[0] + "/"); String middlePath = ""; int i = 0; for (i = 1; i < items.length - 1; i++) middlePath += items[i] + "/"; parts[1]=(middlePath); parts[2]=(items[i]); } return parts; } public static void main(String[] args) { String test1 = "http://waterforpeople.s3.amazonaws.com/images/wfpPhoto10062903227521.jpg?random=123"; String test2 = "http://waterforpeople.s3.amazonaws.com/images/hn/ch003[1].jpg?test"; System.out.println(test1); for (String item : parseImageParts(test1)) System.out.println(" " + item); System.out.println(test2); for (String item : parseImageParts(test2)) System.out.println(" " + item); } }
// Notes.java package loci.ome.notes; import com.jgoodies.forms.layout.*; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.*; import java.util.*; import javax.swing.*; import javax.swing.border.LineBorder; import javax.swing.filechooser.FileFilter; import loci.formats.ImageReader; import loci.formats.MetadataTools; import loci.formats.RandomAccessStream; import loci.formats.gui.GUITools; import loci.formats.meta.AggregateMetadata; import loci.formats.meta.MetadataRetrieve; import loci.formats.meta.MetadataStore; public class Notes extends JFrame implements ActionListener { // -- Constants -- /** Template that is loaded automatically. */ private static final String DEFAULT_TEMPLATE = "templates/viewer.template"; private static final CellConstraints CC = new CellConstraints(); // -- Fields -- /** Progress/status bar. */ private JProgressBar progress; /** Menu bar. */ private JMenuBar menubar; /** Main viewing area. */ private JTabbedPane tabPane; /** Current GUI template. */ private Template currentTemplate; /** Current template file name. */ private String templateName; /** Foreground (font) color. */ private Color foreground; /** Background color. */ private Color background; /** Current font. */ private Font font; /** Name of the current image file. */ private String currentFile; /** Thumbnails for the current file. */ private Vector thumb; private AggregateMetadata metadata; // -- Constructor -- /** Constructs a new main window with the default template. */ public Notes() { this(null, (String) null); } /** * Constructs a new main window with the given metadata, * and default template. */ public Notes(AggregateMetadata store) { this(null, store); } /** Constructs a new main window with the given metadata and template. */ public Notes(String template, AggregateMetadata store) { super("OME Notes"); setupWindow(); // load the appropriate template if (template != null) { loadTemplate(template); } else { templateName = DEFAULT_TEMPLATE; loadTemplate(Notes.class.getResourceAsStream(DEFAULT_TEMPLATE)); } metadata = store; setDefaultCloseOperation(DISPOSE_ON_CLOSE); setVisible(true); } /** Constructs a new main window with the given template. */ public Notes(String template, String newfile) { super("OME Notes"); setupWindow(); // load the appropriate template if (template != null) { loadTemplate(template); } else { templateName = DEFAULT_TEMPLATE; loadTemplate(Notes.class.getResourceAsStream(DEFAULT_TEMPLATE)); } try { if (newfile != null) openFile(newfile); } catch (Exception e) { e.printStackTrace(); } setDefaultCloseOperation(DISPOSE_ON_CLOSE); setVisible(true); } // -- Notes API methods -- /** Load and apply a template from the specified file. */ public void loadTemplate(String filename) { // clear out previous template progress.setString("Loading template " + filename); templateName = filename; // parse the template file try { loadTemplate(new Template(filename)); } catch (IOException e) { e.printStackTrace(); } } /** Load and apply a template from the specified InputStream. */ public void loadTemplate(InputStream stream) { progress.setString("Loading template..."); try { loadTemplate(new Template(stream)); } catch (IOException e) { e.printStackTrace(); } } /** Load and apply the given template. */ public void loadTemplate(Template t) { currentTemplate = t; if (tabPane != null) getContentPane().remove(tabPane); tabPane = new JTabbedPane(); getContentPane().add(tabPane); // retrieve defined GUI parameters setPreferredSize(new Dimension(currentTemplate.getDefaultWidth(), currentTemplate.getDefaultHeight())); font = new Font(currentTemplate.getFontStyle(), Font.PLAIN, currentTemplate.getFontSize()); int[] fore = currentTemplate.getFontColor(); int[] back = currentTemplate.getBackgroundColor(); foreground = new Color(fore[0], fore[1], fore[2]); background = new Color(back[0], back[1], back[2]); // set up all of the defined tabs and fields TemplateTab[] tabs = currentTemplate.getTabs(); for (int i=0; i<tabs.length; i++) { Vector groups = tabs[i].getAllGroups(); Vector fields = tabs[i].getAllFields(); JScrollPane scroll = new JScrollPane(); JPanel panel = new JPanel(); String rowString = "pref,"; String colString = "pref,pref:grow,pref:grow,pref:grow,"; int numRows = tabs[i].getRows(); int numColumns = tabs[i].getColumns(); for (int j=0; j<numRows; j++) { rowString += "pref:grow,pref,"; } for (int j=0; j<numColumns; j++) { colString += "pref:grow,pref,pref:grow,pref,"; } FormLayout l = new FormLayout(colString, rowString); panel.setLayout(l); scroll.getViewport().add(panel); int[] rowNumber = new int[l.getColumnCount()]; Arrays.fill(rowNumber, 2); for (int j=0; j<groups.size(); j++) { TemplateGroup group = (TemplateGroup) groups.get(j); for (int r=0; r<group.getRepetitions(); r++) { FormLayout layout = (FormLayout) panel.getLayout(); int col = 2; if (currentTemplate.editTemplateFields()) { JButton add = new JButton("+"); add.setActionCommand("cloneGroup " + i + "-" + j); add.addActionListener(this); panel.add(add, CC.xy(col, rowNumber[col - 1])); rowNumber[col - 1]++; col++; JButton remove = new JButton("-"); remove.setActionCommand("removeGroup" + i + "-" + j); remove.addActionListener(this); panel.add(remove, CC.xy(col, rowNumber[col - 1])); rowNumber[col - 1]++; col++; } panel.add(new JLabel(group.getName() + " #" + (r + 1)), CC.xy(col, rowNumber[col - 1])); rowNumber[col - 1] += 3; col++; for (int k=0; k<group.getNumFields(); k++) { TemplateField field = group.getField(r, k); setupField(field, col, r, rowNumber, panel); } rowNumber[col - 1]++; } } for (int j=0; j<fields.size(); j++) { TemplateField f = tabs[i].getField(j); setupField(f, 2, 0, rowNumber, panel); } tabPane.add(scroll, tabs[i].getName()); } setFontAndColors(this); changeEditable(currentTemplate.isEditable(), this); progress.setString(""); pack(); } /** Recursively set the font and colors for the root and all children. */ public void setFontAndColors(Container root) { Component[] components = root instanceof JMenu ? ((JMenu) root).getMenuComponents() : root.getComponents(); for (int i=0; i<components.length; i++) { components[i].setFont(font); components[i].setForeground(foreground); components[i].setBackground(background); if (components[i] instanceof JTextArea || components[i] instanceof JComboBox || components[i] instanceof JCheckBox) { LineBorder b = new LineBorder(foreground); ((JComponent) components[i]).setBorder(b); } if (components[i] instanceof Container) { setFontAndColors((Container) components[i]); } } } /** Recursively enable or disable all chilren (non-Container objects). */ public void changeEditable(boolean enable, Container root) { Component[] c = root.getComponents(); for (int i=0; i<c.length; i++) { if (!(c[i] instanceof JMenuBar) && !(c[i] instanceof JMenu) && !(c[i] instanceof JMenuItem) && !(c[i] instanceof JLabel) && !(c[i] instanceof JScrollBar) && !(c[i] instanceof JTabbedPane)) { c[i].setEnabled(enable); } if (c[i] instanceof Container) { changeEditable(enable, (Container) c[i]); } } } // -- ActionListener API methods -- public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("new")) { // check if the user wants to save the current metadata first int s = JOptionPane.showConfirmDialog(this, "Save current metadata?", "", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE); if (s == JOptionPane.YES_OPTION) { actionPerformed(new ActionEvent(this, -1, "save")); } thumb.clear(); if (templateName.equals(DEFAULT_TEMPLATE)) { loadTemplate(Notes.class.getResourceAsStream(DEFAULT_TEMPLATE)); } else loadTemplate(templateName); } else if (cmd.equals("open")) { progress.setString("Opening file..."); try { ImageReader reader = new ImageReader(); JFileChooser chooser = GUITools.buildFileChooser(reader); int status = chooser.showOpenDialog(this); if (status == JFileChooser.APPROVE_OPTION) { currentFile = chooser.getSelectedFile().getAbsolutePath(); } if (currentFile == null) return; thumb.clear(); if (templateName.equals(DEFAULT_TEMPLATE)) { loadTemplate(Notes.class.getResourceAsStream(DEFAULT_TEMPLATE)); } else loadTemplate(templateName); openFile(currentFile); } catch (Exception exc) { exc.printStackTrace(); } } else if (cmd.equals("save")) { progress.setString("Saving metadata to companion file..."); currentTemplate.saveFields(metadata); // always save to the current filename + ".ome" metadata = new AggregateMetadata(new ArrayList()); try { String name = currentFile; if (name == null) { JFileChooser chooser = new JFileChooser(); FileFilter filter = new FileFilter() { public boolean accept(File f) { return true; } public String getDescription() { return "OME-XML files"; } }; chooser.setFileFilter(filter); int status = chooser.showSaveDialog(this); if (status == JFileChooser.APPROVE_OPTION) { name = chooser.getSelectedFile().getAbsolutePath(); if (name == null) return; } } if (name == null) return; if (!name.endsWith(".ome")) name += ".ome"; java.util.List delegates = metadata.getDelegates(); String xml = null; for (int i=0; i<delegates.size(); i++) { if (MetadataTools.isOMEXMLMetadata(delegates.get(i))) { xml = MetadataTools.getOMEXML((MetadataRetrieve) delegates.get(i)); } } File f = new File(name); FileWriter writer = new FileWriter(f); writer.write(xml); progress.setString("Finished writing companion file (" + name + ")"); } catch (Exception io) { io.printStackTrace(); } } else if (cmd.equals("close")) { dispose(); } else if (cmd.equals("load")) { // prompt for the new template file JFileChooser chooser = new JFileChooser(); FileFilter filter = new FileFilter() { public boolean accept(File f) { return f.getAbsolutePath().endsWith(".template") || f.isDirectory(); } public String getDescription() { return "OME Notes Templates"; } }; chooser.setFileFilter(filter); int status = chooser.showOpenDialog(this); if (status == JFileChooser.APPROVE_OPTION) { loadTemplate(chooser.getSelectedFile().getAbsolutePath()); } try { if (currentFile != null) openFile(currentFile); } catch (Exception exc) { exc.printStackTrace(); } } else if (cmd.startsWith("cloneGroup")) { cmd = cmd.substring(10); int tabIndex = Integer.parseInt(cmd.substring(0, cmd.indexOf("-")).trim()); int groupIndex = Integer.parseInt(cmd.substring(cmd.indexOf("-") + 1).trim()); TemplateTab tab = currentTemplate.getTabs()[tabIndex]; TemplateGroup group = tab.getGroup(groupIndex); group.setRepetitions(group.getRepetitions() + 1); int tabIdx = tabPane.getSelectedIndex(); loadTemplate(currentTemplate); try { if (currentFile != null) openFile(currentFile); } catch (Exception exc) { exc.printStackTrace(); } tabPane.setSelectedIndex(tabIdx); } else if (cmd.startsWith("removeGroup")) { cmd = cmd.substring(11); int tabIndex = Integer.parseInt(cmd.substring(0, cmd.indexOf("-")).trim()); int groupIndex = Integer.parseInt(cmd.substring(cmd.indexOf("-") + 1).trim()); TemplateTab tab = currentTemplate.getTabs()[tabIndex]; TemplateGroup group = tab.getGroup(groupIndex); group.setRepetitions(group.getRepetitions() - 1); int tabIdx = tabPane.getSelectedIndex(); loadTemplate(currentTemplate); try { if (currentFile != null) openFile(currentFile); } catch (Exception exc) { exc.printStackTrace(); } tabPane.setSelectedIndex(tabIdx); } } // -- Helper methods -- private void setupWindow() { thumb = new Vector(); // set up the main panel JPanel contentPane = new JPanel(); // set up the menu bar menubar = new JMenuBar(); JMenu file = new JMenu("File"); JMenuItem newFile = new JMenuItem("New..."); newFile.setActionCommand("new"); newFile.addActionListener(this); file.add(newFile); JMenuItem openFile = new JMenuItem("Open"); openFile.setActionCommand("open"); openFile.addActionListener(this); file.add(openFile); JMenuItem saveFile = new JMenuItem("Save"); saveFile.setActionCommand("save"); saveFile.addActionListener(this); file.add(saveFile); JMenuItem close = new JMenuItem("Close"); close.setActionCommand("close"); close.addActionListener(this); file.add(close); JMenu view = new JMenu("View"); JMenuItem loadTemplate = new JMenuItem("Switch Templates"); loadTemplate.setActionCommand("load"); loadTemplate.addActionListener(this); view.add(loadTemplate); view.add(new JSeparator()); menubar.add(file); menubar.add(view); // add the status bar progress = new JProgressBar(0, 1); progress.setStringPainted(true); menubar.add(progress); setJMenuBar(menubar); // provide a place to show metadata tabPane = new JTabbedPane(); contentPane.add(tabPane); } private void openFile(String file) throws Exception { currentFile = file; ImageReader reader = new ImageReader(); reader.setNormalized(true); reader.setOriginalMetadataPopulated(true); progress.setString("Reading " + currentFile); metadata = new AggregateMetadata(new ArrayList()); if (currentFile.endsWith(".ome")) { RandomAccessStream s = new RandomAccessStream(currentFile); String xml = s.readString((int) s.length()); s.close(); metadata.addDelegate(MetadataTools.createOMEXMLMetadata(xml)); } else { // first look for a companion file File companion = new File(currentFile + ".ome"); MetadataStore companionStore = null, readerStore = null; if (companion.exists()) { progress.setString("Reading companion file (" + companion + ")"); RandomAccessStream s = new RandomAccessStream(currentFile); String xml = s.readString((int) s.length()); s.close(); companionStore = MetadataTools.createOMEXMLMetadata(xml); } reader.setMetadataStore(MetadataTools.createOMEXMLMetadata()); reader.setId(currentFile); readerStore = reader.getMetadataStore(); if (companion.exists()) { // merge the two OMENode objects // this depends upon the precedence setting in the template progress.setString("Merging companion and original file..."); if (currentTemplate.preferCompanion()) { metadata.addDelegate(companionStore); metadata.addDelegate(readerStore); } else { metadata.addDelegate(readerStore); metadata.addDelegate(companionStore); } } else metadata.addDelegate(readerStore); // grab thumbnails for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); thumb.add(reader.openThumbImage(0)); } reader.close(); } progress.setString("Populating fields..."); currentTemplate.initializeFields(metadata); currentTemplate.populateFields(metadata); loadTemplate(currentTemplate); progress.setString(""); } /** Set up a new field in the current tab. */ private void setupField(TemplateField field, int col, int r, int[] rowNumber, JPanel panel) { JComponent c = field.getComponent(); if (field.getType().equals("thumbnail")) { BufferedImage thumbnail = null; if (field.getValueMap() == null && thumb.size() > 0) { thumbnail = (BufferedImage) thumb.get(r); } else if (field.getValueMap() != null) { try { ImageReader tempReader = new ImageReader(); tempReader.setId(field.getValueMap()); if (tempReader.getImageCount() > 0) { thumbnail = tempReader.openThumbImage(0); } tempReader.close(); } catch (Exception e) { e.printStackTrace(); } } if (thumbnail != null) { ((JLabel) c).setIcon(new ImageIcon(thumbnail)); } } int cndx = (field.getColumn() - 1) * 4 + col; int rowNdx = field.getRow() == -1 ? rowNumber[cndx - 1] : 2*field.getRow(); FormLayout layout = (FormLayout) panel.getLayout(); if (rowNdx > layout.getRowCount() - 1) { layout.appendRow(new RowSpec("pref:grow")); layout.appendRow(new RowSpec("pref")); } panel.add(new JLabel(field.getName()), CC.xy(cndx, rowNdx)); panel.add(c, CC.xy(cndx + 1, rowNdx)); if (field.getRow() == -1) { rowNumber[cndx - 1]++; rowNumber[cndx]++; } if (rowNdx > rowNumber[1]) { for (int i=0; i<col - 1; i++) { rowNumber[i] = rowNdx + 2; } } } // -- Main method -- public static void main(String[] args) { String template = null, data = null; for (int i=0; i<args.length; i++) { if (args[i].equals("-template")) { if (args.length > i + 1) { template = args[++i]; } else System.err.println("Please specify a template file"); } else data = args[i]; } new Notes(template, data); } }
package utility; import com.rgi.common.BoundingBox; import com.rgi.common.Dimensions; import com.rgi.common.Range; import com.rgi.common.coordinate.Coordinate; import com.rgi.common.coordinate.CoordinateReferenceSystem; import com.rgi.common.coordinate.CrsCoordinate; import com.rgi.common.coordinate.referencesystem.profile.CrsProfile; import com.rgi.common.coordinate.referencesystem.profile.CrsProfileFactory; import com.rgi.common.tile.TileOrigin; import com.rgi.common.tile.scheme.TileMatrixDimensions; import com.rgi.common.tile.scheme.TileScheme; import com.rgi.common.tile.scheme.ZoomTimesTwo; import com.rgi.g2t.TilingException; import com.rgi.store.tiles.TileStoreException; import org.gdal.gdal.Band; import org.gdal.gdal.Dataset; import org.gdal.gdal.gdal; import org.gdal.gdalconst.gdalconstConstants; import org.gdal.osr.SpatialReference; import org.gdal.osr.osr; import java.awt.Transparency; import java.awt.color.ColorSpace; import java.awt.image.BandedSampleModel; import java.awt.image.BufferedImage; import java.awt.image.ComponentColorModel; import java.awt.image.DataBuffer; import java.awt.image.DataBufferByte; import java.awt.image.DataBufferInt; import java.awt.image.DataBufferShort; import java.awt.image.Raster; import java.awt.image.SampleModel; import java.awt.image.WritableRaster; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.zip.DataFormatException; /** * Common functionality of the GDAL library made into helper functions * * @author Luke D. Lambert * @author Steven D. Lander */ public final class GdalUtility { static { // GDAL_DATA needs to be a valid path if(System.getenv("GDAL_DATA") == null) { throw new RuntimeException("Tiling will not work without GDAL_DATA environment variable."); } // Get the system path //String paths = System.getenv("PATH"); // TODO // Parse the path entries // Check each path entry for the required dll's/so's // Throw an error if any of the required ones are missing osr.UseExceptions(); gdal.AllRegister(); // Register GDAL extensions } private GdalUtility() { // Empty constructor for private class } /** * Opens an image file, and returns a {@link Dataset} * * @param rawImage A raster image {@link File} * @return A {@link Dataset} warped to the input coordinate reference system */ public static Dataset open(final File rawImage) { return GdalUtility.open(rawImage, null); } /** * Opens an image file, and returns a {@link Dataset} * * @param rawImage A raster image {@link File} * @param coordinateReferenceSystem The {@link CoordinateReferenceSystem} the tiles should be * output in * @return A {@link Dataset} warped to the input coordinate reference system */ public static Dataset open(final File rawImage, final CoordinateReferenceSystem coordinateReferenceSystem) { final Dataset dataset = gdal.Open(rawImage.getAbsolutePath()); // Opening is read-only by default if(dataset == null) { throw new RuntimeException(new GdalError().getMessage()); } if(coordinateReferenceSystem == null) { return dataset; } try { final Dataset openDataset = GdalUtility.doesDataSetMatchCRS(dataset, coordinateReferenceSystem) ? GdalUtility.warpDatasetToSrs(dataset, GdalUtility.getSpatialReference(dataset), GdalUtility.getSpatialReference( coordinateReferenceSystem)) : GdalUtility.reprojectDatasetToSrs(dataset, GdalUtility.getSpatialReference(dataset), GdalUtility.getSpatialReference( coordinateReferenceSystem)); if(openDataset == null) { throw new RuntimeException(new GdalError().getMessage()); } return openDataset; } catch(IOException | TilingException exception) { throw new RuntimeException(exception); } finally { dataset.delete(); } } public static boolean doesDataSetMatchCRS(final Dataset d1, final CoordinateReferenceSystem crs) { if(!GdalUtility.getSpatialReference(d1).equals(GdalUtility.getSpatialReference(crs))) { final SpatialReference fromSrs = GdalUtility.getSpatialReference(d1); final SpatialReference toSrs = GdalUtility.getSpatialReference(crs); final String fromAuthority0 = fromSrs.GetAttrValue("AUTHORITY", 0); final String toAuthority0 = toSrs.GetAttrValue("AUTHORITY", 0); final String fromAuthority1 = fromSrs.GetAttrValue("AUTHORITY", 1); final String toAuthority1 = toSrs.GetAttrValue("AUTHORITY", 1); if(fromAuthority0 == null || fromAuthority1 == null) { return false; } return fromAuthority0.equals(toAuthority0) && fromAuthority1.equals(toAuthority1); } return true; } public static BufferedImage convert(final Dataset dataset) { if(dataset == null) { throw new IllegalArgumentException("Dataset may not be null"); } final int bandCount = dataset.getRasterCount(); if(bandCount <= 0) { throw new RuntimeException("Raster contained no bands"); } final int rasterWidth = dataset.getRasterXSize(); final int rasterHeight = dataset.getRasterYSize(); final int pixelCount = rasterWidth * rasterHeight; final Band band = dataset.GetRasterBand(1); // Bands are 1-base indexed if(band == null) { throw new RuntimeException("GDAL returned a null raster band"); } final int bandDataType = band.getDataType(); if(bandCount == 1) { if(band.GetRasterColorInterpretation() == gdalconstConstants.GCI_PaletteIndex && band.GetRasterColorTable() != null) { final ByteBuffer byteBuffer = band.ReadRaster_Direct(0, 0, band.getXSize(), band.getYSize(), band.getDataType()); final DataBuffer dataBuffer = getDataBuffer(band.getDataType(), bandCount, pixelCount, new ByteBuffer[]{byteBuffer}); final int dataBufferType = getDataBufferType(bandDataType); final SampleModel sampleModel = new BandedSampleModel(dataBufferType, rasterWidth, rasterHeight, bandCount); final WritableRaster raster = Raster.createWritableRaster(sampleModel, dataBuffer, null); //bufferedImageDataType = BufferedImage.TYPE_BYTE_INDEXED; // This assignment had no effect return new BufferedImage(band.GetRasterColorTable() .getIndexColorModel(gdal.GetDataTypeSize(bandDataType)), raster, false, null); } } final ByteBuffer[] bands = IntStream.range(0, bandCount) .mapToObj(bandIndex -> { final Band currentBand = dataset.GetRasterBand(bandIndex + 1); return currentBand.ReadRaster_Direct(0, 0, currentBand.getXSize(), currentBand.getYSize(), currentBand.getDataType()); }) .toArray(ByteBuffer[]::new); final DataBuffer dataBuffer = getDataBuffer(bandDataType, bandCount, pixelCount, bands); final int dataBufferType = getDataBufferType(bandDataType); final SampleModel sampleModel = new BandedSampleModel(dataBufferType, rasterWidth, rasterHeight, bandCount); final WritableRaster raster = Raster.createWritableRaster(sampleModel, dataBuffer, null); if(bandCount > 2) { return new BufferedImage(new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), bandCount == 4, false, bandCount == 4 ? Transparency.TRANSLUCENT : Transparency.OPAQUE, dataBufferType), raster, true, null); } final BufferedImage bufferedImage = new BufferedImage(rasterWidth, rasterHeight, getBufferedImageDataType(bandDataType)); bufferedImage.setData(raster); return bufferedImage; } private static DataBuffer getDataBuffer(final int bandDataType, final int bandCount, final int pixelCount, final ByteBuffer[] bands) { if(bandDataType == gdalconstConstants.GDT_Byte) { final byte[][] bytes = new byte[bandCount][]; for(int i = 0; i < bandCount; i++) { bytes[i] = new byte[pixelCount]; bands[i].get(bytes[i]); } return new DataBufferByte(bytes, pixelCount); } else if(bandDataType == gdalconstConstants.GDT_Int16) { final short[][] shorts = new short[bandCount][]; for(int i = 0; i < bandCount; i++) { shorts[i] = new short[pixelCount]; bands[i].asShortBuffer().get(shorts[i]); } return new DataBufferShort(shorts, pixelCount); } else if(bandDataType == gdalconstConstants.GDT_Int32) { final int[][] ints = new int[bandCount][]; for(int i = 0; i < bandCount; i++) { ints[i] = new int[pixelCount]; bands[i].asIntBuffer().get(ints[i]); } return new DataBufferInt(ints, pixelCount); } else { throw new IllegalArgumentException("Unsupported band data type"); } } private static int getDataBufferType(final int bandDataType) { if(bandDataType == gdalconstConstants.GDT_Byte) { return DataBuffer.TYPE_BYTE; } else if(bandDataType == gdalconstConstants.GDT_Int16) { return DataBuffer.TYPE_USHORT; } else if(bandDataType == gdalconstConstants.GDT_Int32) { return DataBuffer.TYPE_INT; } else { throw new IllegalArgumentException("Unsupported band data type"); } } private static int getBufferedImageDataType(final int bandDataType) { if(bandDataType == gdalconstConstants.GDT_Byte) { return BufferedImage.TYPE_BYTE_GRAY; } else if(bandDataType == gdalconstConstants.GDT_Int16) { return BufferedImage.TYPE_USHORT_GRAY; } else if(bandDataType == gdalconstConstants.GDT_Int32) { return BufferedImage.TYPE_CUSTOM; } else { throw new IllegalArgumentException("Unsupported band data type"); } } /** * Gets the GDAL {@link SpatialReference} from the input {@link Dataset} * * @param dataset A GDAL {@link Dataset} * @return Returns the GDAL {@link SpatialReference} of the dataset */ public static SpatialReference getSpatialReference(final Dataset dataset) { if(dataset == null) { throw new IllegalArgumentException("Dataset may not be null."); } String wkt = dataset.GetProjection(); // Get the well-known-text of this dataset if(wkt.isEmpty() && dataset.GetGCPCount() != 0) // If the WKT is empty and there are GCPs... { wkt = dataset.GetGCPProjection(); } final SpatialReference srs = new SpatialReference(); srs.ImportFromWkt( wkt); // Returns 0 on success. Otherwise throws a RuntimeException() (or an error code if DontUseExceptions() has been called). return srs; } /** * Get the {@link SpatialReference} from an image file * * @param file Image file * @return The {@link SpatialReference} of the image file */ public static SpatialReference getSpatialReference(final File file) { if(file == null || !file.canRead()) { throw new IllegalArgumentException("File may not be null, and must be readable"); } final Dataset dataset = GdalUtility.open(file); try { return GdalUtility.getSpatialReference(dataset); } finally { dataset.delete(); } } /** * Given a {@link CoordinateReferenceSystem}, return a {@link SpatialReference} * * @param crs An input {@link CoordinateReferenceSystem} * @return A {@link SpatialReference} built from the input CRS WKT */ public static SpatialReference getSpatialReference(final CoordinateReferenceSystem crs) { if(crs == null) { throw new IllegalArgumentException("Coordinate reference system cannot be null."); } final SpatialReference srs = new SpatialReference(); srs.ImportFromWkt(CrsProfileFactory.create(crs).getWellKnownText()); return srs; } /** * Provide a {@link SpatialReference} given an input {@link CrsProfile} * * @param crsProfile A {@link CrsProfile} from which a {@link SpatialReference} should be built * @return A {@link SpatialReference} built from the input CrsProfile */ public static SpatialReference getSpatialReference(final CrsProfile crsProfile) { if(crsProfile == null) { throw new IllegalArgumentException("Crs Profile cannot be null."); } return GdalUtility.getSpatialReference(crsProfile.getCoordinateReferenceSystem()); } /** * Determine if an input dataset has a georeference * * @param dataset An input {@link Dataset} * @return A boolean where true means the dataset has a georeference and false otherwise */ public static boolean hasGeoReference(final Dataset dataset) { if(dataset == null) { throw new IllegalArgumentException("Input dataset cannot be null."); } final double[] identityTransform = {0.0, 1.0, 0.0, 0.0, 0.0, 1.0}; // Compare the dataset's transform to the identity transform and ensure there are no GCPs return !Arrays.equals(dataset.GetGeoTransform(), identityTransform) || dataset.GetGCPCount() != 0; } /** * Get the bounding box for an input {@link Dataset} * * @param dataset An input {@link Dataset} * @return A {@link BoundingBox} built from the bounds of the input {@link Dataset} * @throws DataFormatException When the input dataset contains rotation or skew. Fix the * input raster with the {@code gdalwarp} utility * manually. */ public static BoundingBox getBounds(final Dataset dataset) throws DataFormatException { if(dataset == null) { throw new IllegalArgumentException("Input dataset cannot be null."); } final double[] outputGeotransform = dataset.GetGeoTransform(); if(outputGeotransform[2] != 0 || outputGeotransform[4] != 0) { throw new DataFormatException("Raster's georeference contains a rotation or skew, which is not supported. Please use gdalwarp first."); } return new BoundingBox(outputGeotransform[0], outputGeotransform[3] + dataset.GetRasterYSize() * outputGeotransform[5], outputGeotransform[0] + dataset.GetRasterXSize() * outputGeotransform[1], outputGeotransform[3]); } /** * Build a {@link CoordinateReferenceSystem} from an input {@link SpatialReference} * * @param srs An input {@link SpatialReference} from which a {@link CoordinateReferenceSystem} will be built * @return A {@link CoordinateReferenceSystem} built from the input {@link SpatialReference} using the * authority name and code. */ public static CoordinateReferenceSystem getCoordinateReferenceSystem(final SpatialReference srs) { if(srs == null) { throw new IllegalArgumentException("Input spatial reference system cannot be null."); } // Passing null to GetAuthorityName and Code will query the root node of the WKT, not // sure if this is what we want final String authority = srs.GetAuthorityName(null); final String identifier = srs.GetAuthorityCode(null); // final String authority = srs.GetAttrValue(attributePath, 0); // final String identifier = srs.GetAttrValue(attributePath, 1); if(authority == null || authority.isEmpty() || identifier == null || identifier.isEmpty()) { return null; } return new CoordinateReferenceSystem(getName(srs), authority, Integer.valueOf(identifier)); } public static String getName(final SpatialReference spatialReference) { if(spatialReference == null) { throw new IllegalArgumentException("Input spatial reference cannot be null."); } return Arrays.asList("PROJCS", "GEOGCS", "GEOCCS") .stream() .map(srsType -> spatialReference.GetAttrValue(srsType, 0)) .filter(Objects::nonNull) .findFirst() .orElse(null); } /** * Build a {@link CrsProfile} from an input {@link Dataset} * * @param dataset An input {@link Dataset} * @return A {@link CrsProfile} built from the input {@link Dataset} */ public static CrsProfile getCrsProfile(final Dataset dataset) { if(dataset == null) { throw new IllegalArgumentException("Input dataset cannot be null."); } final SpatialReference srs = GdalUtility.getSpatialReference(dataset); final CoordinateReferenceSystem crs = GdalUtility.getCoordinateReferenceSystem(srs); return CrsProfileFactory.create(crs); } /** * Calculate all the tile ranges for the data in the input {@link * BoundingBox} for the given zoom levels. * * @param tileScheme A {@link TileScheme} describing tile matrices for a set of * zoom levels * @param datasetBounds A {@link BoundingBox} describing the data area * @param tileMatrixBounds A {@link BoundingBox} describing the area of the tile * matrix. * @param crsProfile A {@link CrsProfile} for the input area * @param tileOrigin A {@link TileOrigin} that represents which corner tiling * begins from * @return A {@link Map} of zoom levels to tile coordinate info for the * top left and bottom right corners of the matrix */ public static Map<Integer, Range<Coordinate<Integer>>> calculateTileRanges(final TileScheme tileScheme, final BoundingBox datasetBounds, final BoundingBox tileMatrixBounds, final CrsProfile crsProfile, final TileOrigin tileOrigin) { if(datasetBounds == null) { throw new IllegalArgumentException("Input bounds cannot be null."); } if(crsProfile == null) { throw new IllegalArgumentException("Input crs profile cannot be null."); } if(tileScheme == null) { throw new IllegalArgumentException("Input tile scheme cannot be null."); } if(tileOrigin == null) { throw new IllegalArgumentException("Input tile origin cannot be null."); } // Get the CRS coordinates of the bounds final CrsCoordinate topLeft = new CrsCoordinate(datasetBounds.getTopLeft(), crsProfile.getCoordinateReferenceSystem()); final CrsCoordinate bottomRight = new CrsCoordinate(datasetBounds.getBottomRight(), crsProfile.getCoordinateReferenceSystem()); return tileScheme.getZoomLevels() .stream() .collect(Collectors.toMap(zoom -> zoom, zoom -> { final TileMatrixDimensions tileMatrixDimensions = tileScheme.dimensions(zoom); final Coordinate<Integer> topLeftTile = crsProfile.crsToTileCoordinate(topLeft, tileMatrixBounds, tileMatrixDimensions, tileOrigin); final Coordinate<Integer> bottomRightTile = crsProfile.crsToTileCoordinate(bottomRight, tileMatrixBounds, tileMatrixDimensions, tileOrigin); return new Range<>(topLeftTile, bottomRightTile); })); } /** * Returns the highest numeric Zoom level in which the entire dataset can be viewed as a single tile. * * @param tileRanges The calculated list of tile numbers and zooms * @return The zoom level for this dataset that produces only one tile. * Defaults to 0 if an error occurs. */ public static int getMinimalZoom(final Map<Integer, Range<Coordinate<Integer>>> tileRanges) { if(tileRanges == null || tileRanges.isEmpty()) { throw new IllegalArgumentException("Tile Range Map cannot be null or Empty"); } final Range<Coordinate<Integer>> levelZero = tileRanges.get(0); if(!levelZero.getMinimum().equals(levelZero.getMaximum())) { throw new IllegalArgumentException("Level Zero of the tileRange must be 1 tile"); } return tileRanges.entrySet() .stream() .filter(Objects::nonNull) .filter(entry -> { //if its 1 tile return entry.getValue().getMinimum().equals(entry.getValue().getMaximum()); }) .reduce((previous, current) -> { //get the last entry. return current; }).get().getKey(); } /** * Get the highest-integer zoom level for the input {@link Dataset} * * @param dataset An input {@link Dataset} * @param tileRanges The calculated list of tile numbers and zooms * @param tileOrigin The {@link TileOrigin} of the tile grid * @param tileScheme The {@link TileScheme} of the tile grid * @param tileSize A {@link Dimensions} Integer object that describes what the tiles should look like * @return The zoom level for this dataset that is closest to the actual * resolution * @throws TileStoreException Thrown when a {@link GdalUtility#getCrsProfile(Dataset)} throws */ public static int getMaximalZoom(final Dataset dataset, final Map<Integer, Range<Coordinate<Integer>>> tileRanges, final TileOrigin tileOrigin, final TileScheme tileScheme, final Dimensions<Integer> tileSize) throws TileStoreException { if(dataset == null) { throw new IllegalArgumentException("Input dataset cannot be null."); } if(tileRanges == null || tileRanges.isEmpty()) { throw new IllegalArgumentException("Tile range list cannot be null or empty."); } if(tileOrigin == null) { throw new IllegalArgumentException("Tile origin cannot be null."); } if(tileScheme == null) { throw new IllegalArgumentException("Tile scheme cannot be null."); } if(tileSize == null) { throw new IllegalArgumentException("Tile dimensions cannot be null."); } final double zoomPixelSize = dataset.GetGeoTransform()[1]; try { final CrsProfile crsProfile = GdalUtility.getCrsProfile(dataset); return GdalUtility.zoomLevelForPixelSize(zoomPixelSize, tileRanges, dataset, crsProfile, tileScheme, tileOrigin, tileSize); } catch(final TileStoreException e) { throw new TileStoreException("Could not determine maximum zoom level."); } } /** * Return a {@link Set} of all the zoom levels in the input {@link Dataset} * * @param dataset An input {@link Dataset} * @param tileOrigin The {@link TileOrigin} of the tile grid * @param tileSize A {@link Dimensions} Integer object that describes what the * tiles should look like * @return A set of integers for all the zoom levels in the input dataset * @throws TileStoreException Thrown if the input dataset bounds could not * be retrieved */ public static Set<Integer> getZoomLevels(final Dataset dataset, final TileOrigin tileOrigin, final Dimensions<Integer> tileSize) throws TileStoreException { if(dataset == null) { throw new IllegalArgumentException("Input dataset cannot be null."); } if(tileOrigin == null) { throw new IllegalArgumentException("Tile origin cannot be null."); } if(tileSize == null) { throw new IllegalArgumentException("Tile dimensions cannot be null."); } // World extent tile scheme final ZoomTimesTwo tileScheme = new ZoomTimesTwo(0, 31, 1, 1); try { final BoundingBox datasetBounds = GdalUtility.getBounds(dataset); final CrsProfile crsProfile = GdalUtility.getCrsProfile(dataset); final Map<Integer, Range<Coordinate<Integer>>> tileRanges = GdalUtility.calculateTileRanges(tileScheme, datasetBounds, crsProfile.getBounds(), crsProfile, tileOrigin); final int minZoom = GdalUtility.getMinimalZoom(tileRanges); final int maxZoom = GdalUtility.getMaximalZoom(dataset, tileRanges, tileOrigin, tileScheme, tileSize); return IntStream.rangeClosed(minZoom, maxZoom) .boxed() .collect(Collectors.toSet()); } catch(final DataFormatException dfe) { throw new TileStoreException(dfe); } } /** * Return the appropriate zoom level based on the input pixel resolution * * @param zoomPixelSize The pixel resolution of the zoom level * @param tileRanges The calculated list of tile numbers and zooms * @param dataset An input {@link Dataset} * @param crsProfile A {@link CrsProfile} for the input area * @param tileScheme The {@link TileScheme} of the tile grid * @param tileOrigin The {@link TileOrigin} of the tile grid * @param tileSize A {@link Dimensions} Integer object that describes what the * tiles should look like * @return The integer zoom matched to the pixel resolution * @throws TileStoreException When the bounds of the dataset could not be determined */ public static int zoomLevelForPixelSize(final double zoomPixelSize, final Map<Integer, Range<Coordinate<Integer>>> tileRanges, final Dataset dataset, final CrsProfile crsProfile, final TileScheme tileScheme, final TileOrigin tileOrigin, final Dimensions<Integer> tileSize) throws TileStoreException { if(tileRanges == null || tileRanges.isEmpty()) { throw new IllegalArgumentException("Tile range list cannot be null."); } if(dataset == null) { throw new IllegalArgumentException("Input dataset cannot be null."); } if(crsProfile == null) { throw new IllegalArgumentException("Crs profile cannot be null."); } if(tileScheme == null) { throw new IllegalArgumentException("Tile scheme cannot be null."); } if(tileOrigin == null) { throw new IllegalArgumentException("Tile origin cannot be null."); } if(tileSize == null) { throw new IllegalArgumentException("Tile dimensions cannot be null."); } try { final BoundingBox boundingBox = GdalUtility.getBounds(dataset); final int zoomLevelForPixelSize = tileRanges.entrySet() .stream() .filter(entrySet -> { return zoomLevelForPixelSize( tileScheme.dimensions(entrySet.getKey()), zoomPixelSize, entrySet.getValue(), crsProfile, tileScheme, tileOrigin, tileSize, boundingBox); }) .map(entrySet -> entrySet.getKey()) .findFirst() .orElseThrow( () -> new NumberFormatException("Could not determine zoom level for pizel size: " + String.valueOf( zoomPixelSize))); return zoomLevelForPixelSize == 0 ? 0 : zoomLevelForPixelSize - 1; } catch(DataFormatException | NumberFormatException ex) { throw new TileStoreException(ex); } } private static boolean zoomLevelForPixelSize(final TileMatrixDimensions tileMatrixDimensions, final double zoomPixelSize, final Range<Coordinate<Integer>> tileRange, final CrsProfile crsProfile, final TileScheme tileScheme, final TileOrigin tileOrigin, final Dimensions<Integer> tileSize, final BoundingBox boundingBox) { if(tileMatrixDimensions == null) { throw new IllegalArgumentException(); } if(tileRange == null) { throw new IllegalArgumentException("Tile range cannot be null."); } if(crsProfile == null) { throw new IllegalArgumentException("Crs profile cannot be null."); } if(tileScheme == null) { throw new IllegalArgumentException("Tile scheme cannot be null."); } if(tileOrigin == null) { throw new IllegalArgumentException("Tile origin cannot be null."); } if(tileSize == null) { throw new IllegalArgumentException("Tile dimensions cannot be null."); } // Get the tile coordinates of the top-left and bottom-right tiles final Coordinate<Integer> topLeftTile = crsProfile.crsToTileCoordinate(new CrsCoordinate(boundingBox.getTopLeft(), crsProfile.getCoordinateReferenceSystem()), crsProfile.getBounds(), // Use bounds of the world here tileMatrixDimensions, tileOrigin); final Coordinate<Integer> bottomRightTile = crsProfile.crsToTileCoordinate(new CrsCoordinate(boundingBox.getBottomRight(), crsProfile.getCoordinateReferenceSystem()), crsProfile.getBounds(), //boundingBox, Use bounds of the world here tileMatrixDimensions, tileOrigin); // Convert tile coordinates to crs coordinates: this will give us correct units-of-measure-per-pixel final Coordinate<Integer> topLeftCoord = tileOrigin.transform(TileOrigin.UpperLeft, topLeftTile.getX(), topLeftTile.getY(), tileMatrixDimensions); final Coordinate<Integer> bottomRightCoord = tileOrigin.transform(TileOrigin.LowerRight, bottomRightTile.getX(), bottomRightTile.getY(), tileMatrixDimensions); final CrsCoordinate topLeftCrsFull = crsProfile.tileToCrsCoordinate(topLeftCoord.getX(), topLeftCoord.getY(), crsProfile.getBounds(), tileMatrixDimensions, TileOrigin.UpperLeft); final CrsCoordinate bottomRightCrsFull = crsProfile.tileToCrsCoordinate(bottomRightCoord.getX(), bottomRightCoord.getY(), crsProfile.getBounds(), tileMatrixDimensions, TileOrigin.LowerRight); // get how many tiles wide this zoom will be so that number can be multiplied by tile size // TODO *WARNING* 'tiles wide' is used for both width and height calculations! final int zoomTilesWide = tileRange.getMaximum().getX() - tileRange.getMinimum().getX() + 1; final double zoomResolution; if(tileSize.getWidth() >= tileSize.getHeight()) { final double width = bottomRightCrsFull.getX() - topLeftCrsFull.getX(); zoomResolution = width / (zoomTilesWide * tileSize.getWidth()); } else { final double height = topLeftCrsFull.getY() - bottomRightCrsFull.getY(); zoomResolution = height / (zoomTilesWide * tileSize.getHeight()); } return zoomPixelSize > zoomResolution; } /** * Warp an input {@link Dataset} into a different spatial reference system. Does * not correct for NODATA values. * * @param dataset An input {@link Dataset} * @param fromSrs Original spatial reference system of the {@code dataset} * @param toSrs Spatial reference system to warp the {@code dataset} to * @return A {@link Dataset} in the input {@link SpatialReference} requested */ public static Dataset warpDatasetToSrs(final Dataset dataset, final SpatialReference fromSrs, final SpatialReference toSrs) { if(dataset == null) { throw new IllegalArgumentException("Input dataset cannot be null."); } if(fromSrs == null) { throw new IllegalArgumentException("From-Srs cannot be null."); } if(toSrs == null) { throw new IllegalArgumentException("To-Srs cannot be null."); } final Dataset output = gdal.AutoCreateWarpedVRT(dataset, fromSrs.ExportToWkt(), toSrs.ExportToWkt(), gdalconstConstants.GRA_Average); if(output == null) { throw new RuntimeException(new GdalError().getMessage()); } return output; } /** * Reproject an input {@link Dataset} into a different spatial reference system. Does * not correct for NODATA values. * * @param dataset An input {@link Dataset} * @param fromSrs Original spatial reference system of the {@code dataset} * @param toSrs Spatial reference system to warp the {@code dataset} to * @return A {@link Dataset} in the input {@link SpatialReference} requested * @throws IOException * @throws TilingException */ public static Dataset reprojectDatasetToSrs(final Dataset dataset, final SpatialReference fromSrs, final SpatialReference toSrs) throws IOException, TilingException { if(dataset == null) { throw new IllegalArgumentException("Input dataset cannot be null."); } if(fromSrs == null) { throw new IllegalArgumentException("From-Srs cannot be null."); } if(toSrs == null) { throw new IllegalArgumentException("To-Srs cannot be null."); } final Path path = File.createTempFile("Reprojection", ".tiff").toPath(); final Dataset output = gdal.GetDriverByName("GTiff").Create(path.toString(), dataset.getRasterXSize(), dataset.getRasterYSize(), dataset.getRasterCount()); output.SetProjection(toSrs.ExportToWkt()); final Dataset temp = gdal.AutoCreateWarpedVRT(dataset, fromSrs.ExportToWkt(), toSrs.ExportToWkt(), gdalconstConstants.GRA_Average); if(temp == null) { throw new RuntimeException(new GdalError().getMessage()); } output.SetGeoTransform(temp.GetGeoTransform()); temp.delete(); final int result = gdal.ReprojectImage(dataset, output, fromSrs.ExportToWkt(), toSrs.ExportToWkt()); if(result != gdalconstConstants.CE_None) { //remove database on error output.delete(); Files.delete(path); if(result == gdalconstConstants.CE_Failure) { throw new IOException("Tile call outside of raster bounds."); } if(result == gdalconstConstants.CE_Fatal) { throw new TilingException("Fatal error detected from GDAL readRaster."); } } return output; } /** * Scale a Dataset down into a smaller-sized Dataset using the average algorithm. * * @param queryDataset A {@link Dataset} that needs to be scaled down to a smaller size * @param dimensions A {@link Dimensions} object containing the width and height * information for the output {@link Dataset} * @return A {@link Dataset} of the sizespecified in the width and height properties of * the input {@link Dimensions} object * @throws TilingException Thrown when any band of the input query {@link Dataset} fails * to scale correctly with {@link gdal#RegenerateOverview(Band, Band, String)} */ public static Dataset scaleQueryToTileSize(final Dataset queryDataset, final Dimensions<Integer> dimensions) throws TilingException { if(queryDataset == null) { throw new IllegalArgumentException("Query dataset cannot be null."); } if(dimensions == null) { throw new IllegalArgumentException("Tile dimensions cannot be null."); } // TODO: This just handles average resampling, it should be adjusted for other resampling types final Dataset tileDataInMemory = gdal.GetDriverByName("MEM").Create("", dimensions.getWidth(), dimensions.getHeight(), queryDataset.GetRasterCount()); try { IntStream.rangeClosed(1, queryDataset.GetRasterCount()) .forEach(index -> { final int resolution = gdal.RegenerateOverview(queryDataset.GetRasterBand(index), tileDataInMemory.GetRasterBand(index), "average"); if(resolution != 0) { throw new RuntimeException("Could not regenerate overview on band: " + String.valueOf(index)); } }); } catch(final RuntimeException ex) { throw new TilingException(ex); } return tileDataInMemory; } /** * Get the color values specified as NODATA in a Dataset. * * @param dataset An input {@link Dataset} that possibly has NODATA values * @return The NODATA values as a {@link Double} array */ public static Double[] getNoDataValues(final Dataset dataset) { if(dataset == null) { throw new IllegalArgumentException("Input dataset cannot be null."); } // Initialize a new double array of size 3 final Double[] noDataValues = new Double[4]; // Get the nodata value for each band IntStream.rangeClosed(1, dataset.GetRasterCount()) .forEach(band -> { final Double[] noDataValue = new Double[1]; dataset.GetRasterBand(band).GetNoDataValue(noDataValue); if(noDataValue.length != 0 && noDataValue[0] != null) { // Assumes only one value coming back from the band noDataValues[band - 1] = noDataValue[0]; } }); // Is array still using the initialized values? if(noDataValues[0] == null && noDataValues[1] == null && noDataValues[2] == null) { return new Double[0]; } // TODO: Is it possible to see a raster from GDAL with 2 bands? I think // only Mono and RGB options are possible if(noDataValues[0] != null) { noDataValues[1] = noDataValues[0]; noDataValues[2] = noDataValues[0]; noDataValues[3] = noDataValues[0]; } return noDataValues; } /** * Get the number of raster {@link Band}s in a Dataset. * * @param dataset An input {@link Dataset} containing a number of bands * @param alphaBand An alpha {@link Band} * @return The number of {@link Band}s in the input {@link Dataset} */ public static int getRasterBandCount(final Dataset dataset, final Band alphaBand) { if(dataset == null) { throw new IllegalArgumentException("Input dataset cannot be null."); } if(alphaBand == null) { throw new IllegalArgumentException("Alpha band cannot be null."); } // TODO: The bitwise calc functionality needs to be verified from the python functionality final boolean bitwiseAlpha = (alphaBand.GetMaskFlags() & gdalconstConstants.GMF_ALPHA) != 0; return bitwiseAlpha || dataset.GetRasterCount() == 4 || dataset.GetRasterCount() == 2 ? dataset.GetRasterCount() - 1 : dataset.GetRasterCount(); } /** * Get the index of the alpha {@link Band} of a Dataset, if any. * * @param dataset An input {@link Dataset} to search for an alpha {@link Band} * @return The index of the alpha band of the input Dataset if found * @throws TileStoreException Thrown when no alpha band could be detected. */ public static int getAlphaBandIndex(final Dataset dataset) throws TileStoreException { if(dataset == null) { throw new IllegalArgumentException("Input dataset cannot be null."); } return IntStream.rangeClosed(1, dataset.GetRasterCount()) .filter(index -> dataset.GetRasterBand(index).GetColorInterpretation() == gdalconstConstants.GCI_AlphaBand) .findFirst() .orElseThrow( () -> new TileStoreException("No Alpha band detected. Call getAlphaBandIndex after correcting nodata color.")); } /** * Correct an input raster {@link Dataset}s NODATA values to an alpha {@link Band} * * @param dataset An input {@link Dataset} * @return A dataset with an alpha band added that reflects the input Dataset's NODATA value */ public static Dataset correctNoDataSimple(final Dataset dataset) { if(dataset == null) { throw new IllegalArgumentException("Input dataset cannot be null."); } final boolean datasetHasAlphaBand = GdalUtility.hasAlpha(dataset); // If the dataset actually has an alpha band, return it if(datasetHasAlphaBand) { return dataset; } // Dataset has no alpha and is NOT a VRT if(!dataset.GetDriver().getShortName().equalsIgnoreCase("VRT")) { // Create a vrt of this dataset final Dataset vrtCopy = gdal.AutoCreateWarpedVRT(dataset); // Add an alpha band // TODO: This does not work even on VRT datasets. Find out why. vrtCopy.AddBand(gdalconstConstants.GDT_Byte); // A new band added is always the last, per docs vrtCopy.GetRasterBand(vrtCopy.GetRasterCount() + 1).SetColorInterpretation( gdalconstConstants.GCI_AlphaBand); return vrtCopy; } // Dataset has no alpha and IS a VRT dataset.AddBand(gdalconstConstants.GDT_Byte); dataset.GetRasterBand(dataset.GetRasterCount() + 1).SetColorInterpretation(gdalconstConstants.GCI_AlphaBand); return dataset; } /** * Return whether or not the input Dataset has an alpha {@link Band} * * @param dataset An input {@link Dataset} * @return True if the input {@link Dataset} has an alpha {@link Band}, * false otherwise. */ public static boolean hasAlpha(final Dataset dataset) { if(dataset == null) { throw new IllegalArgumentException("Input dataset cannot be null."); } return IntStream.rangeClosed(1, dataset.GetRasterCount()) .anyMatch(index -> dataset.GetRasterBand(index).GetColorInterpretation() == gdalconstConstants.GCI_AlphaBand); } /** * Create a set of GDAL parameters for reading tile data and writing that * data to another Dataset. * * @param geoTransform An array of doubles representing the geotransform of the input dataset * @param boundingBox The {@link BoundingBox} of the tile query * @param dimensions The tile {@link Dimensions} * @param dataset The input {@link Dataset} * @return An object with all information necessary to perform GDAL ReadRaster and WriteRaster * operations. */ public static GdalRasterParameters getGdalRasterParameters(final double[] geoTransform, final BoundingBox boundingBox, final Dimensions<Integer> dimensions, final Dataset dataset) { if(geoTransform.length == 0) { throw new IllegalArgumentException("Geotransform cannot be empty."); } if(boundingBox == null) { throw new IllegalArgumentException("Bounding box cannot be null."); } if(dimensions == null) { throw new IllegalArgumentException("Tile dimensions cannot be null."); } if(dataset == null) { throw new IllegalArgumentException("Input dataset cannot be null."); } // This is sorcery of the darkest kind. It works but it not fully understood. final int readX = (int)((boundingBox.getMinimumX() - geoTransform[0]) / geoTransform[1] + 0.001); final int readY = (int)((boundingBox.getMaximumY() - geoTransform[3]) / geoTransform[5] + 0.001); final int readXSize = (int)(boundingBox.getWidth() / geoTransform[1] + 0.5); final int readYSize = (int)(boundingBox.getHeight() / -geoTransform[5] + 0.5); return new GdalRasterParameters(readX, readY, readXSize, readYSize, dimensions, dataset); } /** * Read a subset of image data from a raster {@link Dataset}. * * @param params A {@link GdalRasterParameters} object containing data on how * the tile should be read from the raster image * @param dataset The {@link Dataset} to read the tile data from * @return A {@link Byte} array of size @params.writeXSize() * * @throws TilingException Thrown when ReadRaster reports a failure * @throws IOException when {@link Dataset#ReadRaster} fails * @params.writeYSize() * @dataset.GetRasterCount() containing * tile data for the area specified in @params */ public static byte[] readRaster(final GdalRasterParameters params, final Dataset dataset) throws TilingException, IOException { if(params == null) { throw new IllegalArgumentException("GDAL parameters cannot be null."); } if(dataset == null) { throw new IllegalArgumentException("Input dataset cannot be null."); } final int bandCount = dataset.GetRasterCount(); // correctNoDataSimple should have added an alpha band if(params.getWriteXSize() < 0 || params.getWriteYSize() < 0) { throw new IOException("Tile call is outside the raster boundaries."); } final byte[] imageData = new byte[params.getWriteXSize() * params.getWriteYSize() * bandCount]; final int result = dataset.ReadRaster(params.getReadX(), // xOffset params.getReadY(), // yOffset params.getReadXSize(), // xSize params.getReadYSize(), // ySize params.getWriteXSize(), // buffer_xSize params.getWriteYSize(), // buffer_ySize gdalconstConstants.GDT_Byte, // buffer type imageData, // array into which the data will be written, must contain at least buffer_xSize * buffer_ySize * nBandCount null); // Per documentation, will select the first nBandCount bands if(result == gdalconstConstants.CE_Failure) { throw new IOException("Tile call outside of raster bounds."); } if(result == gdalconstConstants.CE_Fatal) { throw new TilingException("Fatal error detected from GDAL readRaster."); } return imageData; } /** * Read a subset of image data from a raster {@link Dataset} directly using a {@link ByteBuffer}. * * @param params A GDAL parameters object containing data on how the tile should be read from * the raster image * @param dataset The {@link Dataset} to read the tile data from * @return A {@link Byte} array of size @params.writeXSize() * @params.writeYSize() * @dataset.GetRasterCount() * containing tile data for the area specified in @params * @throws TilingException Thrown when ReadRaster_Direct reports a failure */ public static ByteBuffer readRasterDirect(final GdalRasterParameters params, final Dataset dataset) throws TilingException { if(params == null) { throw new IllegalArgumentException("GDAL parameters cannot be null."); } if(dataset == null) { throw new IllegalArgumentException("Input dataset cannot be null."); } final int bandCount = dataset.GetRasterCount(); // correctNoDataSimple should have added an alpha band final ByteBuffer imageData = ByteBuffer.allocateDirect(params.getWriteXSize() * params.getWriteYSize() * bandCount); final int result = dataset.ReadRaster_Direct(params.getReadX(), params.getReadY(), params.getReadXSize(), params.getReadYSize(), params.getWriteXSize(), params.getWriteYSize(), gdalconstConstants.GDT_Byte, imageData, null); // Per documentation, will select the first nBandCount bands if(result != gdalconstConstants.CE_None) { throw new TilingException("Failure reported by ReadRaster call in GdalUtility."); } return imageData; } /** * Write tile data to an output {@link Dataset}. * * @param params The {@link GdalRasterParameters} containing data on how the tile should be * written to the returned {@link Dataset} * @param imageData A {@link Byte} array of size @params.writeXSize() * @params.writeYSize() * @dataset.GetRasterCount() * containing tile data for the area specified * @param bandCount The number of bands the output {@link Dataset} should have * @return A {@link Dataset} representing a tile image * @throws TilingException Thrown when WriteRaster reports a failure */ public static Dataset writeRaster(final GdalRasterParameters params, final byte[] imageData, final int bandCount) throws TilingException { if(params == null) { throw new IllegalArgumentException("GDAL parameters cannot be null."); } if(imageData.length == 0) { throw new IllegalArgumentException("Image data must be non-zero length."); } final Dataset querySizeDatasetInMemory = gdal.GetDriverByName("MEM").Create("", params.getQueryXSize(), params.getQueryYSize(), bandCount); final int result = querySizeDatasetInMemory.WriteRaster(params.getWriteX(), params.getWriteY(), params.getWriteXSize(), params.getWriteYSize(), params.getWriteXSize(), params.getWriteYSize(), gdalconstConstants.GDT_Byte, imageData, null); // Per documentation, will select the first nBandCount bands if(result != gdalconstConstants.CE_None) { throw new TilingException("Failure reported by WriteRaster call in GdalUtility."); } return querySizeDatasetInMemory; } /** * Write tile data to an output {@link Dataset} directly using a {@link ByteBuffer}. * * @param params The {@link GdalRasterParameters} containing data on how the tile should be * written to the returned {@link Dataset} * @param imageData A {@link Byte} array of size @params.writeXSize() * @params.writeYSize() * @dataset.GetRasterCount() * containing tile data for the area specified * @param bandCount The number of bands the output {@link Dataset} should have * @return A {@link Dataset} representing a tile image * @throws TilingException Thrown when WriteRaster_Direct reports a failure */ public static Dataset writeRasterDirect(final GdalRasterParameters params, final ByteBuffer imageData, final int bandCount) throws TilingException { if(params == null) { throw new IllegalArgumentException("GDAL parameters cannot be null."); } if(imageData == null) { throw new IllegalArgumentException("Image data must be non-zero length."); } final Dataset querySizeDatasetInMemory = gdal.GetDriverByName("MEM").Create("", params.getQueryXSize(), params.getQueryYSize(), bandCount); final int result = querySizeDatasetInMemory.WriteRaster_Direct(params.getWriteX(), params.getWriteY(), params.getWriteXSize(), params.getWriteYSize(), params.getWriteXSize(), params.getWriteYSize(), gdalconstConstants.GDT_Byte, imageData, null); // Per documentation, will select the first nBandCount bands if(result != gdalconstConstants.CE_None) { throw new TilingException("Failure reported by WriteRasterDirect call in GdalUtility."); } return querySizeDatasetInMemory; } /** * An object containing all data necessary for GDAL ReadRaster and WriteRaster functions. * * @author Steven D. Lander */ public static class GdalRasterParameters { private int readX; private int readY; private int readXSize; private int readYSize; private int writeX; private int writeY; private int writeXSize; private int writeYSize; private final int queryXSize; private final int queryYSize; /** * @param readX The X-axis pixel location to start reading tile data from * @param readY The Y-axis pixel location to start reading tile data from * @param readXSize The amount of pixels to read in the X-axis * @param readYSize The amount of pixels to read in the Y-axis * @param dimensions The {@link Dimensions} of the tile grid * @param dataset The raster {@link Dataset} that is being manipulated */ public GdalRasterParameters(final int readX, final int readY, final int readXSize, final int readYSize, final Dimensions<Integer> dimensions, final Dataset dataset) { if(dimensions == null) { throw new IllegalArgumentException("Dimensions of the tile system cannot be null."); } if(dataset == null) { throw new IllegalArgumentException("Input dataset must be supplied to GdalRasterParameters."); } // Points that dictate where a tile read occurs on the dataset this.readX = readX; this.readY = readY; // Size values that dictate how much data should be read from the dataset for // a tile read operation this.readXSize = readXSize; this.readYSize = readYSize; // Points on the write canvas that dictate where the read data should be written this.writeX = 0; this.writeY = 0; // Size values that indicate how large the tile query canvas should be // Hard coding the query to be larger size for later down-scaling this.queryXSize = 4 * dimensions.getWidth(); this.queryYSize = 4 * dimensions.getHeight(); // Size values that dictate how large the write canvas should be this.writeXSize = this.queryXSize; this.writeYSize = this.queryYSize; this.adjust(dataset); } /** * @return The point in the x axis where tile data should be read from */ public int getReadX() { return this.readX; } /** * @return The point in the x axis where tile data should be read from */ public int getReadY() { return this.readY; } /** * @return The raster read size for the x axis */ public int getReadXSize() { return this.readXSize; } /** * @return The raster read size for the y axis */ public int getReadYSize() { return this.readYSize; } /** * @return The point in the x axis where tile data should be written */ public int getWriteX() { return this.writeX; } /** * @return The point in the y axis where tile data should be written */ public int getWriteY() { return this.writeY; } /** * @return The raster canvas write size for the x axis */ public int getWriteXSize() { return this.writeXSize; } /** * @return The raster canvas write size for the y axis */ public int getWriteYSize() { return this.writeYSize; } /** * @return The size of the raster data query in the x axis */ public int getQueryXSize() { return this.queryXSize; } /** * @return The size of the raster data query in the y axis */ public int getQueryYSize() { return this.queryYSize; } /** * Adjust final read, write, and size parameters for a GDAL calls to ReadRaster and * Write Raster. * * @param dataset The input dataset with which all values will be adjusted from */ private void adjust(final Dataset dataset) { if(this.readX < 0) { final int readXShift = Math.abs(this.readX); this.writeX = (int)(this.writeXSize * ((float)readXShift / this.readXSize)); this.writeXSize -= this.writeX; this.readXSize -= (int)(this.readXSize * ((float)readXShift) / this.readXSize); this.readX = 0; } if(this.readX + this.readXSize > dataset.GetRasterXSize()) { this.writeXSize = (int)(this.writeXSize * ((float)(dataset.GetRasterXSize() - this.readX) / this.readXSize)); this.readXSize = dataset.GetRasterXSize() - this.readX; } if(this.readY < 0) { final int readYShift = Math.abs(this.readY); this.writeY = (int)(this.writeYSize * ((float)readYShift / this.readYSize)); this.writeYSize -= this.writeY; this.readYSize -= (int)(this.readYSize * ((float)readYShift / this.readYSize)); this.readY = 0; } if(this.readY + this.readYSize > dataset.GetRasterYSize()) { this.writeYSize = (int)(this.writeYSize * ((float)(dataset.GetRasterYSize() - this.readY) / this.readYSize)); this.readYSize = dataset.GetRasterYSize() - this.readY; } } } }
package net.aeten.core.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; public class JarExtractor { public static File extract ( Class <?> loadinClass, String resourceRelativePath) { return extract (loadinClass, resourceRelativePath, getTempDir (loadinClass.getName ())); } public static File extract ( Class <?> loadinClass, String resourceRelativePath, File outputDirectory) { URL url = loadinClass.getResource (resourceRelativePath); if (url == null) { throw new UnsatisfiedLinkError ("JarExtractor (" + resourceRelativePath + ") not found in resource path"); } File file = null; if (url.getProtocol ().toLowerCase ().equals ("file")) { try { file = new File (new URI (url.toString ())); } catch (URISyntaxException e) { file = new File (url.getPath ()); } if (!file.exists ()) { throw new Error ("File URL " + url + " could not be properly decoded"); } } else { InputStream is = loadinClass.getResourceAsStream (resourceRelativePath); if (is == null) { throw new Error ("Can't obtain InputStream (" + resourceRelativePath + ")"); } FileOutputStream fos = null; try { /* Suffix is required on windows, or library fails to load Let Java pick the suffix, * except on windows, to avoid problems with Web Start. */ file = new File (outputDirectory, resourceRelativePath); if (file.exists ()) { return file; } file.getParentFile ().mkdirs (); fos = new FileOutputStream (file); int count; byte[] buf = new byte[1024]; while ((count = is.read (buf, 0, buf.length)) > 0) { fos.write (buf, 0, count); } } catch (IOException exception) { throw new Error ("Failed to extract file for", exception); } finally { try { is.close (); } catch (IOException exception) {} if (fos != null) { try { fos.close (); } catch (IOException exception) {} } } } return file; } static File getTempDir (String fileName) { File tmpdir = new File (System.getProperty ("java.io.tmpdir")); File filetmp = new File (tmpdir, fileName + "-" + System.getProperty ("user.name")); filetmp.mkdirs (); return filetmp.exists ()? filetmp: tmpdir; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package moppydesk; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.sound.midi.*; import javax.sound.midi.MidiDevice.Info; /** * * @author Sam */ public class MoppyMIDIBridge implements Receiver{ MidiDevice device; Receiver deviceReceiver; public MoppyMIDIBridge(String midiDeviceName) throws MidiUnavailableException{ MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo(); for (Info i : infos){ try { if (i.getName().equalsIgnoreCase(midiDeviceName)){ this.device = MidiSystem.getMidiDevice(i); } } catch (MidiUnavailableException ex) { Logger.getLogger(MoppyMIDIBridge.class.getName()).log(Level.SEVERE, null, ex); } } device.open(); deviceReceiver = device.getReceiver(); } public static HashMap<String,Info> getMIDIOutInfos(){ MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo(); HashMap<String,Info> outInfos = new HashMap<String,Info>(); for (Info i : infos){ try { MidiDevice dev = MidiSystem.getMidiDevice(i); if (dev.getMaxReceivers() != 0){ outInfos.put(i.getName(), i); } } catch (MidiUnavailableException ex) { Logger.getLogger(MoppyMIDIBridge.class.getName()).log(Level.SEVERE, null, ex); } } return outInfos; } public void send(MidiMessage message, long timeStamp) { deviceReceiver.send(message, timeStamp); } public void close() { deviceReceiver.close(); device.close(); } }
package soot.jimple.infoflow; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Value; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; import soot.jimple.infoflow.util.ConcurrentHashSet; import soot.jimple.infoflow.util.MyConcurrentHashMap; import soot.tagkit.LineNumberTag; /** * Class for collecting information flow results * * @author Steven Arzt */ public class InfoflowResults { private final Logger logger = LoggerFactory.getLogger(getClass()); /** * Class for modeling information flowing out of a specific source * @author Steven Arzt */ public class SourceInfo { private final Value source; private final Stmt context; private final Object userData; private final List<Stmt> path; public SourceInfo(Value source, Stmt context) { assert source != null; this.source = source; this.context = context; this.userData = null; this.path = null; } public SourceInfo(Value source, Stmt context, Object userData, List<Stmt> path) { assert source != null; this.source = source; this.context = context; this.userData = userData; this.path = path; } public Value getSource() { return this.source; } public Stmt getContext() { return this.context; } public Object getUserData() { return this.userData; } public List<Stmt> getPath() { return this.path; } @Override public String toString(){ StringBuilder sb = new StringBuilder(context.toString()); if (context.hasTag("LineNumberTag")) sb.append(" on line ").append(((LineNumberTag) context.getTag("LineNumberTag")).getLineNumber()); return sb.toString(); } @Override public int hashCode() { return (path != null && !Infoflow.getPathAgnosticResults() ? 31 * this.path.hashCode() : 0) + 31 * this.source.hashCode() + 7 * (this.context == null ? 0 : this.context.hashCode()); } @Override public boolean equals(Object o) { if (super.equals(o)) return true; if (o == null || !(o instanceof SourceInfo)) return false; SourceInfo si = (SourceInfo) o; if (!Infoflow.getPathAgnosticResults()) { if (path == null) { if (si.path != null) return false; } if (!path.equals(si.path)) return false; } if (this.context == null) { if (si.context != null) return false; } else if (!this.context.equals(si.context)) return false; return this.source.equals(si.source); } } /** * Class for modeling information flowing into a specific source * @author Steven Arzt */ public class SinkInfo { private final Value sink; private final Stmt context; public SinkInfo(Value sink, Stmt context) { assert sink != null; this.sink = sink; this.context = context; } public Value getSink() { return this.sink; } public Stmt getContext() { return this.context; } @Override public String toString() { StringBuilder sb = new StringBuilder(context.toString()); if (context.hasTag("LineNumberTag")) sb.append(" on line ").append(((LineNumberTag)context.getTag("LineNumberTag")).getLineNumber()); return sb.toString(); } @Override public int hashCode() { return 31 * this.sink.hashCode() + 7 * (this.context == null ? 0 : this.context.hashCode()); } @Override public boolean equals(Object o) { if (super.equals(o)) return true; if (o == null || !(o instanceof SinkInfo)) return false; SinkInfo si = (SinkInfo) o; if (this.context == null) { if (si.context != null) return false; } else if (!this.context.equals(si.context)) return false; return this.sink.equals(si.sink); } } private final MyConcurrentHashMap<SinkInfo, Set<SourceInfo>> results = new MyConcurrentHashMap<SinkInfo, Set<SourceInfo>>(); public InfoflowResults() { } /** * Gets the number of entries in this result object * @return The number of entries in this result object */ public int size() { return this.results.size(); } /** * Gets whether this result object is empty, i.e. contains no information * flows * @return True if this result object is empty, otherwise false. */ public boolean isEmpty() { return this.results.isEmpty(); } /** * Checks whether this result object contains a sink that exactly matches the * given value. * @param sink The sink to check for * @return True if this result contains the given value as a sink, otherwise * false. */ public boolean containsSink(Value sink) { for (SinkInfo si : this.results.keySet()) if (si.getSink().equals(sink)) return true; return false; } /** * Checks whether this result object contains a sink with the given method * signature * @param sinkSignature The method signature to check for * @return True if there is a sink with the given method signature in this * result object, otherwise false. */ public boolean containsSinkMethod(String sinkSignature) { return !findSinkByMethodSignature(sinkSignature).isEmpty(); } public void addResult(Value sink, Stmt sinkStmt, Value source, Stmt sourceStmt) { this.addResult(new SinkInfo(sink, sinkStmt), new SourceInfo(source, sourceStmt)); } public void addResult(Value sink, Stmt sinkStmt, Value source, Stmt sourceStmt, Object userData, List<Stmt> propagationPath) { this.addResult(new SinkInfo(sink, sinkStmt), new SourceInfo(source, sourceStmt, userData, propagationPath)); } public void addResult(Value sink, Stmt sinkContext, Value source, Stmt sourceStmt, Object userData, List<Stmt> propagationPath, Stmt stmt) { List<Stmt> newPropPath = new LinkedList<Stmt>(propagationPath); newPropPath.add(stmt); this.addResult(new SinkInfo(sink, sinkContext), new SourceInfo(source, sourceStmt, userData, newPropPath)); } public void addResult(SinkInfo sink, SourceInfo source) { assert sink != null; assert source != null; Set<SourceInfo> sourceInfo = this.results.putIfAbsentElseGet (sink, new ConcurrentHashSet<SourceInfo>()); sourceInfo.add(source); } /** * Gets all results in this object as a hash map. * @return All results in this object as a hash map. */ public Map<SinkInfo, Set<SourceInfo>> getResults() { return this.results; } /** * Checks whether there is a path between the given source and sink. * @param sink The sink to which there may be a path * @param source The source from which there may be a path * @return True if there is a path between the given source and sink, false * otherwise */ public boolean isPathBetween(Value sink, Value source) { Set<SourceInfo> sources = null; for(SinkInfo sI : this.results.keySet()){ if(sI.getSink().equals(sink)){ sources = this.results.get(sI); break; } } if (sources == null) return false; for (SourceInfo src : sources) if (src.source.equals(source)) return true; return false; } /** * Checks whether there is a path between the given source and sink. * @param sink The sink to which there may be a path * @param source The source from which there may be a path * @return True if there is a path between the given source and sink, false * otherwise */ public boolean isPathBetween(String sink, String source) { for (SinkInfo si : this.results.keySet()) if (si.getSink().toString().equals(sink)) { Set<SourceInfo> sources = this.results.get(si); for (SourceInfo src : sources) if (src.source.toString().equals(source)) return true; } return false; } /** * Checks whether there is an information flow between the two * given methods (specified by their respective Soot signatures). * @param sinkSignature The sink to which there may be a path * @param sourceSignature The source from which there may be a path * @return True if there is a path between the given source and sink, false * otherwise */ public boolean isPathBetweenMethods(String sinkSignature, String sourceSignature) { List<SinkInfo> sinkVals = findSinkByMethodSignature(sinkSignature); for (SinkInfo si : sinkVals) { Set<SourceInfo> sources = this.results.get(si); if (sources == null) return false; for (SourceInfo src : sources) if (src.source instanceof InvokeExpr) { InvokeExpr expr = (InvokeExpr) src.source; if (expr.getMethod().getSignature().equals(sourceSignature)) return true; } } return false; } /** * Finds the entry for a sink method with the given signature * @param sinkSignature The sink's method signature to look for * @return The key of the entry with the given method signature if such an * entry has been found, otherwise null. */ private List<SinkInfo> findSinkByMethodSignature(String sinkSignature) { List<SinkInfo> sinkVals = new ArrayList<SinkInfo>(); for (SinkInfo si : this.results.keySet()) if (si.getSink() instanceof InvokeExpr) { InvokeExpr expr = (InvokeExpr) si.getSink(); if (expr.getMethod().getSignature().equals(sinkSignature)) sinkVals.add(si); } return sinkVals; } /** * Prints all results stored in this object to the standard output */ public void printResults() { for (SinkInfo sink : this.results.keySet()) { logger.info("Found a flow to sink {}, from the following sources:", sink); for (SourceInfo source : this.results.get(sink)) { logger.info("\t- {}", source.getSource()); if (source.getPath() != null && !source.getPath().isEmpty()) logger.info("\t\ton Path {}", source.getPath()); } } } /** * Prints all results stored in this object to the given writer * @param wr The writer to which to print the results * @throws IOException Thrown when data writing fails */ public void printResults(Writer wr) throws IOException { for (SinkInfo sink : this.results.keySet()) { wr.write("Found a flow to sink " + sink + ", from the following sources:\n"); for (SourceInfo source : this.results.get(sink)) { wr.write("\t- " + source.getSource() + "\n"); if (source.getPath() != null && !source.getPath().isEmpty()) wr.write("\t\ton Path " + source.getPath() + "\n"); } } } /** * Removes all results from the data structure */ public void clear() { this.results.clear(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (SinkInfo sink : this.results.keySet()) for (SourceInfo source : this.results.get(sink)) { sb.append(source); sb.append(" -> "); sb.append(sink); } return sb.toString(); } }
package us.ihmc.realtime; import org.junit.runner.*; import org.junit.runners.*; //import us.ihmc.utilities.code.unitTesting.JUnitTestSuiteGenerator; @RunWith(Suite.class) @Suite.SuiteClasses ({ }) public class IHMCRealtimeDockerTestSuite { public static void main(String[] args) { //JUnitTestSuiteGenerator.generateTestSuite(IHMCRealtimeDockerTestSuite.class); } }
public class LetterCount { static String[] tens = {"ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; static String[] hundreds = {"onehundred", "twohundred", "threehundred", "fourhundred", "fivehundred", "sixhundred", "sevenhundred", "eighthundred", "ninehundred"}; public static void main(String[] args) { System.out.println(countOneThroughNinetyhundredninetunine() + "onethousand".length()); } public static int countOneThroughNine() { String[] nums = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; int count = 0; for(String num : nums) { count += num.length(); } return count; } public static int countTenThroughNineteen() { String[] nums = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; int count = 0; for(String num : nums) { count += num.length(); } return count; } public static int countOneThroughNinetynine() { int count = 0; count += countOneThroughNine(); count += countTenThroughNineteen(); // 20 -> 99 for (int i = 1; i < tens.length; i++) { count += (10 * tens[i].length()) + countOneThroughNine(); } return count; } public static int countOneThroughNinetyhundredninetunine() { int count = 0; count += countOneThroughNinetynine(); // 100 => 999 for (int i = 0; i < hundreds.length; i++) { count += hundreds[i].length() + (99 * (hundreds[i].length() + "and".length())) + countOneThroughNinetynine(); } return count; } }
package src.io.view.display; import java.awt.EventQueue; import java.awt.Font; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.awt.event.WindowStateListener; import java.io.InputStream; import java.util.ArrayList; import javax.swing.JComponent; import javax.swing.text.StyledDocument; import src.Key_Commands; import src.QueueCommandInterface; import src.RunGame; class Key_Listener_GUI extends javax.swing.JFrame implements WindowListener { //These two arraylists hold the things to apply when input is received by either the map, or by the chatbox public javax.swing.JTextArea getIncomingText() { return incoming_text_jTextArea; } /** * Returns the skill button of index i. Should i not be a valid skill * button, returns null. * * @param i * @return */ public javax.swing.JButton getSkillButton(int i) { switch (i) { case 1: return occupation_skill_1_jButton; case 2: return occupation_skill_2_jButton; case 3: return occupation_skill_3_jButton; case 4: return occupation_skill_4_jButton; default: return null; } } /** * The number of skill buttons. * * @return */ public int getSkillButtonCount() { return 4; } private static final long serialVersionUID = 1L; private ArrayList<QueueCommandInterface<Character>> game_inputHandlers_ = new ArrayList<QueueCommandInterface<Character>>(); private ArrayList<QueueCommandInterface<Character>> outputbox_inputHandlers_ = new ArrayList<QueueCommandInterface<Character>>(); private ArrayList<QueueCommandInterface<String>> inputchatbox_Handlers_ = new ArrayList<QueueCommandInterface<String>>(); private ArrayList<QueueCommandInterface<Key_Commands>> direct_command_receivers_ = new ArrayList<QueueCommandInterface<Key_Commands>>(); private ArrayList<QueueCommandInterface<String>> command_area_double_clicked_ = new ArrayList<QueueCommandInterface<String>>(); /** * * @param in What to write to the equipped box */ public void takeInEquipped(String in) { equipment_jTextArea.setText(in); } /** * Adds something for the buttons to call with a direct command when * pressed. * * @param receiver */ public void addDirectCommandReceiver(QueueCommandInterface<Key_Commands> receiver) { direct_command_receivers_.add(receiver); } /** * Adds a event to be triggered when chars typed in out box. * * @param handler_ */ public void addoutputBoxReceiver(QueueCommandInterface<Character> handler_) { outputbox_inputHandlers_.add(handler_); } /** * Adds an handler for when the input box receives a string. * * @param handler_ */ public void addInputBoxReceiver(QueueCommandInterface<String> handler_) { inputchatbox_Handlers_.add(handler_); } public void addCommandBoxReceiver(QueueCommandInterface<String> handler_) { command_area_double_clicked_.add(handler_); } /** * * @param in What to write to the inventory box. */ public void takeInInventory(String in) { inventory_jTextArea.setText(in); } /** * Puts a string in the output box * * @param message The string to display in a new line */ public void addMessage(String message) { incoming_text_jTextArea.append(System.lineSeparator() + message); updateScroll(); } public void setCommands(String commands) { commands_jTextArea.setText(commands); } /** * Sends the scroll bar to the buttom, used when new text is added. */ private void updateScroll() { incoming_text_jTextArea.setCaretPosition(incoming_text_jTextArea.getText().length()); } /** * Sets the given styled doc to be displayed in the main view. * * @param doc */ public void setGameContent(StyledDocument doc) { game_jTextPane.setStyledDocument(doc); } private static Key_Listener_GUI gui_ = null;//Singleton variable. /** * Singleton constructor */ private Key_Listener_GUI() { initComponents(); setFont(); bargain_barter_jButton.setText("Talk / Bargain"); occupation_skill_1_jButton.setText("Reassign Me"); occupation_skill_1_jButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { if (EventQueue.isDispatchThread()) { System.out.println("IN KEY_LISTENER: YOU ARE EXECUTING SHIT ON THE EVENT DISPATCH THREADDD!!!!!!!!!!!!!"); } else { System.out.println("IN KEY_LISTENER: YOU ARE NOT EXECUTING SHIT ON THE EVENT DISPATCH THREADDD!!!!!!!!!!!!!"); } occupation_skill_1_jButtonMouseClicked(evt); } }); occupation_skill_2_jButton.setText("Reassign Me"); occupation_skill_2_jButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { occupation_skill_2_jButtonMouseClicked(evt); } }); occupation_skill_3_jButton.setText("Reassign Me"); occupation_skill_3_jButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { occupation_skill_3_jButtonMouseClicked(evt); } }); occupation_skill_4_jButton.setText("Reassign Me"); occupation_skill_4_jButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { occupation_skill_4_jButtonMouseClicked(evt); } }); addWindowListener(this); } @Override public void windowClosing(WindowEvent e) { // close all threads before closing. RunGame.grusomelyKillTheMapAndTheController(); } @Override public void windowClosed(WindowEvent e) { //This will only be seen on standard output. // close all threads before closing. RunGame.grusomelyKillTheMapAndTheController(); } @Override public void windowOpened(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } /** * Sets the font of the 3 main components. Uses the fontSize_ variable. */ private void setFont() { setFont(game_jTextPane); setFont(incoming_text_jTextArea); setFont(outgoing_chat_text_area_jScrollPane); setFont(incoming_text_jTextArea); setFont(equip_text_area_jScrollPane); setFont(inventory_jTextArea); } public String getHighlightedItem() { String highlighted = inventory_jTextArea.getSelectedText(); if (highlighted != null) { return highlighted; } highlighted = equipment_jTextArea.getSelectedText(); if (highlighted != null) { return highlighted; } highlighted = commands_jTextArea.getSelectedText(); return highlighted; } /** * Returns the singleton instance. * * @return The singleton Key_Listener_GUI */ public static Key_Listener_GUI getGUI() { if (gui_ == null) { gui_ = new Key_Listener_GUI(); } return gui_; } /** * Adds a class to be called via the function interface whenever a character * is typed in the main gameview. * * @param foo : The class to call */ public void addGameInputerHandler(QueueCommandInterface<Character> foo) { game_inputHandlers_.add((foo)); } /** * Adds a class to be called via the function interface whenever a new line * is typed in the input box. * * @param foo : the class to call */ public void addChatboxInputerHandler(QueueCommandInterface<String> foo) { inputchatbox_Handlers_.add((foo)); } private float fontSize_ = 14f;//The font size /** * Loads the font from file, if it can find it. * * @return */ private Font loadFont() { InputStream in = this.getClass().getResourceAsStream("Font/DejaVuSansMono.ttf"); try { return Font.createFont(Font.TRUETYPE_FONT, in); } catch (Exception e) { System.err.println(e.toString()); return null; } } /** * Taking into account fontSize_, sets the font of the given component. * * @param object */ private void setFont(JComponent object) { Font font = loadFont(); if (font == null) { return; }//If we failed to load the font, do nothing Font resized = font.deriveFont(fontSize_);//This line sets the size of the game, not sure how to make it dynamic atm object.setFont(resized); return; } /** * 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. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { equipment_and_inventory_jTabbedPane = new javax.swing.JTabbedPane(); equip_text_area_jScrollPane = new javax.swing.JScrollPane(); equipment_jTextArea = new javax.swing.JTextArea(); inventory_text_area_jScrollPane = new javax.swing.JScrollPane(); inventory_jTextArea = new javax.swing.JTextArea(); command_text_area_jScrollPane = new javax.swing.JScrollPane(); commands_jTextArea = new javax.swing.JTextArea(); outgoing_text_jTextField = new javax.swing.JTextField(); outgoing_chat_text_area_jScrollPane = new javax.swing.JScrollPane(); incoming_text_jTextArea = new javax.swing.JTextArea(); regular_and_special_skills_jTabbedPane = new javax.swing.JTabbedPane(); regular_skills_jPanel = new javax.swing.JPanel(); bind_wounds_jButton = new javax.swing.JButton(); observe_jButton = new javax.swing.JButton(); bargain_barter_jButton = new javax.swing.JButton(); special_skills_jPanel = new javax.swing.JPanel(); occupation_skill_2_jButton = new javax.swing.JButton(); occupation_skill_1_jButton = new javax.swing.JButton(); occupation_skill_3_jButton = new javax.swing.JButton(); occupation_skill_4_jButton = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); game_jTextPane = new javax.swing.JTextPane(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); equipment_jTextArea.setEditable(false); equipment_jTextArea.setColumns(20); equipment_jTextArea.setRows(5); equip_text_area_jScrollPane.setViewportView(equipment_jTextArea); commands_jTextArea.setEditable(false); commands_jTextArea.setColumns(20); commands_jTextArea.setRows(5); command_text_area_jScrollPane.setViewportView(commands_jTextArea); commands_jTextArea.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { command_jButtonMouseClicked(evt); } }); equipment_and_inventory_jTabbedPane.addTab("Equip", equip_text_area_jScrollPane); equipment_and_inventory_jTabbedPane.addTab("Commands", command_text_area_jScrollPane); inventory_jTextArea.setEditable(false); inventory_jTextArea.setColumns(20); inventory_jTextArea.setRows(5); inventory_text_area_jScrollPane.setViewportView(inventory_jTextArea); equipment_and_inventory_jTabbedPane.addTab("Inventory", inventory_text_area_jScrollPane); outgoing_text_jTextField.setText(""); outgoing_text_jTextField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { outgoing_text_jTextFieldKeyPressed(evt); } }); incoming_text_jTextArea.setEditable(false); incoming_text_jTextArea.setColumns(20); incoming_text_jTextArea.setRows(5); incoming_text_jTextArea.setText("Game Messages: " + System.lineSeparator()); incoming_text_jTextArea.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { incoming_text_jTextAreaKeyTyped(evt); } }); outgoing_chat_text_area_jScrollPane.setViewportView(incoming_text_jTextArea); bind_wounds_jButton.setText("Bind Wounds"); bind_wounds_jButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { bind_wounds_jButtonMouseClicked(evt); } }); observe_jButton.setText("Observe"); observe_jButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { observe_jButtonMouseClicked(evt); } }); bargain_barter_jButton.setText("Bargain / Barter"); bargain_barter_jButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { bargain_barter_jButtonMouseClicked(evt); } }); javax.swing.GroupLayout regular_skills_jPanelLayout = new javax.swing.GroupLayout(regular_skills_jPanel); regular_skills_jPanel.setLayout(regular_skills_jPanelLayout); regular_skills_jPanelLayout.setHorizontalGroup( regular_skills_jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(regular_skills_jPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(regular_skills_jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(bind_wounds_jButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(observe_jButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE) .addComponent(bargain_barter_jButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE)) .addContainerGap()) ); regular_skills_jPanelLayout.setVerticalGroup( regular_skills_jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(regular_skills_jPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(bind_wounds_jButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(bargain_barter_jButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(observe_jButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(54, Short.MAX_VALUE)) ); regular_and_special_skills_jTabbedPane.addTab("Regular", regular_skills_jPanel); occupation_skill_2_jButton.setText("Occupation Skill 2"); occupation_skill_1_jButton.setText("Occupation Skill 1"); occupation_skill_3_jButton.setText("Occupation Skill 3"); occupation_skill_4_jButton.setText("Occupation Skill 4"); javax.swing.GroupLayout special_skills_jPanelLayout = new javax.swing.GroupLayout(special_skills_jPanel); special_skills_jPanel.setLayout(special_skills_jPanelLayout); special_skills_jPanelLayout.setHorizontalGroup( special_skills_jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(special_skills_jPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(special_skills_jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(occupation_skill_2_jButton, javax.swing.GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE) .addComponent(occupation_skill_3_jButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(occupation_skill_4_jButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(occupation_skill_1_jButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); special_skills_jPanelLayout.setVerticalGroup( special_skills_jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(special_skills_jPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(occupation_skill_1_jButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(occupation_skill_2_jButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(occupation_skill_3_jButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(occupation_skill_4_jButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); regular_and_special_skills_jTabbedPane.addTab("Special", special_skills_jPanel); game_jTextPane.setEditable(false); game_jTextPane.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { game_jTextPaneKeyTyped(evt); } }); jScrollPane1.setViewportView(game_jTextPane); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(regular_and_special_skills_jTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(outgoing_text_jTextField) .addComponent(outgoing_chat_text_area_jScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 716, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(equipment_and_inventory_jTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(regular_and_special_skills_jTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(equipment_and_inventory_jTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(outgoing_chat_text_area_jScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(outgoing_text_jTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))))) ); pack(); }// </editor-fold>//GEN-END:initComponents private class TriggerEvents<T> implements Runnable{ ArrayList<QueueCommandInterface<T>> triggers_; public TriggerEvents(ArrayList<QueueCommandInterface<T>> in){triggers_ = in;} @Override public void run() { for(QueueCommandInterface<T> foo : triggers_){ foo.sendInterrupt(); } } } private Thread sendKeyCommandThread_ = new Thread(new TriggerEvents<Key_Commands>(direct_command_receivers_)); private void sendKeyCommand(Key_Commands command) { for (QueueCommandInterface<Key_Commands> foo : direct_command_receivers_) { foo.enqueue(command); } sendKeyCommandThread_.run(); } private Thread incoming_text_jTextAreaKeyTypedThread_ = new Thread(new TriggerEvents<Character>(outputbox_inputHandlers_)); private void incoming_text_jTextAreaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_incoming_text_jTextAreaKeyTyped for (QueueCommandInterface<Character> foo : outputbox_inputHandlers_) { foo.enqueue(evt.getKeyChar()); } incoming_text_jTextAreaKeyTypedThread_.run(); }//GEN-LAST:event_incoming_text_jTextAreaKeyTyped private Thread outoging_text_jTextFieldKeyPressedThread_ = new Thread(new TriggerEvents<String>(inputchatbox_Handlers_)); private void outgoing_text_jTextFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_outgoing_text_jTextFieldKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { String S = outgoing_text_jTextField.getText(); incoming_text_jTextArea.append(System.lineSeparator() + outgoing_text_jTextField.getText()); if (!outgoing_text_jTextField.getText().startsWith("/fontsize")) { for (QueueCommandInterface<String> functor : inputchatbox_Handlers_) { functor.enqueue(S);//Loop through and apply, but ONLY if we haven't already eaten /fontsize. } outoging_text_jTextFieldKeyPressedThread_.run(); } else { try { String temp = outgoing_text_jTextField.getText(); temp = temp.replaceAll("[^0-9 | .]", "");//Regex, to select anything not 0-9 or . System.out.println("Test " + temp); fontSize_ = Float.parseFloat(temp); setFont(); this.addMessage("Set font to " + fontSize_); } catch (Exception e) { this.addMessage("Invalid Font size! Current size is " + Float.toString(fontSize_)); } } outgoing_text_jTextField.setText("");//Upon enter, clear the input box, and move it's text to output updateScroll(); } }//GEN-LAST:event_outgoing_text_jTextFieldKeyPressed private void occupation_skill_1_jButtonMouseClicked(java.awt.event.MouseEvent evt) { sendKeyCommand(Key_Commands.USE_SKILL_1); } private void occupation_skill_2_jButtonMouseClicked(java.awt.event.MouseEvent evt) { sendKeyCommand(Key_Commands.USE_SKILL_2); } private void occupation_skill_3_jButtonMouseClicked(java.awt.event.MouseEvent evt) { sendKeyCommand(Key_Commands.USE_SKILL_3); } private void occupation_skill_4_jButtonMouseClicked(java.awt.event.MouseEvent evt) { sendKeyCommand(Key_Commands.USE_SKILL_4); } private void bind_wounds_jButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bind_wounds_jButtonMouseClicked sendKeyCommand(Key_Commands.BIND_WOUNDS); }//GEN-LAST:event_bind_wounds_jButtonMouseClicked private void bargain_barter_jButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bargain_barter_jButtonMouseClicked sendKeyCommand(Key_Commands.BARGAIN_AND_BARTER); incoming_text_jTextArea.requestFocusInWindow(); }//GEN-LAST:event_bargain_barter_jButtonMouseClicked private void observe_jButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_observe_jButtonMouseClicked sendKeyCommand(Key_Commands.OBSERVE); }//GEN-LAST:event_observe_jButtonMouseClicked private Thread game_jTextPaneKeyTypedThread_ = new Thread(new TriggerEvents<Character>(game_inputHandlers_)); private void game_jTextPaneKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_game_jTextPaneKeyTyped for (QueueCommandInterface<Character> foo : game_inputHandlers_) { foo.enqueue(evt.getKeyChar()); } game_jTextPaneKeyTypedThread_.run(); }//GEN-LAST:event_game_jTextPaneKeyTyped private Thread command_jButtonMouseClickedThread_ = new Thread(new TriggerEvents<String>(command_area_double_clicked_)); private void command_jButtonMouseClicked(java.awt.event.MouseEvent evt) { if (evt.getClickCount() >= 2) { String selected = commands_jTextArea.getSelectedText(); for (QueueCommandInterface<String> foo : command_area_double_clicked_) { foo.enqueue(selected); } command_jButtonMouseClickedThread_.run(); } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bargain_barter_jButton; private javax.swing.JButton bind_wounds_jButton; private javax.swing.JScrollPane equip_text_area_jScrollPane; private javax.swing.JScrollPane command_text_area_jScrollPane; private javax.swing.JTabbedPane equipment_and_inventory_jTabbedPane; private javax.swing.JTextArea equipment_jTextArea; private javax.swing.JTextArea commands_jTextArea; private javax.swing.JTextPane game_jTextPane; private javax.swing.JTextArea incoming_text_jTextArea; private javax.swing.JTextArea inventory_jTextArea; private javax.swing.JScrollPane inventory_text_area_jScrollPane; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton observe_jButton; private javax.swing.JButton occupation_skill_1_jButton; private javax.swing.JButton occupation_skill_2_jButton; private javax.swing.JButton occupation_skill_3_jButton; private javax.swing.JButton occupation_skill_4_jButton; private javax.swing.JScrollPane outgoing_chat_text_area_jScrollPane; private javax.swing.JTextField outgoing_text_jTextField; private javax.swing.JTabbedPane regular_and_special_skills_jTabbedPane; private javax.swing.JPanel regular_skills_jPanel; private javax.swing.JPanel special_skills_jPanel; // End of variables declaration//GEN-END:variables }
package play.test; import java.util.Collections; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Consumer; import java.util.function.Function; import akka.stream.Materializer; import akka.util.ByteString; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import play.Application; import play.api.i18n.DefaultLangs; import play.api.test.Helpers$; import play.core.j.JavaContextComponents; import play.core.j.JavaHandler; import play.core.j.JavaHandlerComponents; import play.core.j.JavaHelpers$; import play.http.HttpEntity; import play.i18n.MessagesApi; import play.inject.guice.GuiceApplicationBuilder; import play.libs.Scala; import play.mvc.Call; import play.mvc.Result; import play.routing.Router; import play.twirl.api.Content; import scala.compat.java8.FutureConverters; import scala.compat.java8.OptionConverters; import static play.libs.Scala.asScala; import static play.mvc.Http.Request; import static play.mvc.Http.RequestBuilder; /** Helper functions to run tests. */ public class Helpers implements play.mvc.Http.Status, play.mvc.Http.HeaderNames { /** * Default Timeout (milliseconds) for fake requests issued by these Helpers. This value is * determined from System property <b>test.timeout</b>. The default value is <b>30000</b> (30 * seconds). */ public static final long DEFAULT_TIMEOUT = Long.getLong("test.timeout", 30000L); public static String GET = "GET"; public static String POST = "POST"; public static String PUT = "PUT"; public static String DELETE = "DELETE"; public static String HEAD = "HEAD"; public static Class<? extends WebDriver> HTMLUNIT = HtmlUnitDriver.class; public static Class<? extends WebDriver> FIREFOX = FirefoxDriver.class; @SuppressWarnings(value = "unchecked") private static Result invokeHandler( play.api.Application app, play.api.mvc.Handler handler, Request requestBuilder, long timeout) { if (handler instanceof play.api.mvc.Action) { play.api.mvc.Action action = (play.api.mvc.Action) handler; return wrapScalaResult(action.apply(requestBuilder.asScala()), timeout); } else if (handler instanceof JavaHandler) { final play.api.inject.Injector injector = app.injector(); final JavaHandlerComponents handlerComponents = injector.instanceOf(JavaHandlerComponents.class); return invokeHandler( app, ((JavaHandler) handler).withComponents(handlerComponents), requestBuilder, timeout); } else { throw new RuntimeException("This is not a JavaAction and can't be invoked this way."); } } private static Result wrapScalaResult( scala.concurrent.Future<play.api.mvc.Result> result, long timeout) { if (result == null) { return null; } else { try { final play.api.mvc.Result scalaResult = FutureConverters.toJava(result) .toCompletableFuture() .get(timeout, TimeUnit.MILLISECONDS); return scalaResult.asJava(); } catch (ExecutionException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { throw new RuntimeException(e.getCause()); } } catch (InterruptedException | TimeoutException e) { throw new RuntimeException(e); } } } /** * Builds a new "GET /" fake request. * * @return the request builder. */ public static RequestBuilder fakeRequest() { return fakeRequest("GET", "/"); } /** * Builds a new fake request. * * @param method the request method. * @param uri the relative URL. * @return the request builder. */ public static RequestBuilder fakeRequest(String method, String uri) { return new RequestBuilder().method(method).uri(uri); } /** * Builds a new fake request corresponding to a given route call. * * @param call the route call. * @return the request builder. */ public static RequestBuilder fakeRequest(Call call) { return fakeRequest(call.method(), call.url()); } /** * Creates a new JavaContextComponents using play.api.Configuration.reference and * play.api.Environment.simple as defaults * * @return the newly created JavaContextComponents * @deprecated Deprecated as of 2.8.0. Inject MessagesApi, Langs, FileMimeTypes or * HttpConfiguration instead */ @Deprecated public static JavaContextComponents contextComponents() { return JavaHelpers$.MODULE$.createContextComponents(); } /** * Builds a new fake application, using GuiceApplicationBuilder. * * @return an application from the current path with no additional configuration. */ public static Application fakeApplication() { return new GuiceApplicationBuilder().build(); } /** * Constructs a in-memory (h2) database configuration to add to a fake application. * * @return a map of String containing database config info. */ public static Map<String, String> inMemoryDatabase() { return inMemoryDatabase("default"); } /** * Constructs a in-memory (h2) database configuration to add to a fake application. * * @param name the database name. * @return a map of String containing database config info. */ public static Map<String, String> inMemoryDatabase(String name) { return inMemoryDatabase(name, Collections.<String, String>emptyMap()); } /** * Constructs a in-memory (h2) database configuration to add to a fake application. * * @param name the database name. * @param options the database options. * @return a map of String containing database config info. */ public static Map<String, String> inMemoryDatabase(String name, Map<String, String> options) { return Scala.asJava(play.api.test.Helpers.inMemoryDatabase(name, Scala.asScala(options))); } /** * Constructs an empty messagesApi instance. * * @return a messagesApi instance containing no values. */ public static MessagesApi stubMessagesApi() { return new play.i18n.MessagesApi( new play.api.i18n.DefaultMessagesApi(Collections.emptyMap(), new DefaultLangs().asJava())); } /** * Constructs a MessagesApi instance containing the given keys and values. * * @return a messagesApi instance containing given keys and values. */ public static MessagesApi stubMessagesApi( Map<String, Map<String, String>> messages, play.i18n.Langs langs) { return new play.i18n.MessagesApi(new play.api.i18n.DefaultMessagesApi(messages, langs)); } /** * Build a new fake application. Uses GuiceApplicationBuilder. * * @param additionalConfiguration map containing config info for the app. * @return an application from the current path with additional configuration. */ public static Application fakeApplication(Map<String, ?> additionalConfiguration) { @SuppressWarnings("unchecked") Map<String, Object> conf = (Map<String, Object>) additionalConfiguration; return new GuiceApplicationBuilder().configure(conf).build(); } /** * Extracts the content as a {@link akka.util.ByteString}. * * <p>This method is only capable of extracting the content of results with strict entities. To * extract the content of results with streamed entities, use {@link * Helpers#contentAsBytes(Result, Materializer)}. * * @param result The result to extract the content from. * @return The content of the result as a ByteString. * @throws UnsupportedOperationException if the result does not have a strict entity. */ public static ByteString contentAsBytes(Result result) { if (result.body() instanceof HttpEntity.Strict) { return ((HttpEntity.Strict) result.body()).data(); } else { throw new UnsupportedOperationException( "Tried to extract body from a non strict HTTP entity without a materializer, use the version of this method that accepts a materializer instead"); } } /** * Extracts the content as a {@link akka.util.ByteString}. * * @param result The result to extract the content from. * @param mat The materializer to use to extract the body from the result stream. * @return The content of the result as a ByteString. */ public static ByteString contentAsBytes(Result result, Materializer mat) { return contentAsBytes(result, mat, DEFAULT_TIMEOUT); } /** * Extracts the content as a {@link akka.util.ByteString}. * * @param result The result to extract the content from. * @param mat The materializer to use to extract the body from the result stream. * @param timeout The amount of time, in milliseconds, to wait for the body to be produced. * @return The content of the result as a ByteString. */ public static ByteString contentAsBytes(Result result, Materializer mat, long timeout) { try { return result .body() .consumeData(mat) .thenApply(Function.identity()) .toCompletableFuture() .get(timeout, TimeUnit.MILLISECONDS); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } /** * Extracts the content as bytes. * * @param content the content to be turned into bytes. * @return the body of the content as a byte string. */ public static ByteString contentAsBytes(Content content) { return ByteString.fromString(content.body()); } /** * Extracts the content as a String. * * @param content the content. * @return the body of the content as a String. */ public static String contentAsString(Content content) { return content.body(); } /** * Extracts the content as a String. * * <p>This method is only capable of extracting the content of results with strict entities. To * extract the content of results with streamed entities, use {@link * Helpers#contentAsString(Result, Materializer)}. * * @param result The result to extract the content from. * @return The content of the result as a String. * @throws UnsupportedOperationException if the result does not have a strict entity. */ public static String contentAsString(Result result) { return contentAsBytes(result).decodeString(result.charset().orElse("utf-8")); } /** * Extracts the content as a String. * * @param result The result to extract the content from. * @param mat The materializer to use to extract the body from the result stream. * @return The content of the result as a String. */ public static String contentAsString(Result result, Materializer mat) { return contentAsBytes(result, mat, DEFAULT_TIMEOUT) .decodeString(result.charset().orElse("utf-8")); } /** * Extracts the content as a String. * * @param result The result to extract the content from. * @param mat The materializer to use to extract the body from the result stream. * @param timeout The amount of time, in milliseconds, to wait for the body to be produced. * @return The content of the result as a String. */ public static String contentAsString(Result result, Materializer mat, long timeout) { return contentAsBytes(result, mat, timeout).decodeString(result.charset().orElse("utf-8")); } /** * Route and call the request. * * @param app The application used while routing and executing the request * @param router The router * @param requestBuilder The request builder * @return the result */ public static Result routeAndCall(Application app, Router router, RequestBuilder requestBuilder) { return routeAndCall(app, router, requestBuilder, DEFAULT_TIMEOUT); } /** * Route and call the request, respecting the given timeout. * * @param app The application used while routing and executing the request * @param router The router * @param requestBuilder The request builder * @param timeout The amount of time, in milliseconds, to wait for the body to be produced. * @return the result */ public static Result routeAndCall( Application app, Router router, RequestBuilder requestBuilder, long timeout) { try { Request request = requestBuilder.build(); return router .route(request) .map(handler -> invokeHandler(app.asScala(), handler, request, timeout)) .orElse(null); } catch (RuntimeException e) { throw e; } catch (Throwable t) { throw new RuntimeException(t); } } /** * Route a call using the given application. * * @param app the application * @param call the call to route * @see GuiceApplicationBuilder * @return the result */ public static Result route(Application app, Call call) { return route(app, fakeRequest(call)); } /** * Route a call using the given application and timeout. * * @param app the application * @param call the call to route * @param timeout the time out * @see GuiceApplicationBuilder * @return the result */ public static Result route(Application app, Call call, long timeout) { return route(app, fakeRequest(call), timeout); } /** * Route a request. * * @param app The application used while routing and executing the request * @param requestBuilder the request builder * @return the result. */ public static Result route(Application app, RequestBuilder requestBuilder) { return route(app, requestBuilder, DEFAULT_TIMEOUT); } /** * Route the request considering the given timeout. * * @param app The application used while routing and executing the request * @param requestBuilder the request builder * @param timeout the amount of time, in milliseconds, to wait for the body to be produced. * @return the result */ @SuppressWarnings("unchecked") public static Result route(Application app, RequestBuilder requestBuilder, long timeout) { final scala.Option<scala.concurrent.Future<play.api.mvc.Result>> opt = play.api.test.Helpers.jRoute( app.asScala(), requestBuilder.build().asScala(), requestBuilder.body()); return wrapScalaResult(Scala.orNull(opt), timeout); } /** * Starts a new application. * * @param application the application to start. */ public static void start(Application application) { play.api.Play.start(application.asScala()); } /** * Stops an application. * * @param application the application to stop. */ public static void stop(Application application) { play.api.Play.stop(application.asScala()); } /** * Executes a block of code in a running application. * * @param application the application context. * @param block the block to run after the Play app is started. */ public static void running(Application application, final Runnable block) { Helpers$.MODULE$.running( application.asScala(), asScala( () -> { block.run(); return null; })); } /** * Creates a new Test server listening on port defined by configuration setting "testserver.port" * (defaults to 19001). * * @return the test server. */ public static TestServer testServer() { return testServer(play.api.test.Helpers.testServerPort()); } /** * Creates a new Test server listening on port defined by configuration setting "testserver.port" * (defaults to 19001) and using the given Application. * * @param app the application. * @return the test server. */ public static TestServer testServer(Application app) { return testServer(play.api.test.Helpers.testServerPort(), app); } /** * Creates a new Test server. * * @param port the port to run the server on. * @return the test server. */ public static TestServer testServer(int port) { return new TestServer(port, fakeApplication()); } /** * Creates a new Test server. * * @param port the port to run the server on. * @param sslPort the port to run the server on. * @return the test server. */ public static TestServer testServer(int port, int sslPort) { return new TestServer(port, fakeApplication(), sslPort); } /** * Creates a new Test server. * * @param port the port to run the server on. * @param app the Play application. * @return the test server. */ public static TestServer testServer(int port, Application app) { return new TestServer(port, app); } /** * Starts a Test server. * * @param server the test server to start. */ public static void start(TestServer server) { server.start(); } /** * Stops a Test server. * * @param server the test server to stop.a */ public static void stop(TestServer server) { server.stop(); } /** * Executes a block of code in a running server. * * @param server the server to start. * @param block the block of code to run after the server starts. */ public static void running(TestServer server, final Runnable block) { Helpers$.MODULE$.running( server, asScala( () -> { block.run(); return null; })); } /** * Executes a block of code in a running server, with a test browser. * * @param server the test server. * @param webDriver the web driver class. * @param block the block of code to execute. */ public static void running( TestServer server, Class<? extends WebDriver> webDriver, final Consumer<TestBrowser> block) { running(server, play.api.test.WebDriverFactory.apply(webDriver), block); } /** * Executes a block of code in a running server, with a test browser. * * @param server the test server. * @param webDriver the web driver instance. * @param block the block of code to execute. */ public static void running( TestServer server, WebDriver webDriver, final Consumer<TestBrowser> block) { Helpers$.MODULE$.runSynchronized( server.application(), asScala( () -> { TestBrowser browser = null; TestServer startedServer = null; try { start(server); startedServer = server; browser = testBrowser( webDriver, (Integer) OptionConverters.toJava(server.config().port()).get()); block.accept(browser); } finally { if (browser != null) { browser.quit(); } if (startedServer != null) { stop(startedServer); } } return null; })); } /** * Creates a Test Browser. * * @return the test browser. */ public static TestBrowser testBrowser() { return testBrowser(HTMLUNIT); } /** * Creates a Test Browser. * * @param port the local port. * @return the test browser. */ public static TestBrowser testBrowser(int port) { return testBrowser(HTMLUNIT, port); } /** * Creates a Test Browser. * * @param webDriver the class of webdriver. * @return the test browser. */ public static TestBrowser testBrowser(Class<? extends WebDriver> webDriver) { return testBrowser(webDriver, Helpers$.MODULE$.testServerPort()); } /** * Creates a Test Browser. * * @param webDriver the class of webdriver. * @param port the local port to test against. * @return the test browser. */ public static TestBrowser testBrowser(Class<? extends WebDriver> webDriver, int port) { try { return new TestBrowser(webDriver, "http://localhost:" + port); } catch (RuntimeException e) { throw e; } catch (Throwable t) { throw new RuntimeException(t); } } public static TestBrowser testBrowser(WebDriver of, int port) { return new TestBrowser(of, "http://localhost:" + port); } /** * Creates a Test Browser. * * @param of the web driver to run the browser with. * @return the test browser. */ public static TestBrowser testBrowser(WebDriver of) { return testBrowser(of, Helpers$.MODULE$.testServerPort()); } }
package org.biojava.bio.structure.io; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.biojava.bio.BioException; import org.biojava.bio.alignment.NeedlemanWunsch; import org.biojava.bio.alignment.SubstitutionMatrix; import org.biojava.bio.seq.ProteinTools; import org.biojava.bio.seq.Sequence; import org.biojava.bio.structure.AminoAcid; import org.biojava.bio.structure.Chain; import org.biojava.bio.structure.Group; import org.biojava.bio.structure.Structure; import org.biojava.bio.structure.StructureException; import org.biojava.bio.symbol.AlphabetManager; import org.biojava.bio.symbol.FiniteAlphabet; import org.biojava.bio.symbol.SimpleAlignment; import org.biojava.bio.symbol.Symbol; import org.biojava.bio.symbol.SymbolList; /** Aligns the SEQRES residues to the ATOM residues. * The AminoAcids that can be matched between the two of them will be set in the SEQRES * chains * * * @author Andreas Prlic * */ public class SeqRes2AtomAligner { boolean DEBUG = false; static final List<String> excludeTypes; private static final FiniteAlphabet alphabet; private static final Symbol gapSymbol ; private static SubstitutionMatrix matrix; String alignmentString; static { excludeTypes = new ArrayList<String>(); excludeTypes.add("HOH"); // we don't want to align water against the SEQRES... excludeTypes.add("DOD"); // deuterated water alphabet = (FiniteAlphabet) AlphabetManager.alphabetForName("PROTEIN-TERM"); gapSymbol = alphabet.getGapSymbol(); try { matrix = getSubstitutionMatrix(alphabet); } catch (BioException e){ e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } //matrix.printMatrix(); } public SeqRes2AtomAligner(){ alignmentString = ""; } public String getAlignmentString() { return alignmentString; } public boolean isDEBUG() { return DEBUG; } public void setDEBUG(boolean debug) { DEBUG = debug; } private Chain getMatchingAtomRes(Chain seqRes, List<Chain> atomList) throws StructureException { Iterator<Chain> iter = atomList.iterator(); while(iter.hasNext()){ Chain atom = iter.next(); if ( atom.getName().equals(seqRes.getName())){ return atom; } } throw new StructureException("could not match seqres chainID >" + seqRes.getName() + "< to ATOM chains!"); } public void align(Structure s, List<Chain> seqResList){ //List<Chain> seqResList = s.getSeqRes(); List<Chain> atomList = s.getModel(0); Iterator<Chain> iter = seqResList.iterator(); // List<Chain> chains = new ArrayList<Chain>(); while ( iter.hasNext()){ Chain seqRes = iter.next(); if ( seqRes.getAtomGroups("amino").size() < 1) { if (DEBUG){ System.out.println("chain " + seqRes.getName() + " does not contain amino acids, ignoring..."); } continue; } try { Chain atomRes = getMatchingAtomRes(seqRes,atomList); if ( atomRes.getAtomGroups("amino").size() < 1) { if (DEBUG){ System.out.println("chain " + atomRes.getName() + " does not contain amino acids, ignoring..."); } continue; } if ( DEBUG ) System.out.println("Alignment for chain "+ atomRes.getName()); List<Group> seqResGroups = seqRes.getAtomGroups(); boolean noMatchFound = align(seqResGroups,atomRes.getAtomGroups()); if ( ! noMatchFound){ atomRes.setSeqResGroups(seqResGroups); } //chains.add(mapped); } catch (StructureException e){ e.printStackTrace(); } } //s.setChains(0,chains); } /** returns the full sequence of the Atom records of a chain * with X instead of HETATMSs. The advantage of this is * that it allows us to also align HETATM groups back to the SEQRES. * @param groups the list of groups in a chain * * @return string representations */ public String getFullAtomSequence(List<Group> groups){ StringBuffer sequence = new StringBuffer() ; for ( int i=0 ; i< groups.size(); i++){ Group g = (Group) groups.get(i); if ( g instanceof AminoAcid ){ AminoAcid a = (AminoAcid)g; sequence.append( a.getAminoType()); } else { if ( ! excludeTypes.contains(g.getPDBName())) sequence.append("X"); } } return sequence.toString(); } /** aligns two chains of groups, where the first chain is representing the * list of amino acids as obtained from the SEQRES records, and the second chain * represents the groups obtained from the ATOM records (and containing the actual ATOM information). * This does the actual alignment and if a group can be mapped to a position in the SEQRES then the corresponding * position is repplaced with the group that contains the atoms. * * @param seqRes * @param atomRes * @return true if no match has bee found * @throws StructureException */ public boolean align(List<Group> seqRes, List<Group> atomRes) throws StructureException{ /** int MAX_SIZE = 1000; if ( (seqRes.size() > MAX_SIZE) ||( atomRes.size() > MAX_SIZE) ) { System.err.println("can not align chains, length size exceeds limits!"); return false; } */ String seq1 = getFullAtomSequence(seqRes); //String seq1 = seqRes.getSeqResSequence(); String seq2 = getFullAtomSequence(atomRes); //System.out.println("align seq1 " + seq1); //System.out.println("align seq2 " + seq2); SimpleAlignment simpleAli = null; try { Sequence bjseq1 = ProteinTools.createProteinSequence(seq1,"seq1"); Sequence bjseq2 = ProteinTools.createProteinSequence(seq2,"seq2"); //System.out.println(bjseq1.getAlphabet()); NeedlemanWunsch aligner = new NeedlemanWunsch(-2, 5, 3, 3, 0,matrix); if (DEBUG){ System.out.println("seq lengths: " + bjseq1.seqString().length() + " " + bjseq2.seqString().length()); System.out.println("seq1: " + bjseq1.seqString()); System.out.println("seq2: " + bjseq2.seqString()); } org.biojava.bio.symbol.Alignment ali = aligner.getAlignment(bjseq1,bjseq2); if ( ! (ali instanceof SimpleAlignment )) { throw new Exception ("Alignment is not a SimpleAlignment!"); } simpleAli = (SimpleAlignment) ali; alignmentString = aligner.getAlignmentString(); if (DEBUG) System.out.println(alignmentString); } catch (Exception e){ e.printStackTrace(); System.err.println("align seq1 " + seq1); System.err.println("align seq2 " + seq2); } if ( simpleAli == null) throw new StructureException("could not align objects!"); //System.out.println(ali.getAlphabet()); SymbolList lst1 = simpleAli.symbolListForLabel("seq1"); //System.out.println("from seqres : " + lst1.seqString()); SymbolList lst2 = simpleAli.symbolListForLabel("seq2"); boolean noMatchFound = mapChains(seqRes,lst1,atomRes,lst2,gapSymbol); return noMatchFound; } private boolean mapChains(List<Group> seqRes, SymbolList lst1, List<Group> atomRes, SymbolList lst2,Symbol gapSymbol) throws StructureException{ assert (lst1.length() == lst2.length()); // at the present stage the future seqREs are still stored as Atom groups in the seqRes chain... List<Group> seqResGroups = seqRes; int aligLength = lst1.length(); int posSeq = -1; int posAtom = -1; // System.out.println(gapSymbol.getName()); // make sure we actually find an alignment boolean noMatchFound = true; for (int i = 1; i <= aligLength; i++) { Symbol s = lst1.symbolAt(i); Symbol a = lst2.symbolAt(i); //TODO replace the text gap with the proper symbol for terminal gap // don't count gaps and terminal gaps String sn = s.getName(); String an = a.getName(); if (! ( sn.equals("gap") || sn.equals(gapSymbol.getName()))){ posSeq++; } if (! ( an.equals("gap") || an.equals(gapSymbol.getName()))){ posAtom++; } /* System.out.println(i+ " " + posSeq + " " + s.getName() + " " + posAtom + " " + a.getName() + " " + s.getName().equals(a.getName())); */ if ( s.getName().equals(a.getName())){ // the atom record can be aligned to the SeqRes record! // replace the SeqRes group with the Atom group! Group s1 = seqRes.get(posSeq); Group a1 = atomRes.get(posAtom); //System.out.println(s1.getPDBName() + " == " + a1.getPDBName()); // need to trim the names to allow matching e.g in // pdb1b2m String pdbNameS = s1.getPDBName(); String pdbNameA = a1.getPDBName(); if (! pdbNameA.equals(pdbNameS)){ if ( ! pdbNameA.trim().equals(pdbNameS.trim())) { System.err.println(s1 + " " + posSeq + " does not align with " + a1+ " " + posAtom); //System.exit(0);// for debug only throw new StructureException("could not match residues"); } } // do the actual replacing of the SEQRES group with the ATOM group seqResGroups.set(posSeq,a1); noMatchFound = false; } } // now we merge the two chains into one // the Groups that can be aligned are now pointing to the // groups in the Atom records. if ( noMatchFound) { if ( DEBUG ) System.out.println("no alignment found!"); } return noMatchFound; } public static SubstitutionMatrix getSubstitutionMatrix(FiniteAlphabet alphabet) throws IOException,BioException { InputStream inStream = SeqRes2AtomAligner.class.getResourceAsStream("/org/biojava/bio/structure/blosum62.mat"); String newline = System.getProperty("line.separator"); BufferedReader reader = new BufferedReader(new InputStreamReader( inStream)); StringBuffer file = new StringBuffer(); while (reader.ready()){ file.append(reader.readLine() ); file.append(newline); } SubstitutionMatrix matrix = new SubstitutionMatrix(alphabet,file.toString(),"blosum 62"); return matrix; } }
package org.nutz.dao.impl.ext; import java.lang.reflect.Method; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import java.util.WeakHashMap; import javax.sql.DataSource; import org.nutz.aop.ClassAgent; import org.nutz.aop.DefaultClassDefiner; import org.nutz.aop.InterceptorChain; import org.nutz.aop.MethodInterceptor; import org.nutz.aop.asm.AsmClassAgent; import org.nutz.aop.matcher.MethodMatcherFactory; import org.nutz.dao.Dao; import org.nutz.dao.entity.Entity; import org.nutz.dao.entity.LinkField; import org.nutz.dao.impl.EntityHolder; import org.nutz.dao.impl.entity.AnnotationEntityMaker; import org.nutz.dao.impl.entity.NutEntity; import org.nutz.dao.jdbc.JdbcExpert; import org.nutz.ioc.aop.config.InterceptorPair; import org.nutz.lang.Mirror; import org.nutz.lang.Strings; import org.nutz.lang.born.BornContext; import org.nutz.lang.born.Borns; import org.nutz.log.Log; import org.nutz.log.Logs; /** * AnnotationEntityMaker * * @author wendal(wendal1985@gmail.com) * */ public class LazyAnnotationEntityMaker extends AnnotationEntityMaker { private static final Log log = Logs.get(); private Dao dao; public LazyAnnotationEntityMaker(DataSource datasource, JdbcExpert expert, EntityHolder holder, Dao dao) { super(datasource, expert, holder); this.dao = dao; } protected <T> NutEntity<T> _createNutEntity(Class<T> type) { return new LazyNutEntity<T>(type); } @Override public <T> Entity<T> make(Class<T> type) { LazyNutEntity<T> en = (LazyNutEntity<T>) super.make(type); en.init(); return en; } class LazyNutEntity<T> extends NutEntity<T> { public LazyNutEntity(Class<T> type) { super(type); } @SuppressWarnings({"rawtypes", "unchecked"}) public void init() { List<LinkField> lfs = new ArrayList<LinkField>(); lfs.addAll(ones.getAll()); lfs.addAll(manys.getAll()); lfs.addAll(manymanys.getAll()); if (lfs.isEmpty()) return; if (log.isDebugEnabled()) log.debug("Found links , enable lazy!! -->" + type); Mirror<T> mirror = Mirror.me(type); List<InterceptorPair> interceptorPairs = new ArrayList<InterceptorPair>(); for (LinkField lf : lfs) { String fieldName = lf.getName(); try { Method setter = mirror.getSetter(mirror.getField(fieldName)); LazyMethodInterceptor lmi = new LazyMethodInterceptor(setter, fieldName); interceptorPairs.add(new InterceptorPair(lmi, MethodMatcherFactory.matcher("^(get|set)" + Strings.upperFirst(fieldName) + "$"))); } catch (Throwable e) { if (log.isWarnEnabled()) log.warn("Not setter found for LazyLoading ?!", e); } } // Aop ClassAgent agent = new AsmClassAgent(); for (InterceptorPair interceptorPair : interceptorPairs) agent.addInterceptor(interceptorPair.getMethodMatcher(), interceptorPair.getMethodInterceptor()); Class lazyClass = agent.define(DefaultClassDefiner.defaultOne(), type); BornContext<T> bc = Borns.evalByArgTypes(type, ResultSet.class); if (null == bc) this.bornByDefault = Mirror.me(lazyClass) .getBorningByArgTypes(); else this.bornByRS = bc.getBorning(); } } class LazyMethodInterceptor implements MethodInterceptor { private WeakHashMap<Object, LazyStatus> status = new WeakHashMap<Object, LazyAnnotationEntityMaker.LazyStatus>(); private Method setter; private String fieldName; public LazyMethodInterceptor(Method setter, String fieldName) { this.setter = setter; this.fieldName = fieldName; } public void filter(InterceptorChain chain) throws Throwable { LazyStatus stat = status.get(chain.getCallingObj()); if (stat == null) { if (!chain.getCallingMethod().equals(setter)) { dao.fetchLinks(chain.getCallingObj(), fieldName);// setter } status.put(chain.getCallingObj(), LazyStatus.NO_NEED); // setter, } chain.doChain(); } } enum LazyStatus { CAN_FETCH, FETCHED, NO_NEED } }
package com.rtg.reference; import java.io.File; import java.io.IOException; import com.rtg.launcher.AbstractNanoTest; import com.rtg.reader.AnnotatedSequencesReader; import com.rtg.reader.ReaderTestUtils; import com.rtg.reader.SequencesReaderFactory; import com.rtg.util.Resources; import com.rtg.util.io.TestDirectory; import com.rtg.util.test.FileHelper; public class ReferenceDetectorTest extends AbstractNanoTest { public void test() throws IOException { try (TestDirectory dir = new TestDirectory()) { final String dna = mNano.loadReference("testref.fasta"); final File sdfDir = ReaderTestUtils.getDNADir(dna, new File(dir, "sdf")); final ReferenceDetector detector = ReferenceDetector.loadManifest(Resources.getResourceAsStream("com/rtg/reference/resources/testref.manifest")); try (final AnnotatedSequencesReader reader = SequencesReaderFactory.createDefaultSequencesReader(sdfDir)) { assertTrue(detector.checkReference(reader)); detector.installReferenceConfiguration(reader); final File refTxt = new File(sdfDir, "reference.txt"); assertTrue(refTxt.exists()); mNano.check("testref-reference.txt", FileHelper.fileToString(refTxt), false); } } } }
package org.objectweb.proactive.core.body; import org.objectweb.proactive.core.UniqueID; import org.objectweb.proactive.core.body.reply.Reply; import org.objectweb.proactive.core.body.request.Request; import org.objectweb.proactive.core.component.identity.ProActiveComponent; import java.io.IOException; /** * An object implementing this interface provides the minimum service a body offers * remotely or locally. This interface is the generic version that is used remotely * and locally. A body accessed from the same JVM offers all services of this interface, * plus the services defined in the Body interface. * * @author ProActive Team * @version 1.0, 2001/10/23 * @since ProActive 0.9 * @see org.objectweb.proactive.Body * @see org.objectweb.proactive.core.body.rmi.RemoteBodyAdapter */ public interface UniversalBody { /** * Receives a request for later processing. The call to this method is non blocking * unless the body cannot temporary receive the request. * @param request the request to process * @exception java.io.IOException if the request cannot be accepted */ public void receiveRequest(Request request) throws java.io.IOException; /** * Receives a reply in response to a former request. * @param reply the reply received * @exception java.io.IOException if the reply cannot be accepted */ public void receiveReply(Reply r) throws java.io.IOException; /** * Returns the url of the node this body is associated to * The url of the node can change if the active object migrates * @return the url of the node this body is associated to */ public String getNodeURL(); /** * Returns the UniqueID of this body * This identifier is unique accross all JVMs * @return the UniqueID of this body */ public UniqueID getID(); /** * Signals to this body that the body identified by id is now to a new * remote location. The body given in parameter is a new stub pointing * to this new location. This call is a way for a body to signal to his * peer that it has migrated to a new location * @param id the id of the body * @param body the stub to the new location */ public void updateLocation(UniqueID id, UniversalBody body) throws java.io.IOException; /** * Returns the remote friendly version of this body * @return the remote friendly version of this body */ public UniversalBody getRemoteAdapter(); /** * Enables automatic continuation mechanism for this body */ public void enableAC() throws java.io.IOException; /** * Disables automatic continuation mechanism for this body */ public void disableAC() throws java.io.IOException; /** * For setting an immediate service for this body. * An immediate service is a method that will bw excecuted by the calling thread. */ public void setImmediateService(String methodName) throws IOException; /** * Returns a reference on the component metaobject */ // COMPONENTS public ProActiveComponent getProActiveComponent() throws IOException; }
package org.openhab.habdroid.ui; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Timer; import java.util.TimerTask; import org.openhab.habdroid.R; import org.openhab.habdroid.util.Util; import com.google.analytics.tracking.android.EasyTracker; import android.nfc.FormatException; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.Ndef; import android.nfc.tech.NdefFormatable; import android.os.Bundle; import android.preference.PreferenceManager; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class OpenHABWriteTagActivity extends Activity { // Logging TAG private static final String TAG = "OpenHABWriteTagActivity"; private String sitemapPage = ""; private String widget = ""; private String command = ""; @Override public void onStart() { super.onStart(); EasyTracker.getInstance().activityStart(this); } @Override public void onStop() { super.onStop(); EasyTracker.getInstance().activityStop(this); } @Override protected void onCreate(Bundle savedInstanceState) { Util.setActivityTheme(this); super.onCreate(savedInstanceState); setContentView(R.layout.openhabwritetag); TextView writeTagMessage = (TextView)findViewById(R.id.write_tag_message); if (!this.getPackageManager().hasSystemFeature("android.hardware.nfc")) { writeTagMessage.setText(R.string.info_write_tag_unsupported); } else if (NfcAdapter.getDefaultAdapter(this) != null) { if (!NfcAdapter.getDefaultAdapter(this).isEnabled()) { writeTagMessage.setText(R.string.info_write_tag_disabled); } } if (getIntent().hasExtra("sitemapPage")) { sitemapPage = getIntent().getExtras().getString("sitemapPage"); Log.d(TAG, "Got sitemapPage = " + sitemapPage); } if (getIntent().hasExtra("widget")) { widget = getIntent().getExtras().getString("widget"); Log.d(TAG, "Got widget = " + widget); } if (getIntent().hasExtra("command")) { command = getIntent().getExtras().getString("command"); Log.d(TAG, "Got command = " + command); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main_menu, menu); return true; } @Override public void onResume() { Log.d(TAG, "onResume()"); super.onResume(); PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); if (NfcAdapter.getDefaultAdapter(this) != null) NfcAdapter.getDefaultAdapter(this).enableForegroundDispatch(this, pendingIntent, null, null); } @Override public void onPause() { Log.d(TAG, "onPause()"); super.onPause(); if(NfcAdapter.getDefaultAdapter(this) != null) NfcAdapter.getDefaultAdapter(this).disableForegroundDispatch(this); } public void onNewIntent(Intent intent) { Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); String openhabURI = ""; //do something with tagFromIntent Log.d(TAG, "NFC TAG = " + tagFromIntent.toString()); Log.d(TAG, "Writing page " + sitemapPage + " to TAG"); TextView writeTagMessage = (TextView)findViewById(R.id.write_tag_message); try { URI sitemapURI = new URI(sitemapPage); if (sitemapURI.getPath().startsWith("/rest/sitemaps")) { openhabURI = "openhab://sitemaps" + sitemapURI.getPath().substring(14, sitemapURI.getPath().length()); if (widget.length() > 0) { openhabURI = openhabURI + "?widget=" + widget; } if (command.length() > 0) { openhabURI = openhabURI + "&command=" + command; } } Log.d(TAG, "URI = " + openhabURI); writeTagMessage.setText(R.string.info_write_tag_progress); writeTag(tagFromIntent, openhabURI); } catch (URISyntaxException e) { Log.e(TAG, e.getMessage()); writeTagMessage.setText(R.string.info_write_failed); } } public void writeTag(Tag tag, String openhabUri) { Log.d(TAG, "Creating tag object"); TextView writeTagMessage = (TextView)findViewById(R.id.write_tag_message); NdefRecord[] ndefRecords; ndefRecords = new NdefRecord[1]; ndefRecords[0] = NdefRecord.createUri(openhabUri); NdefMessage message = new NdefMessage(ndefRecords); NdefFormatable ndefFormatable = NdefFormatable.get(tag); if (ndefFormatable != null) { Log.d(TAG, "Tag is uninitialized, formating"); try { ndefFormatable.connect(); ndefFormatable.format(message); ndefFormatable.close(); writeTagMessage.setText(R.string.info_write_tag_finished); autoCloseActivity(); } catch (IOException e) { // TODO Auto-generated catch block if (e.getMessage() != null) Log.e(TAG, e.getMessage()); writeTagMessage.setText(R.string.info_write_failed); } catch (FormatException e) { // TODO Auto-generated catch block Log.e(TAG, e.getMessage()); writeTagMessage.setText(R.string.info_write_failed); } } else { Log.d(TAG, "Tag is initialized, writing"); Ndef ndef = Ndef.get(tag); if (ndef != null) { try { Log.d(TAG, "Connecting"); ndef.connect(); Log.d(TAG, "Writing"); if (ndef.isWritable()) { ndef.writeNdefMessage(message); } Log.d(TAG, "Closing"); ndef.close(); writeTagMessage.setText(R.string.info_write_tag_finished); autoCloseActivity(); } catch (IOException e) { // TODO Auto-generated catch block if (e != null) Log.e(TAG, e.getMessage()); } catch (FormatException e) { // TODO Auto-generated catch block Log.e(TAG, e.getMessage()); } } else { Log.e(TAG, "Ndef == null"); writeTagMessage.setText(R.string.info_write_failed); } } } private void autoCloseActivity() { Timer autoCloseTimer = new Timer(); autoCloseTimer.schedule(new TimerTask() { @Override public void run() { finish(); Log.d(TAG, "Autoclosing tag write activity"); } }, 2000); } }
package org.pentaho.di.core.database; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.row.ValueMetaInterface; /** * Contains Oracle specific information through static final members * * @author Matt * @since 11-mrt-2005 */ public class OracleDatabaseMeta extends BaseDatabaseMeta implements DatabaseInterface { /** * Construct a new database connections. Note that not all these parameters are not allways mandatory. * * @param name The database name * @param access The type of database access * @param host The hostname or IP address * @param db The database name * @param port The port on which the database listens. * @param user The username * @param pass The password */ public OracleDatabaseMeta(String name, String access, String host, String db, String port, String user, String pass) { super(name, access, host, db, port, user, pass); } public OracleDatabaseMeta() { } public String getDatabaseTypeDesc() { return "ORACLE"; } public String getDatabaseTypeDescLong() { return "Oracle"; } /** * @return Returns the databaseType. */ public int getDatabaseType() { return DatabaseMeta.TYPE_DATABASE_ORACLE; } public int[] getAccessTypeList() { return new int[] { DatabaseMeta.TYPE_ACCESS_NATIVE, DatabaseMeta.TYPE_ACCESS_ODBC, DatabaseMeta.TYPE_ACCESS_OCI, DatabaseMeta.TYPE_ACCESS_JNDI }; } public int getDefaultDatabasePort() { if (getAccessType()==DatabaseMeta.TYPE_ACCESS_NATIVE) return 1521; return -1; } /** * @return Whether or not the database can use auto increment type of fields (pk) */ public boolean supportsAutoInc() { return false; } /** * @see org.pentaho.di.core.database.DatabaseInterface#getLimitClause(int) */ public String getLimitClause(int nrRows) { return " WHERE ROWNUM <= "+nrRows; } /** * Returns the minimal SQL to launch in order to determine the layout of the resultset for a given database table * @param tableName The name of the table to determine the layout for * @return The SQL to launch. */ public String getSQLQueryFields(String tableName) { return "SELECT /*+FIRST_ROWS*/ * FROM "+tableName+" WHERE ROWNUM < 1"; } public String getSQLTableExists(String tablename) { return getSQLQueryFields(tablename); } public boolean needsToLockAllTables() { return false; } public String getDriverClass() { if (getAccessType()==DatabaseMeta.TYPE_ACCESS_ODBC) { return "sun.jdbc.odbc.JdbcOdbcDriver"; } else { return "oracle.jdbc.driver.OracleDriver"; } } public String getURL(String hostname, String port, String databaseName) throws KettleDatabaseException { if (getAccessType()==DatabaseMeta.TYPE_ACCESS_ODBC) { return "jdbc:odbc:"+databaseName; } else if (getAccessType()==DatabaseMeta.TYPE_ACCESS_NATIVE) { // the database name can be a SID (starting with :) or a Service (starting with /) //<host>:<port>/<service> //<host>:<port>:<SID> if (databaseName != null && databaseName.length()>0 && (databaseName.startsWith("/") || databaseName.startsWith(":"))) { return "jdbc:oracle:thin:@"+hostname+":"+port+databaseName; } else { // by default we assume a SID return "jdbc:oracle:thin:@"+hostname+":"+port+":"+databaseName; } } else // OCI { // Let's see if we have an database name if (getDatabaseName()!=null && getDatabaseName().length()>0) { // Has the user specified hostname & port number? if (getHostname()!=null && getHostname().length()>0 && getDatabasePortNumberString()!=null && getDatabasePortNumberString().length()>0) { // User wants the full url return "jdbc:oracle:oci:@(description=(address=(host="+getHostname()+")(protocol=tcp)(port="+getDatabasePortNumberString()+"))(connect_data=(sid="+getDatabaseName()+")))"; } else { // User wants the shortcut url return "jdbc:oracle:oci:@"+getDatabaseName(); } } else { throw new KettleDatabaseException("Unable to construct a JDBC URL: at least the database name must be specified"); } } } /** * Oracle doesn't support options in the URL, we need to put these in a Properties object at connection time... */ public boolean supportsOptionsInURL() { return false; } /** * @return true if the database supports sequences */ public boolean supportsSequences() { return true; } /** * Check if a sequence exists. * @param sequenceName The sequence to check * @return The SQL to get the name of the sequence back from the databases data dictionary */ public String getSQLSequenceExists(String sequenceName) { return "SELECT * FROM USER_SEQUENCES WHERE SEQUENCE_NAME = '"+sequenceName.toUpperCase()+"'"; } /** * Get the current value of a database sequence * @param sequenceName The sequence to check * @return The current value of a database sequence */ public String getSQLCurrentSequenceValue(String sequenceName) { return "SELECT "+sequenceName+".currval FROM DUAL"; } /** * Get the SQL to get the next value of a sequence. (Oracle only) * @param sequenceName The sequence name * @return the SQL to get the next value of a sequence. (Oracle only) */ public String getSQLNextSequenceValue(String sequenceName) { return "SELECT "+sequenceName+".nextval FROM dual"; } /** * @return true if we need to supply the schema-name to getTables in order to get a correct list of items. */ public boolean useSchemaNameForTableList() { return true; } /** * @return true if the database supports synonyms */ public boolean supportsSynonyms() { return true; } /** * Generates the SQL statement to add a column to the specified table * @param tablename The table to add * @param v The column defined as a value * @param tk the name of the technical key field * @param use_autoinc whether or not this field uses auto increment * @param pk the name of the primary key field * @param semicolon whether or not to add a semi-colon behind the statement. * @return the SQL statement to add a column to the specified table */ public String getAddColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon) { return "ALTER TABLE "+tablename+" ADD ( "+getFieldDefinition(v, tk, pk, use_autoinc, true, false)+" ) "; } /** * Generates the SQL statement to drop a column from the specified table * @param tablename The table to add * @param v The column defined as a value * @param tk the name of the technical key field * @param use_autoinc whether or not this field uses auto increment * @param pk the name of the primary key field * @param semicolon whether or not to add a semi-colon behind the statement. * @return the SQL statement to drop a column from the specified table */ public String getDropColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon) { return "ALTER TABLE "+tablename+" DROP ( "+v.getName()+" ) "+Const.CR; } /** * Generates the SQL statement to modify a column in the specified table * @param tablename The table to add * @param v The column defined as a value * @param tk the name of the technical key field * @param use_autoinc whether or not this field uses auto increment * @param pk the name of the primary key field * @param semicolon whether or not to add a semi-colon behind the statement. * @return the SQL statement to modify a column in the specified table */ public String getModifyColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon) { ValueMetaInterface tmpColumn = v.clone(); int threeoh = v.getName().length()>=30 ? 30 : v.getName().length(); tmpColumn.setName(v.getName().substring(0,threeoh)+"_KTL"); // should always be less then 35 String sql=""; // Create a new tmp column sql+=getAddColumnStatement(tablename, tmpColumn, tk, use_autoinc, pk, semicolon)+";"+Const.CR; // copy the old data over to the tmp column sql+="UPDATE "+tablename+" SET "+tmpColumn.getName()+"="+v.getName()+";"+Const.CR; // drop the old column sql+=getDropColumnStatement(tablename, v, tk, use_autoinc, pk, semicolon)+";"+Const.CR; // create the wanted column sql+=getAddColumnStatement(tablename, v, tk, use_autoinc, pk, semicolon)+";"+Const.CR; // copy the data from the tmp column to the wanted column (again) // All this to avoid the rename clause as this is not supported on all Oracle versions sql+="UPDATE "+tablename+" SET "+v.getName()+"="+tmpColumn.getName()+";"+Const.CR; // drop the temp column sql+=getDropColumnStatement(tablename, tmpColumn, tk, use_autoinc, pk, semicolon); return sql; } public String getFieldDefinition(ValueMetaInterface v, String tk, String pk, boolean use_autoinc, boolean add_fieldname, boolean add_cr) { StringBuffer retval=new StringBuffer(128); String fieldname = v.getName(); int length = v.getLength(); int precision = v.getPrecision(); if (add_fieldname) retval.append(fieldname).append(' '); int type = v.getType(); switch(type) { case ValueMetaInterface.TYPE_DATE : retval.append("DATE"); break; case ValueMetaInterface.TYPE_BOOLEAN: retval.append("CHAR(1)"); break; case ValueMetaInterface.TYPE_NUMBER : case ValueMetaInterface.TYPE_BIGNUMBER: retval.append("NUMBER"); if (length>0) { retval.append('(').append(length); if (precision>0) { retval.append(", ").append(precision); } retval.append(')'); } break; case ValueMetaInterface.TYPE_INTEGER: retval.append("INTEGER"); break; case ValueMetaInterface.TYPE_STRING: if (length>=DatabaseMeta.CLOB_LENGTH) { retval.append("CLOB"); } else { if (length>0 && length<=2000) { retval.append("VARCHAR2(").append(length).append(')'); } else { if (length<=0) { retval.append("VARCHAR2(2000)"); // We don't know, so we just use the maximum... } else { retval.append("CLOB"); } } } break; case ValueMetaInterface.TYPE_BINARY: // the BLOB can contain binary data. { retval.append("BLOB"); } break; default: retval.append(" UNKNOWN"); break; } if (add_cr) retval.append(Const.CR); return retval.toString(); } /* (non-Javadoc) * @see com.ibridge.kettle.core.database.DatabaseInterface#getReservedWords() */ public String[] getReservedWords() { return new String[] { "ACCESS", "ADD", "ALL", "ALTER", "AND", "ANY", "ARRAYLEN", "AS", "ASC", "AUDIT", "BETWEEN", "BY", "CHAR", "CHECK", "CLUSTER", "COLUMN", "COMMENT", "COMPRESS", "CONNECT", "CREATE", "CURRENT", "DATE", "DECIMAL", "DEFAULT", "DELETE", "DESC", "DISTINCT", "DROP", "ELSE", "EXCLUSIVE", "EXISTS", "FILE", "FLOAT", "FOR", "FROM", "GRANT", "GROUP", "HAVING", "IDENTIFIED", "IMMEDIATE", "IN", "INCREMENT", "INDEX", "INITIAL", "INSERT", "INTEGER", "INTERSECT", "INTO", "IS", "LEVEL", "LIKE", "LOCK", "LONG", "MAXEXTENTS", "MINUS", "MODE", "MODIFY", "NOAUDIT", "NOCOMPRESS", "NOT", "NOTFOUND", "NOWAIT", "NULL", "NUMBER", "OF", "OFFLINE", "ON", "ONLINE", "OPTION", "OR", "ORDER", "PCTFREE", "PRIOR", "PRIVILEGES", "PUBLIC", "RAW", "RENAME", "RESOURCE", "REVOKE", "ROW", "ROWID", "ROWLABEL", "ROWNUM", "ROWS", "SELECT", "SESSION", "SET", "SHARE", "SIZE", "SMALLINT", "SQLBUF", "START", "SUCCESSFUL", "SYNONYM", "SYSDATE", "TABLE", "THEN", "TO", "TRIGGER", "UID", "UNION", "UNIQUE", "UPDATE", "USER", "VALIDATE", "VALUES", "VARCHAR", "VARCHAR2", "VIEW", "WHENEVER", "WHERE", "WITH" }; } /** * @return The SQL on this database to get a list of stored procedures. */ public String getSQLListOfProcedures() { return "SELECT DISTINCT DECODE(package_name, NULL, '', package_name||'.')||object_name FROM user_arguments"; } public String getSQLLockTables(String tableNames[]) { StringBuffer sql=new StringBuffer(128); for (int i=0;i<tableNames.length;i++) { sql.append("LOCK TABLE ").append(tableNames[i]).append(" IN EXCLUSIVE MODE;").append(Const.CR); } return sql.toString(); } public String getSQLUnlockTables(String tableNames[]) { return null; // commit handles the unlocking! } /** * @return extra help text on the supported options on the selected database platform. */ public String getExtraOptionsHelpText() { return "http://www.oracle.com/technology/tech/java/sqlj_jdbc/htdocs/jdbc_faq.htm#05_00"; } public String[] getUsedLibraries() { return new String[] { "ojdbc14.jar", "orai18n.jar" }; } }
package org.usfirst.frc.team2471.robot.subsystems; import org.usfirst.frc.team2471.robot.RobotMap; import org.usfirst.frc.team2471.robot.commands.DriveLoop; import edu.wpi.first.wpilibj.CANTalon; import edu.wpi.first.wpilibj.PIDController; import edu.wpi.first.wpilibj.PIDSource; import edu.wpi.first.wpilibj.PIDOutput; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class Drive extends Subsystem{ public static CANTalon lDrive1; public static CANTalon lDriveMiddle; public static CANTalon lDrive2; public static CANTalon rDrive1; public static CANTalon rDriveMiddle; public static CANTalon rDrive2; public static Solenoid shifter; public static Solenoid lPTO; public static Solenoid rPTO; public static int gearAP; boolean bSpeedControl = SmartDashboard.getBoolean("Speed Control", true); // should read from prefs and save to prefs on disabled, find TMMSmartDashboard from 2015 Robot code. WCDLeftPIDOutput wcdLeftPIDOutput; WCDRightPIDOutput wcdRightPIDOutput; public double requestedPowerLeft, requestedPowerRight; public PIDController leftController, rightController; class WCDLeftPIDSource implements PIDSource { public double pidGet(){ return RobotMap.leftE.getRate(); } } class WCDRightPIDSource implements PIDSource { public double pidGet(){ return RobotMap.rightE.getRate(); } } class WCDLeftPIDOutput implements PIDOutput { public double prevScale = 1.0; public void pidWrite(double output){ output *= Math.signum( requestedPowerLeft ); prevScale += output; if(prevScale >=10.0 ){ prevScale = 10.0; } else if(prevScale <= 0.01){ prevScale = 0.01; } SetLeftPower( prevScale * requestedPowerLeft ); } } class WCDRightPIDOutput implements PIDOutput { public double prevScale = 1.0; public void pidWrite(double output){ output *= Math.signum( requestedPowerRight ); prevScale += output; if(prevScale >=10.0 ){ prevScale = 10.0; } else if(prevScale <= 0.01){ prevScale = 0.01; } SetRightPower( prevScale * requestedPowerRight ); } } public Drive(){ lDrive1 = RobotMap.lDrive1; lDriveMiddle = RobotMap.lDriveMiddle; lDrive2 = RobotMap.lDrive2; rDrive1 = RobotMap.rDrive1; rDriveMiddle = RobotMap.rDriveMiddle; rDrive2 = RobotMap.rDrive2; lPTO = RobotMap.lPTO; rPTO = RobotMap.rPTO; shifter = RobotMap.shifter; gearAP = RobotMap.gear; wcdLeftPIDOutput = new WCDLeftPIDOutput(); wcdRightPIDOutput = new WCDRightPIDOutput(); leftController = new PIDController( 0.01, 0.0, 0.03, new WCDLeftPIDSource(), wcdLeftPIDOutput); rightController = new PIDController( 0.01, 0.0, 0.03, new WCDRightPIDSource(), wcdRightPIDOutput); SmartDashboard.putData("PID Left: ", leftController); SmartDashboard.putData("PID Right: ", rightController); SmartDashboard.putBoolean("Speed Control", bSpeedControl); } public void onDisabled(){ wcdLeftPIDOutput.prevScale = 1.0; wcdRightPIDOutput.prevScale = 1.0; } @Override protected void initDefaultCommand() { // TODO Auto-generated method stub setDefaultCommand(new DriveLoop()); } public void driveplz(double x, double y){ SmartDashboard.putNumber("Left Encoder: ", RobotMap.leftE.getRate()); SmartDashboard.putNumber("Right Encoder: ", RobotMap.rightE.getRate()); double deadband = 0.05; if (x <= deadband && x >= -deadband){ x = 0; } if(y <= deadband && y >= -deadband){ y = 0; } double speed = Math.abs(RobotMap.leftE.getRate() + RobotMap.rightE.getRate())/2.0; if (gearAP == 0 && speed>8.0){ // feet per second gearAP++; shifter.set(true); } else if(gearAP == 1 && speed<7.0){ gearAP shifter.set(false); } //RobotMap.ftop.set( RobotMap.leftE.getRate() / 240.0 ); System.out.println("Encoder: "+ RobotMap.leftE.getRate()); if (gearAP == 0) SetSpeed(0.75*x, y); // diminish turning speed else SetSpeed(1*x, y); // diminish turning speed } void SetLeftPower( double power ) { lDrive1.set(power); lDriveMiddle.set(power); lDrive2.set(power); } void SetRightPower( double power ) { rDrive1.set(-power); rDriveMiddle.set(-power); rDrive2.set(-power); } private void SetSpeed(double right, double forward){ bSpeedControl = SmartDashboard.getBoolean("Speed Control", true); if (bSpeedControl) { leftController.enable(); rightController.enable(); } else { leftController.disable(); rightController.disable(); } if (bSpeedControl) { double a = forward + right; double b = forward - right; double maxPower = Math.max( Math.abs(a) , Math.abs(b) ); if (maxPower > 1.0){ a /= maxPower; b /= maxPower; } if (a==0) { wcdLeftPIDOutput.prevScale = 1.0; } if (b==0) { wcdRightPIDOutput.prevScale = 1.0; } requestedPowerLeft = a; requestedPowerRight = b; leftController.setSetpoint( 20.0 * a ); rightController.setSetpoint( 20.0 * b ); } else { SetLeftPower( forward + right ); SetRightPower( forward - right ); } } }
package com.github.thetric.iliasdownloader.ui.common.prefs; import lombok.Data; import java.util.HashSet; import java.util.Set; /** * @author broj * @since 16.01.2017 */ @Data public final class UserPreferences { private String iliasServerURL; private String userName; private long maxFileSize; private Set<Long> activeCourses = new HashSet<>(); }
package org.opens.tgol.orchestrator; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Future; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.log4j.Logger; import org.opens.tanaguru.entity.audit.Audit; import org.opens.tanaguru.entity.audit.AuditStatus; import org.opens.tanaguru.entity.parameterization.Parameter; import org.opens.tanaguru.service.AuditService; import org.opens.tanaguru.service.AuditServiceListener; import org.opens.tgol.emailsender.EmailSender; import org.opens.tgol.entity.contract.*; import org.opens.tgol.entity.factory.contract.ActFactory; import org.opens.tgol.entity.scenario.Scenario; import org.opens.tgol.entity.service.contract.ActDataService; import org.opens.tgol.entity.service.contract.ScopeDataService; import org.opens.tgol.entity.service.scenario.ScenarioDataService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; /** * * @author jkowalczyk */ public class TanaguruOrchestratorImpl implements TanaguruOrchestrator { private static final Logger LOGGER = Logger.getLogger(TanaguruOrchestratorImpl.class); private AuditService auditService; private ActDataService actDataService; private ScenarioDataService scenarioDataService; private ActFactory actFactory; private ThreadPoolTaskExecutor threadPoolTaskExecutor; private Map<ScopeEnum, Scope> scopeMap = new EnumMap<ScopeEnum, Scope>(ScopeEnum.class); private void initializeScopeMap(ScopeDataService ScopeDataService) { for (Scope scope : ScopeDataService.findAll()) { scopeMap.put(scope.getCode(), scope); } } private EmailSender emailSender; /* * keys to send the user an email at the end of an audit. */ private static final String RECIPIENT_KEY = "recipient"; private static final String SUCCESS_SUBJECT_KEY = "success-subject"; private static final String ERROR_SUBJECT_KEY = "error-subject"; private static final String URL_TO_REPLACE = "#webresourceUrl"; private static final String PROJECT_NAME_TO_REPLACE = "#projectName"; private static final String PROJECT_URL_TO_REPLACE = "#projectUrl"; private static final String SUCCESS_MSG_CONTENT_KEY = "success-content"; private static final String SITE_ERROR_MSG_CONTENT_KEY = "site-error-content"; private static final String PAGE_ERROR_MSG_CONTENT_KEY = "page-error-content"; private static final String BUNDLE_NAME = "email-content-I18N"; private static final int DEFAULT_AUDIT_DELAY = 30000; private String webappUrl; public String getWebappUrl() { return webappUrl; } public void setWebappUrl(String webappUrl) { this.webappUrl = webappUrl; } private String siteResultUrlSuffix; public String getSiteResultUrlSuffix() { return siteResultUrlSuffix; } public void setSiteResultUrlSuffix(String siteResultUrlSuffix) { this.siteResultUrlSuffix = siteResultUrlSuffix; } private String scenarioResultUrlSuffix; public String getScenarioResultUrlSuffix() { return scenarioResultUrlSuffix; } public void setScenarioResultUrlSuffix(String scenarioResultUrlSuffix) { this.scenarioResultUrlSuffix = scenarioResultUrlSuffix; } private String pageResultUrlSuffix; public String getPageResultUrlSuffix() { return pageResultUrlSuffix; } public void setPageResultUrlSuffix(String pageResultUrlSuffix) { this.pageResultUrlSuffix = pageResultUrlSuffix; } private String groupResultUrlSuffix; public String getGroupResultUrlSuffix() { return groupResultUrlSuffix; } public void setGroupResultUrlSuffix(String groupResultUrlSuffix) { this.groupResultUrlSuffix = groupResultUrlSuffix; } private String contractUrlSuffix; public String getContractUrlSuffix() { return contractUrlSuffix; } public void setContractUrlSuffix(String contractUrlSuffix) { this.contractUrlSuffix = contractUrlSuffix; } private int delay = DEFAULT_AUDIT_DELAY; public int getDelay() { return delay; } public void setDelay(int delay) { this.delay = delay; } private List<String> emailSentToUserExclusionList = new ArrayList<String>(); public void setEmailSentToUserExclusionRawList(String emailSentToUserExclusionRawList) { this.emailSentToUserExclusionList.addAll(Arrays.asList(emailSentToUserExclusionRawList.split(";"))); } // public TanaguruOrchestratorImpl(BlockingQueue workQueue) { // threadPoolTaskExecutor = new ThreadPoolExecutor( // 10, 100, 300L, TimeUnit.SECONDS, workQueue); // public TanaguruOrchestratorImpl(int corePoolSize, // int maximumPoolSize, // long keepAliveTime, // BlockingQueue workQueue) { // threadPoolTaskExecutor = new ThreadPoolExecutor( // corePoolSize, maximumPoolSize, // keepAliveTime, TimeUnit.SECONDS, workQueue); @Autowired public TanaguruOrchestratorImpl( AuditService auditService, ActDataService actDataService, ActFactory actFactory, ScopeDataService scopeDataService, ScenarioDataService scenarioDataService, ThreadPoolTaskExecutor threadPoolTaskExecutor, EmailSender emailSender) { this.auditService = auditService; this.actDataService = actDataService; this.actFactory = actFactory; this.scenarioDataService = scenarioDataService; initializeScopeMap(scopeDataService); this.threadPoolTaskExecutor = threadPoolTaskExecutor; this.emailSender = emailSender; } @Override public Audit auditPage( Contract contract, String pageUrl, String clientIp, Set<Parameter> parameterSet, Locale locale) { LOGGER.info("auditPage "); if (LOGGER.isDebugEnabled()) { LOGGER.debug("pageUrl " + pageUrl); for (Parameter param : parameterSet) { LOGGER.debug("param " + param.getValue() + " "+ param.getParameterElement().getParameterElementCode()); } } Act act = createAct(contract, ScopeEnum.PAGE, clientIp); AuditTimeoutThread auditPageThread = new AuditPageThread( pageUrl, auditService, act, parameterSet, locale, delay); Audit audit = submitAuditAndLaunch(auditPageThread, act); return audit; } @Override public Audit auditPageUpload( Contract contract, Map<String, String> fileMap, String clientIp, Set<Parameter> parameterSet, Locale locale) { LOGGER.info("auditPage Upload"); if (LOGGER.isDebugEnabled()) { for (Parameter param : parameterSet) { LOGGER.debug("param " + param.getValue() + " "+ param.getParameterElement().getParameterElementCode()); } } Act act; if (fileMap.size()>1) { act = createAct(contract, ScopeEnum.GROUPOFFILES, clientIp); } else { act = createAct(contract, ScopeEnum.FILE, clientIp); } AuditTimeoutThread auditPageUploadThread = new AuditPageUploadThread( fileMap, auditService, act, parameterSet, locale, delay); Audit audit = submitAuditAndLaunch(auditPageUploadThread, act); return audit; } @Override public void auditSite( Contract contract, String siteUrl, String clientIp, Set<Parameter> parameterSet, Locale locale) { LOGGER.info("auditSite"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("siteUrl " + siteUrl); for (Parameter param : parameterSet) { LOGGER.debug("param " + param.getValue() + " "+ param.getParameterElement().getParameterElementCode()); } } Act act = createAct(contract, ScopeEnum.DOMAIN, clientIp); AuditThread auditSiteThread = new AuditSiteThread( siteUrl, auditService, act, parameterSet, locale); threadPoolTaskExecutor.submit(auditSiteThread); } @Override public void auditScenario( Contract contract, Long idScenario, String clientIp, Set<Parameter> parameterSet, Locale locale) { LOGGER.info("auditScenario"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Scenario id " + idScenario); for (Parameter param : parameterSet) { LOGGER.debug("param " + param.getValue() + " "+ param.getParameterElement().getParameterElementCode()); } } Act act = createAct(contract, ScopeEnum.SCENARIO, clientIp); Scenario scenario = scenarioDataService.read(idScenario); AuditThread auditScenarioThread = new AuditScenarioThread( scenario.getLabel(), scenario.getContent(), auditService, act, parameterSet, locale); threadPoolTaskExecutor.submit(auditScenarioThread); } @Override public Audit auditSite( Contract contract, String siteUrl, final List<String> pageUrlList, String clientIp, Set<Parameter> parameterSet, Locale locale) { LOGGER.info("auditGroupOfPages"); if (LOGGER.isDebugEnabled()) { for (String str :pageUrlList) { LOGGER.debug("pageUrl " + str); } for (Parameter param : parameterSet) { LOGGER.debug("param " + param.getValue() + " "+ param.getParameterElement().getParameterElementCode()); } } Act act = createAct(contract, ScopeEnum.GROUPOFPAGES, clientIp); AuditTimeoutThread auditPageThread = new AuditGroupOfPagesThread( siteUrl, pageUrlList, auditService, act, parameterSet, locale, delay); Audit audit = submitAuditAndLaunch(auditPageThread, act); return audit; } /** * * @param auditTimeoutThread * @param act * @return */ private Audit submitAuditAndLaunch(AuditTimeoutThread auditTimeoutThread, Act act) { synchronized (auditTimeoutThread) { Future submitedThread = threadPoolTaskExecutor.submit(auditTimeoutThread); while (submitedThread!=null && !submitedThread.isDone()) { try { Thread.sleep(500); } catch (InterruptedException ex) { LOGGER.error("", ex); } if (auditTimeoutThread.isDurationExceedsDelay()) { LOGGER.debug("Audit Duration ExceedsDelay. The audit result " + "is now managed in an asynchronous way."); break; } } return auditTimeoutThread.getAudit(); } } private void sendEmail(Act act, Locale locale) { String emailTo = act.getContract().getUser().getEmail1(); if (this.emailSentToUserExclusionList.contains(emailTo)) { LOGGER.debug("Email not set cause user " + emailTo + " belongs to " + "exlusion list"); return; } ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_NAME, locale); String emailFrom = bundle.getString(RECIPIENT_KEY); Set<String> emailToSet = new HashSet<String>(); emailToSet.add(emailTo); StringBuilder projectName = new StringBuilder(); projectName.append(act.getContract().getLabel()); if (act.getScope().getCode().equals(ScopeEnum.SCENARIO)) { projectName.append(" - "); // the name of the scenario is persisted on engine's side as the URL // of the parent WebResource projectName.append(act.getWebResource().getURL()); } if (act.getStatus().equals(ActStatus.COMPLETED)) { String emailSubject = bundle.getString(SUCCESS_SUBJECT_KEY).replaceAll(PROJECT_NAME_TO_REPLACE, projectName.toString()); StringBuilder emailMessage = new StringBuilder(); emailMessage.append(computeSuccessfulMessageOnActTerminated(act, bundle, projectName.toString())); emailSender.sendEmail(emailFrom, emailToSet, emailSubject, emailMessage.toString()); LOGGER.debug("success email sent to " + emailTo); } else if (act.getStatus().equals(ActStatus.ERROR)) { String emailSubject = bundle.getString(ERROR_SUBJECT_KEY).replaceAll(PROJECT_NAME_TO_REPLACE, projectName.toString()); StringBuilder emailMessage = new StringBuilder(); emailMessage.append(computeFailureMessageOnActTerminated(act, bundle, projectName.toString())); emailSender.sendEmail(emailFrom, emailToSet, emailSubject, emailMessage.toString()); LOGGER.debug("error email sent " + emailTo); } } /** * * @param act * @param bundle * @return */ private String computeSuccessfulMessageOnActTerminated(Act act, ResourceBundle bundle, String projectName) { String messageContent = bundle.getString(SUCCESS_MSG_CONTENT_KEY). replaceAll(URL_TO_REPLACE, buildResultUrl(act)); return messageContent.replaceAll(PROJECT_NAME_TO_REPLACE, projectName); } /** * * @param act * @param bundle * @return */ private String computeFailureMessageOnActTerminated(Act act, ResourceBundle bundle, String projectName) { String messageContent; if (act.getScope().getCode().equals(ScopeEnum.DOMAIN)) { messageContent = bundle.getString(SITE_ERROR_MSG_CONTENT_KEY); } else { messageContent = bundle.getString(PAGE_ERROR_MSG_CONTENT_KEY); } messageContent = messageContent.replaceAll(PROJECT_URL_TO_REPLACE, buildContractUrl(act.getContract())); messageContent = messageContent.replaceAll(URL_TO_REPLACE, buildResultUrl(act)); return messageContent.replaceAll(PROJECT_NAME_TO_REPLACE, projectName); } /** * * @param act * @return */ private String buildResultUrl (Act act) { StringBuilder strb = new StringBuilder(); strb.append(webappUrl); ScopeEnum scope = act.getScope().getCode(); if (scope.equals(ScopeEnum.DOMAIN)) { strb.append(siteResultUrlSuffix); } else if (scope.equals(ScopeEnum.GROUPOFPAGES) || scope.equals(ScopeEnum.GROUPOFFILES)) { strb.append(groupResultUrlSuffix); } else if (scope.equals(ScopeEnum.FILE) || scope.equals(ScopeEnum.PAGE)) { strb.append(pageResultUrlSuffix); } else if (scope.equals(ScopeEnum.SCENARIO)) { strb.append(scenarioResultUrlSuffix); } strb.append(act.getWebResource().getId()); return strb.toString(); } /** * * @param act * @return */ private String buildContractUrl (Contract contract) { StringBuilder strb = new StringBuilder(); strb.append(webappUrl); strb.append(contractUrlSuffix); strb.append(contract.getId()); return strb.toString(); } /** * This method initializes an act instance and persists it. * @param contract * @param scope * @return */ private Act createAct(Contract contract, ScopeEnum scope, String clientIp) { Date beginDate = new Date(); Act act = actFactory.createAct(beginDate, contract); act.setStatus(ActStatus.RUNNING); act.setScope(scopeMap.get(scope)); act.setClientIp(clientIp); actDataService.saveOrUpdate(act); return act; } private abstract class AuditThread implements Runnable, AuditServiceListener { private AuditService auditService; public AuditService getAuditService() { return auditService; } public void setAuditService(AuditService auditService) { this.auditService = auditService; } private Set<Parameter> parameterSet = new HashSet<Parameter>(); public Set<Parameter> getParameterSet() { return parameterSet; } public void setParameterSet(Set<Parameter> parameterSet) { this.parameterSet = parameterSet; } private Act currentAct; public Act getCurrentAct() { return currentAct; } public void setCurrentAct(Act currentAct) { this.currentAct = currentAct; } private Map<Audit, Long> auditExecutionList = new ConcurrentHashMap<Audit, Long>(); public Map<Audit, Long> getAuditExecutionList() { return auditExecutionList; } public void setAuditExecutionList(Map<Audit, Long> auditExecutionList) { this.auditExecutionList = auditExecutionList; } private Map<Long, Audit> auditCompletedList = new ConcurrentHashMap<Long, Audit>(); public Map<Long, Audit> getAuditCompletedList() { return auditCompletedList; } public void setAuditCompletedList(Map<Long, Audit> auditCompletedList) { this.auditCompletedList = auditCompletedList; } private Map<Long, AbstractMap.SimpleImmutableEntry<Audit, Exception>> auditCrashedList = new HashMap<Long, AbstractMap.SimpleImmutableEntry<Audit, Exception>>(); public Map<Long, SimpleImmutableEntry<Audit, Exception>> getAuditCrashedList() { return auditCrashedList; } public void setAuditCrashedList(Map<Long, SimpleImmutableEntry<Audit, Exception>> auditCrashedList) { this.auditCrashedList = auditCrashedList; } private Date startDate; public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } private Audit audit = null; public Audit getAudit() { return audit; } public void setAudit(Audit audit) { this.audit = audit; } private Locale locale = null; public Locale getLocale() { return locale; } public void setLocale(Locale locale) { this.locale = locale; } public AuditThread( AuditService auditService, Act act, Set<Parameter> parameterSet, Locale locale) { if (parameterSet != null) { this.parameterSet.addAll(parameterSet); } this.auditService = auditService; this.currentAct = act; this.locale = locale; startDate = act.getBeginDate(); } @Override public void run() { this.getAuditService().add(this); Audit currentAudit = launchAudit(); currentAudit = this.waitForAuditToComplete(currentAudit); this.getAuditService().remove(this); this.getCurrentAct().setWebResource(currentAudit.getSubject()); onActTerminated(this.getCurrentAct(), currentAudit); } /** * * @return */ public abstract Audit launchAudit(); @Override public void auditCompleted(Audit audit) { LOGGER.debug("AUDIT COMPLETED:" + audit + "," + audit.getSubject().getURL() + "," + (long) (audit.getDateOfCreation().getTime() / 1000) + audit.getId()); Audit auditCompleted = null; for (Audit auditRunning : this.auditExecutionList.keySet()) { if (auditRunning.getId().equals(audit.getId()) && (long) (auditRunning.getDateOfCreation().getTime() / 1000) == (long) (audit.getDateOfCreation().getTime() / 1000)) { auditCompleted = auditRunning; break; } } if (auditCompleted != null) { Long token = this.auditExecutionList.get(auditCompleted); this.auditExecutionList.remove(auditCompleted); this.auditCompletedList.put(token, audit); } } @Override public void auditCrashed(Audit audit, Exception exception) { LOGGER.error("AUDIT CRASHED:" + audit + "," + audit.getSubject().getURL() + "," + (long) (audit.getDateOfCreation().getTime() / 1000), exception); Audit auditCrashed = null; for (Audit auditRunning : this.auditExecutionList.keySet()) { if (auditRunning.getId().equals(audit.getId()) && (long) (auditRunning.getDateOfCreation().getTime() / 1000) == (long) (audit.getDateOfCreation().getTime() / 1000)) { auditCrashed = auditRunning; break; } } if (auditCrashed != null) { Long token = this.auditExecutionList.get(auditCrashed); this.auditExecutionList.remove(auditCrashed); this.auditCrashedList.put(token, new AbstractMap.SimpleImmutableEntry<Audit, Exception>(audit, exception)); } } protected Audit waitForAuditToComplete(Audit audit) { LOGGER.debug("WAIT FOR AUDIT TO COMPLETE:" + audit + "," + (long) (audit.getDateOfCreation().getTime() / 1000)); Long token = new Date().getTime(); this.getAuditExecutionList().put(audit, token); // while the audit is not seen as completed or crashed while (!this.getAuditCompletedList().containsKey(token) && !this.getAuditCrashedList().containsKey(token)) { try { Thread.sleep(500); } catch (InterruptedException ex) { LOGGER.error("", ex); } } if ((audit = this.getAuditCompletedList().get(token)) != null) { this.getAuditCompletedList().remove(token); return audit; } auditCrashed(this.getAuditCrashedList().get(token).getKey(), this.getAuditCrashedList().get(token).getValue()); return null; } protected void onActTerminated(Act act, Audit audit) { LOGGER.debug("act is terminated"); this.audit = audit; Date endDate = new Date(); act.setEndDate(endDate); if (audit.getStatus().equals(AuditStatus.COMPLETED)) { act.setStatus(ActStatus.COMPLETED); } else { act.setStatus(ActStatus.ERROR); } actDataService.saveOrUpdate(act); } } /** * Inner class in charge of launching a site audit in a thread. At the end * the audit, an email has to be sent to the user with the audit info. */ private class AuditSiteThread extends AuditThread { private String siteUrl; public AuditSiteThread( String siteUrl, AuditService auditService, Act act, Set<Parameter> parameterSet, Locale locale) { super(auditService, act, parameterSet, locale); this.siteUrl = siteUrl; } @Override public Audit launchAudit() { Audit audit = this.getAuditService().auditSite( this.siteUrl, this.getParameterSet()); return audit; } @Override protected void onActTerminated(Act act, Audit audit) { super.onActTerminated(act, audit); sendEmail(act, getLocale()); LOGGER.info("site audit terminated"); } } /** * Inner class in charge of launching a site audit in a thread. At the end * the audit, an email has to be sent to the user with the audit info. */ private class AuditScenarioThread extends AuditThread { private String scenarioName; private String scenario; public AuditScenarioThread( String scenarioName, String scenario, AuditService auditService, Act act, Set<Parameter> parameterSet, Locale locale) { super(auditService, act, parameterSet, locale); this.scenario = scenario; this.scenarioName = scenarioName; } @Override public Audit launchAudit() { Audit audit = this.getAuditService().auditScenario( this.scenarioName, this.scenario, this.getParameterSet()); return audit; } @Override protected void onActTerminated(Act act, Audit audit) { super.onActTerminated(act, audit); sendEmail(act, getLocale()); LOGGER.info("scenario audit terminated"); } } /** * Abstract Inner class in charge of launching an audit in a thread. This * thread has to expose the current audit as an attribute. If the * audit is not terminated in a given delay, this attribute returns null and * an email has to be sent to inform the user. */ private abstract class AuditTimeoutThread extends AuditThread { private boolean isAuditTerminatedAfterTimeout = false; public boolean isAuditTerminatedAfterTimeout() { return isAuditTerminatedAfterTimeout; } public void setAuditTerminatedAfterTimeout(boolean isAuditTerminatedBeforeTimeout) { this.isAuditTerminatedAfterTimeout = isAuditTerminatedBeforeTimeout; } private int delay = DEFAULT_AUDIT_DELAY; public AuditTimeoutThread ( AuditService auditService, Act act, Set<Parameter> parameterSet, Locale locale, int delay) { super(auditService, act, parameterSet, locale); this.delay = delay; } @Override protected void onActTerminated(Act act, Audit audit) { super.onActTerminated(act, audit); if (isAuditTerminatedAfterTimeout()) { sendEmail(act, getLocale()); } } public boolean isDurationExceedsDelay() { long currentDuration = new Date().getTime() - getStartDate().getTime(); if (currentDuration > delay) { LOGGER.debug("Audit Duration has exceeded synchronous delay " + delay); isAuditTerminatedAfterTimeout = true; return true; } return false; } } private class AuditGroupOfPagesThread extends AuditTimeoutThread { private String siteUrl; private List<String> pageUrlList = new ArrayList<String>(); public AuditGroupOfPagesThread( String siteUrl, List<String> pageUrlList, AuditService auditService, Act act, Set<Parameter> parameterSet, Locale locale, int delay) { super(auditService, act, parameterSet, locale, delay); this.siteUrl = siteUrl; if (pageUrlList != null) { this.pageUrlList.addAll(pageUrlList); } } @Override public Audit launchAudit() { Audit audit = null; if (CollectionUtils.isNotEmpty(this.pageUrlList)) { audit = this.getAuditService().auditSite( this.siteUrl, this.pageUrlList, this.getParameterSet()); } return audit; } } /** * Inner class in charge of launching a page audit in a thread. */ private class AuditPageThread extends AuditTimeoutThread { private String pageUrl; public AuditPageThread( String pageUrl, AuditService auditService, Act act, Set<Parameter> parameterSet, Locale locale, int delay) { super(auditService, act, parameterSet, locale, delay); this.pageUrl = pageUrl; LOGGER.info("auditPage " + pageUrl); } @Override public Audit launchAudit() { Audit audit = null; if (this.pageUrl != null) { audit = this.getAuditService().auditPage( this.pageUrl, this.getParameterSet()); } return audit; } } /** * Inner class in charge of launching a upload pages audit in a thread. */ private class AuditPageUploadThread extends AuditTimeoutThread { Map<String, String> pageMap = new HashMap<String, String>(); public AuditPageUploadThread( Map<String, String> pageMap, AuditService auditService, Act act, Set<Parameter> parameterSet, Locale locale, int delay) { super(auditService, act, parameterSet, locale, delay); if (pageMap != null) { this.pageMap.putAll(pageMap); } } @Override public Audit launchAudit() { Audit audit = null; if (MapUtils.isNotEmpty(pageMap)) { audit = this.getAuditService().auditPageUpload( this.pageMap, this.getParameterSet()); } return audit; } } }
package org.devgateway.ocds.web.rest.controller; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import io.swagger.annotations.ApiOperation; import org.devgateway.ocds.persistence.mongo.Award; import org.devgateway.ocds.persistence.mongo.Tender; import org.devgateway.ocds.web.rest.controller.request.GroupingFilterPagingRequest; import org.devgateway.ocds.web.rest.controller.request.YearFilterPagingRequest; import org.devgateway.toolkit.persistence.mongo.aggregate.CustomGroupingOperation; import org.devgateway.toolkit.persistence.mongo.aggregate.CustomProjectionOperation; import org.devgateway.toolkit.persistence.mongo.aggregate.CustomUnwindOperation; import org.devgateway.toolkit.web.spring.AsyncControllerLookupService; import org.devgateway.toolkit.web.spring.util.AsyncBeanParamControllerMethodCallable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.mongodb.core.aggregation.Aggregation; import org.springframework.data.mongodb.core.aggregation.AggregationResults; import org.springframework.data.mongodb.core.aggregation.Fields; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import static org.springframework.data.mongodb.core.aggregation.Aggregation.limit; import static org.springframework.data.mongodb.core.aggregation.Aggregation.match; import static org.springframework.data.mongodb.core.aggregation.Aggregation.project; import static org.springframework.data.mongodb.core.aggregation.Aggregation.skip; import static org.springframework.data.mongodb.core.aggregation.Aggregation.unwind; import static org.springframework.data.mongodb.core.query.Criteria.where; /** * * @author mpostelnicu * */ @RestController @CacheConfig(keyGenerator = "genericPagingRequestKeyGenerator", cacheNames = "genericPagingRequestJson") @Cacheable public class CostEffectivenessVisualsController extends GenericOCDSController { public static final BigDecimal ONE_HUNDRED = new BigDecimal(100); @Autowired private AsyncControllerLookupService controllerLookupService; public static final class Keys { public static final String TOTAL_AWARD_AMOUNT = "totalAwardAmount"; public static final String YEAR = "year"; public static final String TOTAL_AWARDS = "totalAwards"; public static final String TOTAL_AWARDS_WITH_TENDER = "totalAwardsWithTender"; public static final String PERCENTAGE_AWARDS_WITH_TENDER = "percentageAwardsWithTender"; private static final String FRACTION_AWARDS_WITH_TENDER = "fractionAwardsWithTender"; public static final String TOTAL_TENDER_AMOUNT = "totalTenderAmount"; public static final String TOTAL_TENDERS = "totalTenders"; public static final String TOTAL_TENDER_WITH_AWARDS = "totalTenderWithAwards"; public static final String PERCENTAGE_TENDERS_WITH_AWARDS = "percentageTendersWithAwards"; private static final String FRACTION_TENDERS_WITH_AWARDS = "fractionTendersWithAwards"; public static final String PERCENTAGE_AWARD_TENDER_AMOUNT = "percentageAwardTenderAmount"; public static final String PERCENTAGE_DIFF_TENDER_AMOUNT = "percentageDiffTenderAmount"; public static final String DIFF_TENDER_AWARD_AMOUNT = "diffTenderAwardAmount"; private static final String YEAR_MONTH = "year-month"; //this is for internal use public static final String MONTH = "month"; } @ApiOperation(value = "Cost effectiveness of Awards: Displays the total amount of active awards grouped by year." + "The tender entity, for each award, has to have amount value. The year is calculated from " + "tender.tenderPeriod.startDate") @RequestMapping(value = "/api/costEffectivenessAwardAmount", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") public List<DBObject> costEffectivenessAwardAmount( @ModelAttribute @Valid final YearFilterPagingRequest filter) { DBObject project = new BasicDBObject(); addYearlyMonthlyProjection(filter, project, "$tender.tenderPeriod.startDate"); project.put("awards.value.amount", 1); project.put("totalAwardsWithTender", new BasicDBObject("$cond", Arrays.asList(new BasicDBObject("$gt", Arrays.asList("$tender.tenderPeriod.startDate", null)), 1, 0))); project.put("awardsWithTenderValue", new BasicDBObject("$cond", Arrays.asList(new BasicDBObject("$gt", Arrays.asList("$tender.tenderPeriod.startDate", null)), "$awards.value.amount", 0))); Aggregation agg = Aggregation.newAggregation( match(where("awards").elemMatch(where("status").is(Award.Status.active.toString())).and("awards.date") .exists(true).and("tender.tenderPeriod.startDate").exists(true)), getMatchDefaultFilterOperation(filter), unwind("$awards"), match(where("awards.status").is(Award.Status.active.toString()).and("awards.value").exists(true). andOperator(getYearDefaultFilterCriteria(filter, "tender.tenderPeriod.startDate"))), new CustomProjectionOperation(project), getYearlyMonthlyGroupingOperation(filter) .sum("awardsWithTenderValue").as(Keys.TOTAL_AWARD_AMOUNT).count().as(Keys.TOTAL_AWARDS) .sum("totalAwardsWithTender").as(Keys.TOTAL_AWARDS_WITH_TENDER), project(Fields.UNDERSCORE_ID, Keys.TOTAL_AWARD_AMOUNT, Keys.TOTAL_AWARDS, Keys.TOTAL_AWARDS_WITH_TENDER) .and(Keys.TOTAL_AWARDS_WITH_TENDER).divide(Keys.TOTAL_AWARDS) .as(Keys.FRACTION_AWARDS_WITH_TENDER), project(Fields.UNDERSCORE_ID, Keys.TOTAL_AWARD_AMOUNT, Keys.TOTAL_AWARDS, Keys.TOTAL_AWARDS_WITH_TENDER, Keys.FRACTION_AWARDS_WITH_TENDER).and(Keys.FRACTION_AWARDS_WITH_TENDER).multiply(100) .as(Keys.PERCENTAGE_AWARDS_WITH_TENDER), transformYearlyGrouping(filter).andInclude(Keys.TOTAL_AWARD_AMOUNT, Keys.TOTAL_AWARDS, Keys.TOTAL_AWARDS_WITH_TENDER, Keys.PERCENTAGE_AWARDS_WITH_TENDER ), getSortByYearMonth(filter), skip(filter.getSkip()), limit(filter.getPageSize())); AggregationResults<DBObject> results = mongoTemplate.aggregate(agg, "release", DBObject.class); List<DBObject> tagCount = results.getMappedResults(); return tagCount; } @ApiOperation(value = "Cost effectiveness of Tenders:" + " Displays the total amount of the active tenders that have active awards, " + "grouped by year. Only tenders.status=active" + "are taken into account. The year is calculated from tenderPeriod.startDate") @RequestMapping(value = "/api/costEffectivenessTenderAmount", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") public List<DBObject> costEffectivenessTenderAmount( @ModelAttribute @Valid final GroupingFilterPagingRequest filter) { DBObject project = new BasicDBObject(); project.put("year", new BasicDBObject("$year", "$tender.tenderPeriod.startDate")); addYearlyMonthlyProjection(filter, project, "$tender.tenderPeriod.startDate"); project.put("tender.value.amount", 1); project.put(Fields.UNDERSCORE_ID, "$tender._id"); project.put("tenderWithAwards", new BasicDBObject("$cond", Arrays.asList( new BasicDBObject("$eq", Arrays.asList("$awards.status", Award.Status.active.toString())), 1, 0))); project.put("tenderWithAwardsValue", new BasicDBObject("$cond", Arrays.asList(new BasicDBObject("$eq", Arrays.asList("$awards.status", Award.Status.active.toString())), "$tender.value.amount", 0))); project.putAll(filterProjectMap); DBObject group1 = new BasicDBObject(); group1.put(Fields.UNDERSCORE_ID, Fields.UNDERSCORE_ID_REF); addYearlyMonthlyGroupingOperationFirst(filter, group1); group1.put("tenderWithAwards", new BasicDBObject("$max", "$tenderWithAwards")); group1.put("tenderWithAwardsValue", new BasicDBObject("$max", "$tenderWithAwardsValue")); group1.put("tenderAmount", new BasicDBObject("$first", "$tender.value.amount")); filterProjectMap.forEach((k, v) -> group1.put(k.replace(".", ""), new BasicDBObject("$first", "$" + k))); Aggregation agg = Aggregation.newAggregation( match(where("tender.status").is(Tender.Status.active.toString()).and("tender.tenderPeriod.startDate") .exists(true) .andOperator(getYearDefaultFilterCriteria(filter, "tender.tenderPeriod.startDate"))), getMatchDefaultFilterOperation(filter), new CustomUnwindOperation("$awards", true), new CustomProjectionOperation(project), new CustomGroupingOperation(group1), getTopXFilterOperation(filter, getYearlyMonthlyGroupingFields(filter)).sum("tenderWithAwardsValue") .as(Keys.TOTAL_TENDER_AMOUNT).count().as(Keys.TOTAL_TENDERS).sum("tenderWithAwards") .as(Keys.TOTAL_TENDER_WITH_AWARDS), project(Keys.TOTAL_TENDER_AMOUNT, Keys.TOTAL_TENDERS, Keys.TOTAL_TENDER_WITH_AWARDS) .andInclude(Fields.from(Fields.field(Fields.UNDERSCORE_ID, Fields.UNDERSCORE_ID_REF))) .and(Keys.TOTAL_TENDER_WITH_AWARDS).divide(Keys.TOTAL_TENDERS) .as(Keys.FRACTION_TENDERS_WITH_AWARDS), project(Keys.TOTAL_TENDER_AMOUNT, Keys.TOTAL_TENDERS, Keys.TOTAL_TENDER_WITH_AWARDS, Fields.UNDERSCORE_ID).and(Keys.FRACTION_TENDERS_WITH_AWARDS).multiply(100) .as(Keys.PERCENTAGE_TENDERS_WITH_AWARDS), transformYearlyGrouping(filter).andInclude(Keys.TOTAL_TENDER_AMOUNT, Keys.TOTAL_TENDERS, Keys.TOTAL_TENDER_WITH_AWARDS, Keys.PERCENTAGE_TENDERS_WITH_AWARDS), getSortByYearMonth(filter), skip(filter.getSkip()), limit(filter.getPageSize())) .withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build()); AggregationResults<DBObject> results = mongoTemplate.aggregate(agg, "release", DBObject.class); List<DBObject> tagCount = results.getMappedResults(); return tagCount; } private String getYearMonthlyKey(GroupingFilterPagingRequest filter, DBObject db) { return filter.getMonthly() ? db.get(Keys.YEAR) + "-" + db.get(Keys.MONTH) : db.get(Keys.YEAR).toString(); } @ApiOperation(value = "Aggregated version of /api/costEffectivenessTenderAmount and " + "/api/costEffectivenessAwardAmount." + "This endpoint aggregates the responses from the specified endpoints, per year. " + "Responds to the same filters.") @RequestMapping(value = "/api/costEffectivenessTenderAwardAmount", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") public List<DBObject> costEffectivenessTenderAwardAmount( @ModelAttribute @Valid final GroupingFilterPagingRequest filter) { Future<List<DBObject>> costEffectivenessAwardAmountFuture = controllerLookupService .asyncInvoke(new AsyncBeanParamControllerMethodCallable<List<DBObject>, GroupingFilterPagingRequest>() { @Override public List<DBObject> invokeControllerMethod(GroupingFilterPagingRequest filter) { return costEffectivenessAwardAmount(filter); } }, filter); Future<List<DBObject>> costEffectivenessTenderAmountFuture = controllerLookupService .asyncInvoke(new AsyncBeanParamControllerMethodCallable<List<DBObject>, GroupingFilterPagingRequest>() { @Override public List<DBObject> invokeControllerMethod(GroupingFilterPagingRequest filter) { return costEffectivenessTenderAmount(filter); } }, filter); //this is completely unnecessary since the #get methods are blocking //controllerLookupService.waitTillDone(costEffectivenessAwardAmountFuture, costEffectivenessTenderAmountFuture); LinkedHashMap<Object, DBObject> response = new LinkedHashMap<>(); try { costEffectivenessAwardAmountFuture.get() .forEach(dbobj -> response.put(getYearMonthlyKey(filter, dbobj), dbobj)); costEffectivenessTenderAmountFuture.get().forEach(dbobj -> { if (response.containsKey(getYearMonthlyKey(filter, dbobj))) { Map<?, ?> map = dbobj.toMap(); map.remove(Keys.YEAR); if (filter.getMonthly()) { map.remove(Keys.MONTH); } response.get(getYearMonthlyKey(filter, dbobj)).putAll(map); } else { response.put(getYearMonthlyKey(filter, dbobj), dbobj); } }); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } Collection<DBObject> respCollection = response.values(); respCollection.forEach(dbobj -> { dbobj.put(Keys.DIFF_TENDER_AWARD_AMOUNT, BigDecimal .valueOf(dbobj.get(Keys.TOTAL_TENDER_AMOUNT) == null ? 0d : ((Number) dbobj.get(Keys.TOTAL_TENDER_AMOUNT)).doubleValue()) .subtract(BigDecimal.valueOf(dbobj.get(Keys.TOTAL_AWARD_AMOUNT) == null ? 0d : ((Number) dbobj.get(Keys.TOTAL_AWARD_AMOUNT)).doubleValue()))); dbobj.put(Keys.PERCENTAGE_AWARD_TENDER_AMOUNT, dbobj.get(Keys.TOTAL_TENDER_AMOUNT)!=null && !dbobj.get(Keys.TOTAL_TENDER_AMOUNT).equals(BigDecimal.ZERO)? BigDecimal .valueOf(dbobj.get(Keys.TOTAL_AWARD_AMOUNT) == null ? 0d : ((Number) dbobj.get(Keys.TOTAL_AWARD_AMOUNT)).doubleValue()) .divide(BigDecimal.valueOf(dbobj.get(Keys.TOTAL_TENDER_AMOUNT) == null ? 0d : ((Number) dbobj.get(Keys.TOTAL_TENDER_AMOUNT)).doubleValue()),BigDecimal.ROUND_HALF_UP) .multiply(ONE_HUNDRED):BigDecimal.ZERO); }); return new ArrayList<>(respCollection); } }
package org.jgroups.tests; import org.jgroups.ExtendedReceiverAdapter; import org.jgroups.Global; import org.jgroups.JChannel; import org.jgroups.util.Util; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import java.util.Arrays; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * Tests concurrent FLUSH and partial FLUSHes * * @author Manik Surtani * @version $Id: ConcurrentFlushTest.java,v 1.4 2009/02/26 15:11:51 vlada Exp $ */ @Test(groups=Global.FLUSH, sequential=true) public class ConcurrentFlushTest extends ChannelTestBase { JChannel c1, c2, c3; @AfterMethod public void tearDown() throws Exception { Util.close(c1, c2, c3); } public boolean useBlocking() { return true; } /** * Tests 2 channels calling FLUSH simultaneously */ public void testConcurrentFlush() throws Exception { c1=createChannel(true, 2); c1.connect("testConcurrentFlush"); c2=createChannel(c1); c2.connect("testConcurrentFlush"); assertViewsReceived(c1, c2); final CountDownLatch startFlushLatch=new CountDownLatch(1); final CountDownLatch stopFlushLatch=new CountDownLatch(1); final CountDownLatch flushStartReceived=new CountDownLatch(2); final CountDownLatch flushStopReceived=new CountDownLatch(2); Thread t1=new Thread() { public void run() { try { startFlushLatch.await(); } catch (InterruptedException e) { interrupt(); } c1.startFlush(false); try { stopFlushLatch.await(); } catch (InterruptedException e) { interrupt(); } c1.stopFlush(); } }; Thread t2=new Thread() { public void run() { try { startFlushLatch.await(); } catch (InterruptedException e) { interrupt(); } c2.startFlush(false); try { stopFlushLatch.await(); } catch (InterruptedException e) { interrupt(); } c2.stopFlush(); } }; Listener l1=new Listener(c1, flushStartReceived, flushStopReceived); Listener l2=new Listener(c2, flushStartReceived, flushStopReceived); t1.start(); t2.start(); startFlushLatch.countDown(); assertTrue(flushStartReceived.await(60, TimeUnit.SECONDS)); // at this stage both channels should have started a flush stopFlushLatch.countDown(); assertTrue(flushStopReceived.await(60, TimeUnit.SECONDS)); assert l1.blockReceived; assert l1.unblockReceived; assert l2.blockReceived; assert l2.unblockReceived; } /** * Tests 2 channels calling partial FLUSHes and one calling FLUSH simultaneously */ public void testConcurrentFlushAndPartialFlush() throws Exception { c1=createChannel(true, 3); c1.connect("testConcurrentFlushAndPartialFlush"); c2=createChannel(c1); c2.connect("testConcurrentFlushAndPartialFlush"); c3=createChannel(c1); c3.connect("testConcurrentFlushAndPartialFlush"); assertViewsReceived(c1, c2, c3); final CountDownLatch startFlushLatch=new CountDownLatch(1); final CountDownLatch stopFlushLatch=new CountDownLatch(1); //2 because either total or partial has to finish first final CountDownLatch flushStartReceived=new CountDownLatch(2); //5 because we have total and partial flush final CountDownLatch flushStopReceived=new CountDownLatch(5); Thread t1=new Thread() { public void run() { try { startFlushLatch.await(); } catch (InterruptedException e) { interrupt(); } c1.startFlush(false); try { stopFlushLatch.await(); } catch (InterruptedException e) { interrupt(); } c1.stopFlush(); } }; Thread t2=new Thread() { public void run() { try { startFlushLatch.await(); } catch (InterruptedException e) { interrupt(); } // partial, only between c2 and c3 c2.startFlush(Arrays.asList(c2.getLocalAddress(), c3.getLocalAddress()), false); try { stopFlushLatch.await(); } catch (InterruptedException e) { interrupt(); } c2.stopFlush(Arrays.asList(c2.getLocalAddress(), c3.getLocalAddress())); } }; Listener l1=new Listener(c1, flushStartReceived, flushStopReceived); Listener l2=new Listener(c2, flushStartReceived, flushStopReceived); Listener l3=new Listener(c3, flushStartReceived, flushStopReceived); t1.start(); t2.start(); startFlushLatch.countDown(); assertTrue(flushStartReceived.await(60, TimeUnit.SECONDS)); // at this stage both channels should have started a flush? stopFlushLatch.countDown(); assertTrue(flushStopReceived.await(60, TimeUnit.SECONDS)); assertTrue(l1.blockReceived); assertTrue(l1.unblockReceived); assertTrue(l2.blockReceived); assertTrue(l2.unblockReceived); assertTrue(l3.blockReceived); assertTrue(l3.unblockReceived); } private static void assertViewsReceived(JChannel... channels) { for (JChannel c : channels) assertEquals(c.getView().getMembers().size(), channels.length); } private static class Listener extends ExtendedReceiverAdapter { boolean blockReceived, unblockReceived; JChannel channel; CountDownLatch flushStartReceived, flushStopReceived; Listener(JChannel channel, CountDownLatch flushStartReceived, CountDownLatch flushStopReceived) { this.channel=channel; this.flushStartReceived=flushStartReceived; this.flushStopReceived=flushStopReceived; this.channel.setReceiver(this); } public void unblock() { unblockReceived=true; flushStopReceived.countDown(); } public void block() { blockReceived=true; flushStartReceived.countDown(); } } }
package ed.lang.python; import static org.testng.AssertJUnit.assertEquals; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import org.testng.annotations.Test; import org.testng.annotations.BeforeClass; import org.python.core.*; import ed.js.Encoding; import ed.appserver.JSFileLibrary; import ed.appserver.templates.djang10.Printer.RedirectedPrinter; import ed.js.JSLocalFile; import ed.js.JSObjectBase; import ed.js.JSString; import ed.js.engine.Scope; import ed.js.func.JSFunctionCalls1; import ed.log.Level; import ed.log.Logger; public class PythonReloadTest extends ed.TestCase { private static final String TEST_DIR = "/tmp/"; private static final File testDir = new File(TEST_DIR); //time to wait between file modifications to allow the fs to update the timestamps private static final long SLEEP_MS = 5000; @BeforeClass public void setUp() throws IOException, InterruptedException { if(!testDir.mkdir() && !testDir.exists()) throw new IOException("Failed to create test dir"); } @Test public void test() throws IOException, InterruptedException { Scope globalScope = initScope(); RedirectedPrinter printer = new RedirectedPrinter(); globalScope.set("print", printer); globalScope.set("counter", 0); JSFileLibrary fileLib = (JSFileLibrary)globalScope.get("local"); writeTest1File1(); writeTest1File2(); writeTest1File3(); Scope oldScope = Scope.getThreadLocal(); globalScope.makeThreadLocal(); try { globalScope.eval("local.file1();"); assertRan3(globalScope); clearScope(globalScope); Thread.sleep(SLEEP_MS); writeTest1File2(); PyObject m = Py.getSystemState().__findattr__("modules"); System.out.println("Modules are: " + m.getClass() + " " + m); globalScope.eval("local.file1();"); assertRan2(globalScope); Thread.sleep(SLEEP_MS); System.out.println("New test"); clearScope(globalScope); writeTest2File2(); globalScope.eval("local.file1();"); assertRan2(globalScope); clearScope(globalScope); globalScope.eval("local.file1();"); assertRan1(globalScope); Thread.sleep(SLEEP_MS); writeTest2File2(); clearScope(globalScope); globalScope.eval("local.file1();"); assertRan2(globalScope); Thread.sleep(SLEEP_MS); writeTest3File2(); writeTest3File3(); clearScope(globalScope); globalScope.eval("local.file1();"); assertRan3(globalScope); clearScope(globalScope); globalScope.eval("local.file1();"); assertRan1(globalScope); Thread.sleep(SLEEP_MS); writeTest3File2(); writeTest3File3(); clearScope(globalScope); globalScope.eval("local.file1();"); assertRan3(globalScope); clearScope(globalScope); globalScope.eval("local.file1();"); assertRan1(globalScope); Thread.sleep(SLEEP_MS); writeTest3File3(); clearScope(globalScope); globalScope.eval("local.file1();"); assertRan3(globalScope); } finally { if(oldScope != null) oldScope.makeThreadLocal(); else Scope.clearThreadLocal(); try { //rdelete(testDir); } catch (Exception e) { } } } private static void rdelete(File f) { if(f.isDirectory()) { for(File sf : f.listFiles()) rdelete(sf); } f.delete(); } private Scope initScope() { Scope oldScope = Scope.getThreadLocal(); Scope globalScope = Scope.newGlobal().child(); globalScope.setGlobal(true); globalScope.makeThreadLocal(); try { //Load native objects Logger log = Logger.getRoot(); globalScope.set("log", log); log.makeThreadLocal(); Map<String, JSFileLibrary> rootFiles = new HashMap<String, JSFileLibrary>(); rootFiles.put("local", new JSFileLibrary(new File(TEST_DIR), "local", globalScope)); for(Map.Entry<String, JSFileLibrary> rootFileLib : rootFiles.entrySet()) globalScope.set(rootFileLib.getKey(), rootFileLib.getValue()); Encoding.install(globalScope); //JSHelper helper = JSHelper.install(globalScope, rootFiles, log); globalScope.set("SYSOUT", new JSFunctionCalls1() { public Object call(Scope scope, Object p0, Object[] extra) { System.out.println(p0); return null; } }); globalScope.put("openFile", new JSFunctionCalls1() { public Object call(Scope s, Object name, Object extra[]) { return new JSLocalFile(new File(TEST_DIR), name.toString()); } }, true); //helper.addTemplateRoot(globalScope, new JSString("/local")); } finally { if(oldScope != null) oldScope.makeThreadLocal(); else Scope.clearThreadLocal(); } return globalScope; } private void clearScope(Scope s){ s.set("ranFile1", 0); s.set("ranFile2", 0); s.set("ranFile3", 0); } // file1 -> file2 -> file3 private void writeTest1File1() throws IOException{ fillFile(1, true); } private void writeTest1File2() throws IOException{ fillFile(2, true); } private void writeTest1File3() throws IOException{ fillFile(3, false); } private void setTime(PrintWriter writer, String name){ writer.println("_10gen."+name+" = _10gen.counter; _10gen.counter += 1"); } private void fillFile(int n, boolean importNext) throws IOException{ File f = new File(testDir, "file"+n+".py"); PrintWriter writer = new PrintWriter(f); writer.println("import _10gen"); writer.println("_10gen.ranFile"+n+" = 1"); setTime(writer, "startFile1"); if(importNext) writer.println("import file"+(n+1)); setTime(writer, "endFile1"); writer.close(); } private void writeTest2File2() throws IOException{ File f = new File(testDir, "file2.py"); PrintWriter writer = new PrintWriter(f); writer.println("import _10gen"); writer.println("_10gen.ranFile2 = 1"); writer.println("import file2"); writer.close(); } private void writeTest3File2() throws IOException{ fillFile(2, true); } private void writeTest3File3() throws IOException{ File f = new File(testDir, "file3.py"); PrintWriter writer = new PrintWriter(f); writer.println("import _10gen"); writer.println("_10gen.ranFile3 = 1"); writer.println("import file2"); writer.close(); } private void assertRan1(Scope s){ assertEquals(s.get("ranFile1"), 1); assertEquals(s.get("ranFile2"), 0); assertEquals(s.get("ranFile3"), 0); } private void assertRan2(Scope s){ assertEquals(s.get("ranFile1"), 1); assertEquals(s.get("ranFile2"), 1); assertEquals(s.get("ranFile3"), 0); } private void assertRan3(Scope s){ assertEquals(s.get("ranFile1"), 1); assertEquals(s.get("ranFile2"), 1); assertEquals(s.get("ranFile3"), 1); } public static void main(String [] args){ (new PythonReloadTest()).runConsole(); } }
package ed.lang.ruby; import java.io.*; import org.jruby.*; import org.testng.annotations.Test; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import ed.appserver.JSFileLibrary; import ed.appserver.Module; import ed.js.*; import ed.js.engine.Scope; import ed.js.func.JSFunctionCalls0; import ed.lang.ruby.RubyJxpSource; public class RubyFileRunnerTest { protected static final String QA_RAILS_TEST_DIR_RELATIVE = "modules/ruby/rails"; @Test(groups = {"ruby", "ruby.testunit"}) public void testRunRubyTests() { runTestsIn(new File(System.getenv("ED_HOME"), "src/test/ed/lang/ruby")); } /** * This test runs the tests in QA_RAILS_TEST_DIR_RELATIVE, but only if * that directory exists. We look in two places: /data/qa and * $ED_HOME/../qa. * <p> * These tests require one or more copies of Rails itself, which we'd like * to keep out of the base Babble code. */ @Test(groups = {"ruby", "ruby.testunit", "ruby.activerecord"}) public void testRunRailsTests() { File dir; if ((dir = new File("/data/qa", QA_RAILS_TEST_DIR_RELATIVE)).exists() || (dir = new File(new File(System.getenv("ED_HOME"), "../qa"), QA_RAILS_TEST_DIR_RELATIVE)).exists()) runTestsIn(dir); else assertTrue(true); } protected void runTestsIn(File rootDir) { String edHome = System.getenv("ED_HOME"); File f = new File(rootDir, "run_all_tests.rb"); Scope s = createScope(f.getParentFile()); RubyJxpSource source = new RubyJxpSource(f, Ruby.newInstance()); addRubyLoadPath(s, source, new File(edHome, "build").getPath()); // for xgen.rb and files it includes addRubyLoadPath(s, source, rootDir.getPath()); try { source.getFunction().call(s, new Object[0]); } catch (Exception e) { e.printStackTrace(); fail("while running file " + f.getPath() + ", exception was thrown: " + e); } } protected Scope createScope(File localRootDir) { Scope s = Scope.newGlobal(); s = new Scope("test", s); // child of global scope Shell.addNiceShellStuff(s); s.set("local", new JSFileLibrary(localRootDir, "local", s)); s.set("rails_local", new JSFileLibrary(new File(localRootDir, "rails-test-app"), "local", s)); s.set("core", CoreJS.get().getLibrary(null, null, s, false)); s.set("jsout", ""); // initial value; used by tests; will be written over later JSFunction print = new JSFunctionCalls0() { public Object call(Scope s, Object[] args) { return s.put("jsout", s.get("jsout").toString() + args[0].toString() + "\n", false); // default print behavior adds newline } }; print.setName("print"); s.set("print", print); return s; } protected void addRubyLoadPath(Scope s, RubyJxpSource source, String path) { Ruby runtime = source.getRuntime(s); RubyString rpath = RubyString.newString(runtime, path.replace('\\', '/')); RubyArray loadPath = (RubyArray)runtime.getLoadService().getLoadPath(); if (loadPath.include_p(runtime.getCurrentContext(), rpath).isFalse()) loadPath.append(rpath); } }
/* * $Id: TestEncodedProperty.java,v 1.2 2002-10-06 21:27:16 tal Exp $ */ package org.lockss.util; import java.util.*; import java.io.*; import java.net.*; import junit.framework.TestCase; import org.lockss.test.*; /** * Test class for <code>EncodedProperty</code>. */ public class TestEncodedProperty extends LockssTestCase { public static Class testedClasses[] = { org.lockss.util.EncodedProperty.class }; private static byte testbyte = 127; private static boolean testbool = true; private static byte[] testarray = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 }; private static double testdbl = 1.0d; private static float testfloat = 1.0f; private static int testint = 1; private static long testlong = 1280000000; private static Properties p1 = new Properties(); static { p1.put("byte","127"); p1.put("boolean","true"); p1.put("bytearr", "0102030405060708090A0B0C0D0E0F"); p1.put("double","1.0d"); p1.put("float","1.0f"); p1.put("int", "1"); p1.put("long","1280000000"); }; public TestEncodedProperty(String msg) { super(msg); } public void testDefaultTransformation() { EncodedProperty props1 = new EncodedProperty(p1); EncodedProperty props2 = new EncodedProperty(); byte[] encoded = null; try { encoded = props1.encode(); } catch (IOException ex) { fail("prop encoding failed\n"); } try { props2.decode(encoded); } catch (IOException ex) { fail("prop decoding failed\n"); } assertEquals(props1,props2); } public void testTransformation() { EncodedProperty props1 = new EncodedProperty(p1); EncodedProperty props2 = new EncodedProperty(); byte[] encoded = null; try { encoded = props1.encode("UTF-16"); } catch (IOException ex) { fail("prop encoding for UTF-16 failed\n"); } try { props2.decode(encoded, "UTF-16"); } catch (IOException ex) { fail("prop decoding UTF-16 failed\n"); } assertEquals(props1,props2); } public void testBooleanData() { EncodedProperty props = new EncodedProperty(); // check request for missing type returns requested assertEquals(props.getBoolean("bool",testbool),testbool); // check request for expected item props.putBoolean("bool",testbool); assertEquals(props.getBoolean("bool",false), testbool); } public void testByteArrayData() { EncodedProperty props = new EncodedProperty(); // check request for missing type returns requested assertEquals(props.getByteArray("bytearr",testarray),testarray); // check request for expected item props.putByteArray("bytearr",testarray); assertTrue(Arrays.equals(props.getByteArray("bytearr",new byte[0]), testarray)); } public void testDoubleData() { EncodedProperty props = new EncodedProperty(); // check request for missing type returns requested assertEquals(props.getDouble("double",testdbl),testdbl,0); // check request for expected item props.putDouble("double",testdbl); assertEquals(props.getDouble("double",0.0d),testdbl,0); } public void testFloatData() { EncodedProperty props = new EncodedProperty(); // check request for missing type returns requested assertEquals(props.getFloat("float",testfloat),testfloat,0); // check request for expected item props.putFloat("float",testfloat); assertEquals(props.getFloat("float",0.0f),testfloat,0); } public void testIntData() { EncodedProperty props = new EncodedProperty(); // check request for missing type returns requested assertEquals(props.getInt("int",testint),testint); // check request for expected item props.putInt("int",testint); assertEquals(props.getInt("int",0),testint); } public void testLongData() { EncodedProperty props = new EncodedProperty(); // check request for missing type returns requested assertEquals(props.getLong("long",testlong),testlong); // check request for expected item props.putLong("long",testlong); assertEquals(props.getLong("long",0),testlong); } }
package cf; import org.junit.Assert; import org.junit.Test; public class CircumscribedCircleTest { @Test public void testCircumcircle() { CircumscribedCircle circle = new CircumscribedCircle(); int[][] triangle = new int[][] { { 3, 2 }, { 1, 4 }, { 5, 4 } }; int[] expecteds = new int[] { 3, 4, 2 }; int[] actuals = circle.circumcircle(triangle); // Assert.assertArrayEquals(expecteds, actuals); triangle = new int[][] { { 8, 6 }, { 8, -2 }, { 2, -2 } }; expecteds = new int[] { 5, 2, 5 }; actuals = circle.circumcircle(triangle); // Assert.assertArrayEquals(expecteds, actuals); triangle = new int[][] { { 5, 7 }, { 6, 6 }, { 2, -2 } }; expecteds = new int[] { 2, 3, 5 }; // Assert.assertArrayEquals(expecteds, circle.circumcircle(triangle)); triangle = new int[][] { { 3, 4 }, { 4, 5 }, { 4, 3 } }; expecteds = new int[] { 4, 4, 1 }; // Assert.assertArrayEquals(expecteds, circle.circumcircle(triangle)); triangle = new int[][] { { 3, 4 }, { 4, 5 }, { 4, 3 } }; expecteds = new int[] { 4, 4, 1 }; // Assert.assertArrayEquals(expecteds, circle.circumcircle(triangle)); triangle = new int[][] { { 2, 11 }, { 6, 7 }, { -2, 7 } }; expecteds = new int[] { 2, 7, 4 }; // Assert.assertArrayEquals(expecteds, circle.circumcircle(triangle)); triangle = new int[][] { { 5, 1 }, { -2, 0 }, { 4, 8 } }; expecteds = new int[] { 1, 4, 5 }; // Assert.assertArrayEquals(expecteds, circle.circumcircle(triangle)); triangle = new int[][] { { 1, 4 }, { -2, 3 }, { 5, 2 } }; expecteds = new int[] { 1, -1, 5 }; // Assert.assertArrayEquals(expecteds, circle.circumcircle(triangle)); } }
package guitests; import org.junit.Test; import seedu.task.model.task.ReadOnlyTask; import static org.junit.Assert.assertEquals; public class SelectCommandTest extends TaskManagerGuiTest { @Test public void selectTask_nonEmptyList() { assertSelectionInvalid(10); //invalid index assertNoTaskSelected(); assertSelectionSuccess(1); //first task in the list int taskCount = td.getTypicalTasks().length; assertSelectionSuccess(taskCount); //last task in the list int middleIndex = taskCount / 2; assertSelectionSuccess(middleIndex); //a task in the middle of the list assertSelectionInvalid(taskCount + 1); //invalid index assertTaskSelected(middleIndex); //assert previous selection remains /* Testing other invalid indexes such as -1 should be done when testing the SelectCommand */ } @Test public void selectTask_emptyList(){ commandBox.runCommand("clear"); assertSelectionInvalid(1); assertListSize(0);//invalid index } private void assertSelectionInvalid(int index) { commandBox.runCommand("select " + index); assertResultMessage("The task index provided is invalid"); } private void assertSelectionSuccess(int index) { commandBox.runCommand("select " + index); assertResultMessage("Selected Task: "+index); assertTaskSelected(index); } private void assertTaskSelected(int index) { assertEquals(taskListPanel.getSelectedTasks().size(), 1); ReadOnlyTask selectedTask = taskListPanel.getSelectedTasks().get(0); assertEquals(taskListPanel.getTask(index-1), selectedTask); } private void assertNoTaskSelected() { assertEquals(taskListPanel.getSelectedTasks().size(), 0); } }
package linenux.model; import static junit.framework.TestCase.assertEquals; import static linenux.helpers.Assert.assertNoChange; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import org.junit.Before; import org.junit.Test; /** * JUnit test for schedule. */ public class ScheduleTest { private Schedule schedule; @Before public void setupSchedule() { this.schedule = new Schedule(); } @Test public void testAddTask() { int beforeSize = this.schedule.getTaskList().size(); this.schedule.addTask(new Task("bla")); int afterSize = this.schedule.getTaskList().size(); assertEquals(beforeSize + 1, afterSize); } @Test public void testClear() { Task task1 = new Task("hello"); Task task2 = new Task("blah"); this.schedule.addTask(task1); this.schedule.addTask(task2); int originalSize = this.schedule.getTaskList().size(); this.schedule.clear(); int endSize = this.schedule.getTaskList().size(); assertEquals(originalSize - 2, endSize); } @Test public void testSearch() { String[] keywords = {"hello", "WoRlD"}; Task match1 = new Task("Say Hello"); Task match2 = new Task("Around the world"); Task mismatch = new Task("meh"); this.schedule.addTask(match1); this.schedule.addTask(mismatch); this.schedule.addTask(match2); ArrayList<Task> tasks = this.schedule.search(keywords); assertEquals(2, tasks.size()); } @Test public void testEdit() { this.schedule.clear(); Task originalTask = new Task("hello"); this.schedule.addTask(originalTask); Task editedTask = new Task("new task"); this.schedule.editTask(originalTask, editedTask); assertEquals(this.schedule.getTaskList().get(0), editedTask); } @Test public void testDelete() { Task task = new Task("bla"); this.schedule.addTask(task); int beforeSize = this.schedule.getTaskList().size(); this.schedule.deleteTask(task); int afterSize = this.schedule.getTaskList().size(); assertEquals(beforeSize - 1, afterSize); assertTrue(this.schedule.getTaskList().indexOf(task) == -1); } @Test public void testMaxStates() { for (int i = 0; i < Schedule.MAX_STATES; i++) { this.schedule.addTask(new Task("task" + Integer.toString(i))); } assertEquals(Schedule.MAX_STATES, this.schedule.getStates().size()); assertNoChange(() -> this.schedule.getStates().size(), () -> { this.schedule.addTask(new Task("Hi")); return 0; }); } }
package me.mneri.csv.test; import me.mneri.csv.CsvReader; import me.mneri.csv.CsvWriter; import me.mneri.csv.exception.CsvConversionException; import me.mneri.csv.exception.CsvException; import me.mneri.csv.exception.UncheckedCsvException; import me.mneri.csv.exception.UnexpectedCharacterException; import me.mneri.csv.test.model.Person; import me.mneri.csv.test.serialization.*; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import java.util.stream.Collectors; import java.util.stream.Stream; public class MainTest { @Test(expected = CsvConversionException.class) public void conversionException1() throws CsvException, IOException { File file = getResourceFile("simple.csv"); try (CsvReader<Void> reader = CsvReader.open(file, new ExceptionDeserializer())) { while (reader.hasNext()) { reader.next(); } } } @Test(expected = CsvConversionException.class) public void conversionException2() throws CsvException, IOException { CsvWriter<Void> writer = null; File file = null; try { file = createTempFile(); writer = CsvWriter.open(file, new ExceptionSerializer()); writer.put(null); } finally { //@formatter:off if (writer != null) { try { writer.close(); } catch (Exception ignored) { } } if (file != null) { try { file.delete(); } catch (Exception ignored) { } } //@formatter:on } } private Person createMneri() { Person mneri = new Person(); mneri.setFirstName("Massimo"); mneri.setLastName("Neri"); mneri.setNickname("\"mneri\""); mneri.setAddress("Gambettola, Italy"); mneri.setWebsite("http://mneri.me"); return mneri; } private Person createRms() { Person rms = new Person(); rms.setFirstName("Richard"); rms.setMiddleName("Matthew"); rms.setLastName("Stallman"); rms.setNickname("\"rms\""); rms.setAddress("Cambridge, Massachusetts"); rms.setWebsite("http://stallman.org/"); return rms; } private File createTempFile() throws IOException { File dir = new File(System.getProperty("java.io.tmpdir")); return File.createTempFile("junit_", ".csv", dir); } @Test(expected = NoSuchElementException.class) public void empty() throws CsvException, IOException { File file = getResourceFile("empty.csv"); try (CsvReader<Void> reader = CsvReader.open(file, new VoidDeserializer())) { reader.next(); } finally { //@formatter:off if (file != null) { try { file.delete(); } catch (Exception ignored) { } } //@formatter:on } } @Test public void flush() throws CsvException, IOException { File file = null; CsvReader<List<Integer>> reader = null; CsvWriter<List<Integer>> writer = null; try { file = createTempFile(); List<Integer> line = Arrays.asList(0, 1, 2, 3); writer = CsvWriter.open(file, new IntegerListSerializer()); writer.put(line); writer.flush(); reader = CsvReader.open(file, new IntegerListDeserializer()); Assert.assertEquals(line, reader.next()); } finally { //@formatter:off if (writer != null) { try { writer.close(); } catch (Exception ignored) { } } if (reader != null) { try { reader.close(); } catch (Exception ignored) { } } if (file != null) { try { file.delete(); } catch (Exception ignored) { } } //@formatter:on } } private File getResourceFile(String name) { ClassLoader classLoader = getClass().getClassLoader(); return new File(classLoader.getResource(name).getFile()); } @Test(expected = UnexpectedCharacterException.class) public void illegal1() throws CsvException, IOException { File file = getResourceFile("illegal.csv"); try (CsvReader<List<String>> reader = CsvReader.open(file, new StringListDeserializer())) { while (reader.hasNext()) { reader.next(); } } } @Test(expected = UnexpectedCharacterException.class) public void illegal2() throws CsvException, IOException { File file = getResourceFile("illegal.csv"); try (Stream<List<String>> stream = CsvReader.stream(file, new StringListDeserializer())) { try { //@formatter:off stream.forEach(line -> { }); //@formatter:on } catch (UncheckedCsvException e) { throw (CsvException) e.getCause(); } } } @Test(expected = IllegalStateException.class) public void readAfterClose() throws CsvException, IOException { File file = getResourceFile("simple.csv"); CsvReader<List<Integer>> reader = null; try { reader = CsvReader.open(file, new IntegerListDeserializer()); reader.close(); reader.next(); } finally { //@formatter:off if (reader != null) { try { reader.close(); } catch (Exception ignored) { } } //@formatter:on } } @Test public void shouldQuote() throws CsvException, IOException { File file = null; List<String> strings = Arrays.asList("a", "\"b\"", "", null, "c,d,e"); try { file = createTempFile(); try (CsvWriter<List<String>> writer = CsvWriter.open(file, new StringListSerializer())) { writer.put(strings); } try (CsvReader<List<String>> reader = CsvReader.open(file, new StringListDeserializer())) { Assert.assertEquals(strings, reader.next()); } } finally { //@formatter:off if (file != null) { try { file.delete(); } catch (Exception ignored) { } } //@formatter:on } } @Test public void skip1() throws CsvException, IOException { File file = getResourceFile("simple.csv"); List<Integer> expected = Arrays.asList(6, 7, 8, 9, 0); try (CsvReader<List<Integer>> reader = CsvReader.open(file, new IntegerListDeserializer())) { reader.skip(1); List<Integer> second = reader.next(); Assert.assertEquals(second, expected); } } @Test public void skip2() throws CsvException, IOException { File file = getResourceFile("simple.csv"); List<Integer> expected = Arrays.asList(6, 7, 8, 9, 0); try (CsvReader<List<Integer>> reader = CsvReader.open(file, new IntegerListDeserializer())) { if (reader.hasNext()) { reader.skip(1); } List<Integer> second = reader.next(); Assert.assertEquals(second, expected); } } @Test public void skip3() throws CsvException, IOException { File file = getResourceFile("simple.csv"); try (CsvReader<List<Integer>> reader = CsvReader.open(file, new IntegerListDeserializer())) { reader.next(); reader.skip(1); Assert.assertFalse(reader.hasNext()); } } @Test public void skip4() throws CsvException, IOException { File file = getResourceFile("simple.csv"); try (CsvReader<List<Integer>> reader = CsvReader.open(file, new IntegerListDeserializer())) { reader.skip(2); Assert.assertFalse(reader.hasNext()); } } @Test public void skip5() throws CsvException, IOException { File file = getResourceFile("simple.csv"); try (CsvReader<List<Integer>> reader = CsvReader.open(file, new IntegerListDeserializer())) { reader.skip(999); Assert.assertFalse(reader.hasNext()); } } @Test public void skip6() throws CsvException, IOException { File file = getResourceFile("simple.csv"); try (CsvReader<List<Integer>> reader = CsvReader.open(file, new IntegerListDeserializer())) { while (reader.hasNext()) { reader.next(); } reader.skip(1); Assert.assertFalse(reader.hasNext()); } } @Test(expected = UnexpectedCharacterException.class) public void skip7() throws CsvException, IOException { File file = getResourceFile("illegal.csv"); try (CsvReader<List<String>> reader = CsvReader.open(file, new StringListDeserializer())) { reader.skip(1); } } @Test public void stream1() throws CsvConversionException, IOException { File file = null; List<Person> persons = Arrays.asList(createMneri(), createRms()); try { file = createTempFile(); try (CsvWriter<Person> writer = CsvWriter.open(file, new PersonSerializer())) { writer.putAll(persons); } try (Stream<Person> stream = CsvReader.stream(file, new PersonDeserializer())) { List<Person> collected = stream.collect(Collectors.toList()); Assert.assertEquals(persons, collected); } } finally { //@formatter:off if (file != null) { try { file.delete(); } catch (Exception ignored) { } } //@formatter:on } } @Test public void stream2() throws CsvConversionException, IOException { File file = null; List<Person> persons = Arrays.asList(createMneri(), createRms()); try { file = createTempFile(); try (CsvWriter<Person> writer = CsvWriter.open(file, new PersonSerializer())) { writer.putAll(persons.stream()); } try (Stream<Person> stream = CsvReader.stream(file, new PersonDeserializer())) { List<Person> collected = stream.collect(Collectors.toList()); Assert.assertEquals(persons, collected); } } finally { //@formatter:off if (file != null) { try { file.delete(); } catch (Exception ignored) { } } //@formatter:on } } @Test(expected = IllegalStateException.class) public void writeAfterClose() throws CsvException, IOException { File file = null; CsvWriter<List<Integer>> writer = null; List<Integer> line = Arrays.asList(0, 1, 2, 3); try { file = createTempFile(); writer = CsvWriter.open(file, new IntegerListSerializer()); writer.close(); writer.put(line); } finally { //@formatter:off if (writer != null) { try { writer.close(); } catch (Exception ignored) { } } if (file != null) { try { file.delete(); } catch (Exception ignored) { } } //@formatter:on } } @Test public void writeRead() throws CsvException, IOException { File file = null; Person mneri = createMneri(); try { file = createTempFile(); try (CsvWriter<Person> writer = CsvWriter.open(file, new PersonSerializer())) { writer.put(mneri); } try (CsvReader<Person> reader = CsvReader.open(file, new PersonDeserializer())) { Person person = reader.next(); Assert.assertEquals(mneri, person); } } finally { //@formatter:off if (file != null) { try { file.delete(); } catch (Exception ignored) { } } //@formatter:on } } }
package org.gnode.nix; import org.gnode.nix.valid.Result; import org.gnode.nix.valid.Validator; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import static org.junit.Assert.*; public class TestMultiTag { private File file; private Block block; private DataArray positions, extents; private MultiTag tag, tag_other, tag_null; private Section section; private Date statup_time; @Before public void setUp() { // precision of time_t is in seconds hence (millis / 1000) * 1000 statup_time = new Date((System.currentTimeMillis() / 1000) * 1000); file = File.open("test_multiTag.h5", FileMode.Overwrite); block = file.createBlock("block", "dataset"); positions = block.createDataArray("positions_DataArray", "dataArray", DataType.Double, new NDSize(new int[]{0, 0})); extents = block.createDataArray("extents_DataArray", "dataArray", DataType.Double, new NDSize(new int[]{0, 0})); double[] A = new double[5 * 5]; for (int i = 0; i < 5; i++) { A[i * 5 + i] = 100.0 * i; } positions.setDataExtent(new NDSize(new int[]{5, 5})); positions.setData(A, new NDSize(new int[]{5, 5}), new NDSize()); double[] B = new double[5 * 5]; for (int i = 0; i < 5; i++) { B[i * 5 + i] = 100.0 * i; } extents.setDataExtent(new NDSize(new int[]{5, 5})); extents.setData(B, new NDSize(new int[]{5, 5}), new NDSize()); tag = block.createMultiTag("tag_one", "test_tag", positions); tag_other = block.createMultiTag("tag_two", "test_tag", positions); tag_null = null; section = file.createSection("foo_section", "metadata"); } @After public void tearDown() { file.deleteBlock(block.getId()); file.deleteSection(section.getId()); file.close(); } @Test public void testValidate() { Result result = Validator.validate(tag); assertTrue(result.getErrors().size() == 0); assertTrue(result.getWarnings().size() == 0); } @Test public void testId() { assertEquals(tag.getId().length(), 36); } @Test public void testName() { assertEquals(tag.getName(), "tag_one"); } @Test public void testType() { assertEquals(tag.getType(), "test_tag"); } @Test public void testDefinition() { String def = "some_str"; tag.setDefinition(def); assertEquals(tag.getDefinition(), def); tag.setDefinition(null); assertNull(tag.getDefinition()); } @Test public void testCreateRemove() { List<String> ids = new ArrayList<String>(); long count = block.getMultiTagCount(); String[] names = {"tag_a", "tag_b", "tag_c", "tag_d", "tag_e"}; for (int i = 0; i < 5; i++) { String type = "Event"; MultiTag dt1 = block.createMultiTag(names[i], type, positions); MultiTag dt2 = block.getMultiTag(dt1.getId()); ids.add(dt1.getId()); assertTrue(dt1.getId().compareTo(dt2.getId()) == 0); } assertTrue(block.getMultiTagCount() == (count + 5)); for (int i = 0; i < ids.size(); i++) { block.deleteMultiTag(ids.get(i)); } assertTrue(block.getMultiTagCount() == count); DataArray a = null; MultiTag mtag = null; try { mtag = block.createMultiTag("test", "test", a); fail(); } catch (RuntimeException re) { } mtag = block.createMultiTag("test", "test", positions); mtag.setExtents(positions); try { mtag.setPositions(a); fail(); } catch (RuntimeException re) { } assertEquals(mtag.getExtents().getId(), positions.getId()); try { mtag.removeExtents(); } catch (Exception e) { fail(); } assertNull(mtag.getExtents()); } @Test public void testUnits() { MultiTag dt = block.createMultiTag("TestMultiTag1", "Tag", positions); List<String> valid_units = Arrays.asList("mV", "cm", "m^2"); List<String> invalid_units = Arrays.asList("mV", "haha", "qm^2"); List<String> insane_units = Arrays.asList("muV ", " muS"); try { dt.setUnits(valid_units); } catch (Exception e) { fail(); } assertTrue(dt.getUnits().size() == valid_units.size()); List<String> retrieved_units = dt.getUnits(); for (int i = 0; i < retrieved_units.size(); i++) { assertEquals(retrieved_units.get(i), valid_units.get(i)); } dt.setUnits(null); assertTrue(dt.getUnits().size() == 0); try { dt.setUnits(invalid_units); fail(); } catch (RuntimeException re) { } assertTrue(dt.getUnits().size() == 0); dt.setUnits(insane_units); retrieved_units = dt.getUnits(); assertTrue(retrieved_units.size() == 2); assertEquals(retrieved_units.get(0), "uV"); assertEquals(retrieved_units.get(1), "uS"); block.deleteMultiTag(dt.getId()); } @Test public void testReferences() { DataArray da_1 = block.createDataArray("TestReference 1", "Reference", DataType.Double, new NDSize(new int[]{0})); DataArray da_2 = block.createDataArray("TestReference 2", "Reference", DataType.Double, new NDSize(new int[]{0})); DataArray a = null; MultiTag dt = block.createMultiTag("TestMultiTag1", "Tag", positions); try { dt.getReference(42); fail(); } catch (RuntimeException re) { } try { dt.hasReference(a); fail(); } catch (RuntimeException re) { } assertTrue(dt.getReferenceCount() == 0); dt.addReference(da_1); dt.addReference(da_2); try { dt.addReference(a); fail(); } catch (RuntimeException re) { } assertTrue(dt.getReferenceCount() == 2); assertTrue(dt.hasReference(da_1)); assertTrue(dt.hasReference(da_2)); assertTrue(dt.hasReference(da_1.getId())); assertTrue(dt.hasReference(da_1.getName())); DataArray ref1 = dt.getReference(da_1.getId()); assertEquals(ref1.getId(), da_1.getId()); DataArray ref2 = dt.getReference(da_1.getName()); assertEquals(ref2.getId(), da_1.getId()); List<DataArray> arrays = dt.getReferences(); assertTrue(arrays.size() == 2); assertTrue(dt.hasReference(da_1.getId())); assertTrue(dt.hasReference(da_2.getId())); dt.removeReference(da_1.getId()); assertTrue(dt.getReferenceCount() == 1); dt.removeReference("NONEXISTENT"); assertTrue(dt.getReferenceCount() == 1); dt.removeReference(da_2.getName()); assertTrue(dt.getReferenceCount() == 0); dt.addReference(da_1); assertTrue(dt.getReferenceCount() == 1); try { dt.removeReference(da_1); } catch (Exception e) { fail(); } assertTrue(dt.getReferenceCount() == 0); // delete data arrays List<String> ids = Arrays.asList(da_1.getId(), da_2.getId()); block.deleteDataArray(da_1.getId()); block.deleteDataArray(da_2.getId()); // check if references are gone too! assertTrue(dt.getReferenceCount() == 0); assertTrue(!dt.hasReference(ids.get(0))); assertTrue(!dt.hasReference(ids.get(1))); block.deleteMultiTag(dt.getId()); } @Test public void testFeatures() { DataArray a = null; Feature f = null; assertEquals(tag.getFeatureCount(), 0); try { tag.hasFeature(f); fail(); } catch (RuntimeException re) { } try { tag.deleteFeature(f); fail(); } catch (RuntimeException re) { } try { tag.createFeature(a, LinkType.Indexed); fail(); } catch (RuntimeException re) { } try { f = tag.createFeature(positions, LinkType.Indexed); } catch (Exception e) { fail(); } assertTrue(tag.getFeatureCount() == 1); try { tag.deleteFeature(f); } catch (Exception e) { fail(); } assertTrue(tag.getFeatureCount() == 0); } @Test public void testExtents() { try { tag.setExtents("wrong_data_array_id"); fail(); } catch (RuntimeException re) { } tag.setPositions(positions); tag.setExtents(extents); assertNotNull(tag.getExtents()); tag.removeExtents(); assertNull(tag.getExtents()); } @Test public void testPositions() { try { tag.setPositions("wrong_data_array_id"); fail(); } catch (RuntimeException re) { } tag.setPositions(positions); assertEquals(tag.getPositions().getId(), positions.getId()); block.deleteDataArray(positions.getId()); // make sure link is gone with data array try { tag.getPositions(); fail(); } catch (RuntimeException re) { } // re-create positions positions = block.createDataArray("positions_DataArray", "dataArray", DataType.Double, new NDSize(new int[]{0, 0})); } @Test public void testPositionExtents() { tag.setExtents(extents); assertEquals(tag.getExtents().getId(), extents.getId()); block.deleteDataArray(extents.getId()); // make sure that link is gone with data array assertNull(tag.getExtents()); // re-create extents extents = block.createDataArray("extents_DataArray", "dataArray", DataType.Double, new NDSize(new int[]{0, 0})); double[] B = new double[5 * 5]; for (int i = 0; i < 5; ++i) { B[i * 5 + i] = 100.0 * i; } extents.setDataExtent(new NDSize(new int[]{5, 5})); extents.setData(B, extents.getDataExtent(), new NDSize()); double[] A = new double[10 * 10]; for (int i = 0; i < 10; ++i) { A[i * 10 + i] = 100.0 * i; } positions.setDataExtent(new NDSize(new int[]{10, 10})); positions.setData(A, positions.getDataExtent(), new NDSize()); tag.setPositions(positions); try { tag.setExtents(extents); fail(); } catch (RuntimeException re) { } tag.removeExtents(); assertNull(tag.getExtents()); } @Test public void testDataAccess() { DataArray data_array = block.createDataArray("dimensionTest", "test", DataType.Double, new NDSize(new int[]{0, 0, 0})); double samplingInterval = 1.0; double[] ticks = {1.2, 2.3, 3.4, 4.5, 6.7}; String unit = "ms"; int[] data = new int[2 * 10 * 5]; int value; for (int i = 0; i != 2; ++i) { value = 0; for (int j = 0; j != 10; ++j) { for (int k = 0; k != 5; ++k) { data[i * 10 * 5 + j * 5 + k] = value++; } } } data_array.setDataExtent(new NDSize(new int[]{2, 10, 5})); data_array.setData(data, data_array.getDataExtent(), new NDSize()); SetDimension setDim = data_array.appendSetDimension(); List<String> labels = Arrays.asList("label_a", "label_b"); setDim.setLabels(labels); SampledDimension sampledDim = data_array.appendSampledDimension(samplingInterval); sampledDim.setUnit(unit); RangeDimension rangeDim = data_array.appendRangeDimension(ticks); rangeDim.setUnit(unit); double[] event_positions = {0.0, 3.0, 3.4, 0.0, 8.0, 2.3}; double[] event_extents = {0.0, 6.0, 2.3, 0.0, 3.0, 2.0}; List<String> event_labels = Arrays.asList("event 1", "event 2"); List<String> dim_labels = Arrays.asList("dim 0", "dim 1", "dim 2"); DataArray event_array = block.createDataArray("positions", "test", DataType.Double, new NDSize(new int[]{2, 3})); event_array.setData(event_positions, event_array.getDataExtent(), new NDSize()); SetDimension event_set_dim; event_set_dim = event_array.appendSetDimension(); event_set_dim.setLabels(event_labels); event_set_dim = event_array.appendSetDimension(); event_set_dim.setLabels(dim_labels); DataArray extent_array = block.createDataArray("extents", "test", DataType.Double, new NDSize(new int[]{2, 3})); extent_array.setData(event_extents, extent_array.getDataExtent(), new NDSize()); SetDimension extent_set_dim; extent_set_dim = extent_array.appendSetDimension(); extent_set_dim.setLabels(event_labels); extent_set_dim = extent_array.appendSetDimension(); extent_set_dim.setLabels(dim_labels); MultiTag multi_tag = block.createMultiTag("multi_tag", "events", event_array); multi_tag.setExtents(extent_array); multi_tag.addReference(data_array); DataView ret_data = multi_tag.retrieveData(0, 0); NDSize data_size = ret_data.getDataExtent(); assertEquals(data_size.getSize(), 3); int[] data_size_arr = data_size.getData(); assertTrue(data_size_arr[0] == 1 && data_size_arr[1] == 6 && data_size_arr[2] == 2); try { multi_tag.retrieveData(1, 0); fail(); } catch (RuntimeException re) { } block.deleteMultiTag(multi_tag); block.deleteDataArray(data_array); block.deleteDataArray(event_array); block.deleteDataArray(event_array); } @Test public void testMetadataAccess() { assertNull(tag.getMetadata()); tag.setMetadata(section); assertNotNull(tag.getMetadata()); assertNotNull(tag.getMetadata().getId(), section.getId()); // test none-unsetter tag.removeMetadata(); assertNull(tag.getMetadata()); // test deleter removing link too tag.setMetadata(section); file.deleteSection(section.getId()); assertNull(tag.getMetadata()); // re-create section section = file.createSection("foo_section", "metadata"); } @Test public void testSourceAccess() { List<String> names = Arrays.asList("source_a", "source_b", "source_c", "source_d", "source_e"); assertEquals(tag.getSourceCount(), 0); assertEquals(tag.getSources().size(), 0); List<String> ids = new ArrayList<String>(); for (String name : names) { Source child_source = block.createSource(name, "channel"); tag.addSource(child_source); assertEquals(child_source.getName(), name); ids.add(child_source.getId()); } assertEquals(tag.getSourceCount(), names.size()); assertEquals(tag.getSources().size(), names.size()); String name = names.get(0); Source source = tag.getSource(name); assertEquals(source.getName(), name); for (String id : ids) { Source child_source = tag.getSource(id); assertTrue(tag.hasSource(id)); assertEquals(child_source.getId(), id); tag.removeSource(id); block.deleteSource(id); } assertEquals(tag.getSourceCount(), 0); assertEquals(tag.getSources().size(), 0); } @Test public void testCreatedAt() { assertTrue(tag.getCreatedAt().compareTo(statup_time) >= 0); long time = System.currentTimeMillis() - 10000000L * 1000; // precision of time_t is in seconds hence (millis / 1000) * 1000 time = time / 1000 * 1000; Date past_time = new Date(time); tag.forceCreatedAt(past_time); assertTrue(tag.getCreatedAt().equals(past_time)); } @Test public void testUpdatedAt() { assertTrue(tag.getUpdatedAt().compareTo(statup_time) >= 0); } }
package org.apache.commons.validator; import java.io.Serializable; import java.util.HashSet; import org.apache.oro.text.perl.Perl5Util; public class UrlValidator implements Serializable { private static final String alphaChars = "a-zA-Z"; private static final String alphaNumChars = alphaChars + "\\d"; private static final String specialChars = ";/@&=,.?:+$"; private static final String validChars = "[^\\s" + specialChars + "]"; private static final String schemeChars = alphaChars; // Drop numeric, and "+-." for now private static final String authorityChars = alphaNumChars + "\\-\\."; private static final String atom = validChars + '+'; /** * This expression derived/taken from the BNF for URI (RFC2396). */ private static final String urlPat = "/^(([^:/? // 12 3 4 5 6 7 8 9 /** * Schema/Protocol (ie. http:, ftp:, file:, etc). */ private static final int PARSE_URL_SCHEME = 2; /** * Includes hostname/ip and port number. */ private static final int PARSE_URL_AUTHORITY = 4; private static final int PARSE_URL_PATH = 5; private static final int PARSE_URL_QUERY = 7; private static final int PARSE_URL_FRAGMENT = 9; /** * Protocol (ie. http:, ftp:,https:). */ private static final String schemePat = "/^[" + schemeChars + "]/"; private static final String authorityPat = "/^([" + authorityChars + "]*)(:\\d*)?(.*)?/"; // 1 2 3 4 private static final int PARSE_AUTHORITY_HOST_IP = 1; private static final int PARSE_AUTHORITY_PORT = 2; /** * Should always be empty. */ private static final int PARSE_AUTHORITY_EXTRA = 3; private static final String pathPat = "/^(/[-a-zA-Z0-9_:@&?=+,.!/~*'%$]*)$/"; private static final String queryPat = "/^(.*)$/"; private static final String legalAsciiPat = "/^[\\000-\\177]+$/"; private static final String ipV4DomainPat = "/^(\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})$/"; private static final String domainPat = "/^" + atom + "(\\." + atom + ")*$/"; private static final String portPat = "/^:(\\d{1,5})$/"; private static final String atomPat = "/(" + atom + ")/"; private static final String alphaPat = "/^[" + alphaChars + "]/"; // Non static fields private boolean allow2Slash = false; private boolean allowAllScheme = false; private boolean noFragment = false; private HashSet allowedSchemeSet; protected String[] defaultSchemeSet = {"http", "https", "ftp"}; /** * Create a UrlValidator with default properties. */ public UrlValidator() { this(null); } public UrlValidator(String[] schemes) { this(schemes, false, false, false); } public UrlValidator(String[] schemes, boolean allowAllScheme, boolean allow2Slash, boolean noFragment) { this.allowAllScheme = allowAllScheme; this.allow2Slash = allow2Slash; this.noFragment = noFragment; if (!this.allowAllScheme) { if (schemes == null) { this.allowedSchemeSet = new HashSet(defaultSchemeSet.length); for (int sIndex = 0; sIndex < defaultSchemeSet.length; sIndex++) { this.allowedSchemeSet.add(defaultSchemeSet[sIndex]); } } else if (schemes != null) { this.allowedSchemeSet = new HashSet(schemes.length); for (int sIndex = 0; sIndex < schemes.length; sIndex++) { this.allowedSchemeSet.add(schemes[sIndex]); } } } } /** * <p>Checks if a field has a valid url address.</p> * * @param value The value validation is being performed on. * @return true if the url is valid. */ public boolean isValid(String value) { try { Perl5Util matchUrlPat = new Perl5Util(); Perl5Util matchAsciiPat = new Perl5Util(); if (!matchAsciiPat.match(legalAsciiPat, value)) { return false; } // Check the whole url address structure if (!matchUrlPat.match(urlPat, value)) { return false; } if (!isValidScheme(matchUrlPat.group(PARSE_URL_SCHEME))) { return false; } if (!isValidAuthority(matchUrlPat.group(PARSE_URL_AUTHORITY))) { return false; } if (!isValidPath(matchUrlPat.group(PARSE_URL_PATH))) { return false; } if (!isValidQuery(matchUrlPat.group(PARSE_URL_QUERY))) { return false; } if (!isValidFragment(matchUrlPat.group(PARSE_URL_FRAGMENT))) { return false; } } catch (Exception e) { // TODO Do we need to catch Exception? return false; } return true; } /** * Validate scheme. If schemes[] was initialized to a non null, * then only those scheme's are allowed. Note this is slightly different * than for the Constructor. * @param scheme The scheme to validate. * @return true is valid. */ protected boolean isValidScheme(String scheme) { Perl5Util matchSchemePat = new Perl5Util(); boolean bValid = matchSchemePat.match(schemePat, scheme); if (bValid) { if (allowedSchemeSet != null) { bValid = allowedSchemeSet.contains(scheme); } } return bValid; } /** * Returns true if the authority is properly formatted. An authority is the combination * of hostname and port. */ protected boolean isValidAuthority(String authority) { boolean bValid = true; Perl5Util matchAuthorityPat = new Perl5Util(); Perl5Util matchIPV4Pat = new Perl5Util(); Perl5Util matchDomainPat = new Perl5Util(); Perl5Util matchAtomPat = new Perl5Util(); Perl5Util matchPortPat = new Perl5Util(); Perl5Util matchAlphaPat = new Perl5Util(); bValid = matchAuthorityPat.match(authorityPat, authority); if (bValid) { boolean ipV4Address = false; boolean hostname = false; // check if authority is IP address or hostname String hostIP = matchAuthorityPat.group(PARSE_AUTHORITY_HOST_IP); ipV4Address = matchIPV4Pat.match(ipV4DomainPat, hostIP); if (ipV4Address) { // this is an IP address so check components for (int i = 1; i <= 4; i++) { String ipSegment = matchIPV4Pat.group(i); if (ipSegment != null && ipSegment.length() > 0) { int iIpSegment = 0; try { iIpSegment = Integer.parseInt(ipSegment); } catch (Exception e) { bValid = false; } if (iIpSegment > 255) { bValid = false; } } else { bValid = false; } } } else { // Domain is hostname name hostname = matchDomainPat.match(domainPat, hostIP); } //rightmost hostname will never start with a digit. if (hostname) { // this is a hostname authority so check components String[] domainSegment = new String[10]; boolean match = true; int segmentCount = 0; int segmentLength = 0; while (match) { match = matchAtomPat.match(atomPat, hostIP); if (match) { domainSegment[segmentCount] = matchAtomPat.group(1); segmentLength = domainSegment[segmentCount].length() + 1; hostIP = (segmentLength >= hostIP.length()) ? "" : hostIP.substring(segmentLength); segmentCount++; } } String topLevel = domainSegment[segmentCount - 1]; if (topLevel.length() < 2 || topLevel.length() > 4) { bValid = false; } // First letter of top level must be a alpha boolean isAlpha; isAlpha = matchAlphaPat.match(alphaPat, topLevel.substring(0, 1)); if (!isAlpha) { bValid = false; } // Make sure there's a host name preceding the authority. if (segmentCount < 2) { bValid = false; } } if (bValid) { bValid = (hostname || ipV4Address); } if (bValid) { String port = matchAuthorityPat.group(PARSE_AUTHORITY_PORT); if (port != null) { bValid = matchPortPat.match(portPat, port); } } if (bValid) { String extra = matchAuthorityPat.group(PARSE_AUTHORITY_EXTRA); bValid = ((extra == null) || (extra.length() == 0)); } } return bValid; } protected boolean isValidPath(String path) { Perl5Util matchPathPat = new Perl5Util(); boolean bValid = true; bValid = matchPathPat.match(pathPat, path); if (bValid) { //Shouldn't end with a '/' bValid = (path.lastIndexOf("/") < (path.length() - 1)); } if (bValid) { int slash2Count = countToken("//", path); if (!allow2Slash) { bValid = (slash2Count == 0); } if (bValid) { int slashCount = countToken("/", path); int dot2Count = countToken("..", path); if (dot2Count > 0) { bValid = ((slashCount - slash2Count - 1) > dot2Count); } } } return bValid; } /** * Returns true if the query is null or it's a properly formatted query string. */ protected boolean isValidQuery(String query) { if (query == null) { return true; } Perl5Util matchQueryPat = new Perl5Util(); return matchQueryPat.match(queryPat, query); } /** * Returns true if the given fragment is null or fragments are allowed. */ protected boolean isValidFragment(String fragment) { if (fragment == null) { return true; } return (noFragment == false); } /** * Returns the number of times the token appears in the target. */ protected int countToken(String token, String target) { int tokenIndex = 0; int count = 0; while (tokenIndex != -1) { tokenIndex = target.indexOf(token, tokenIndex); if (tokenIndex > -1) { tokenIndex++; count++; } } return count; } }
package motocitizen.app.mc; import android.content.Context; import android.graphics.Color; import android.view.View; import android.view.View.OnLongClickListener; import android.widget.PopupWindow; import android.widget.TableRow; import android.widget.TextView; import org.json.JSONException; import org.json.JSONObject; import java.text.ParseException; import java.util.Date; import motocitizen.app.mc.popups.MCMessagesPopup; import motocitizen.utils.Const; public class MCMessage { public int id; public int owner_id; public int table_row; public final int acc_id; private final OnLongClickListener rowLongClick = new OnLongClickListener() { @Override public boolean onLongClick(View v) { PopupWindow pw; pw = MCMessagesPopup.getPopupWindow(id, acc_id); pw.showAsDropDown(v, 20, -20); return true; } }; public String owner, status, text; public Date time; public Boolean unread; public MCMessage(JSONObject json, int acc_id) throws JSONException { this.acc_id = acc_id; unread = true; id = json.getInt("id"); owner_id = json.getInt("id_user"); owner = json.getString("owner"); status = json.getString("status"); text = json.getString("text"); text = json.getString("text"); time = new Date(Long.parseLong(json.getString("uxtime"), 10)*1000); } public TableRow createRow(Context context) { TableRow tr = new TableRow(context); TableRow.LayoutParams lp = new TableRow.LayoutParams(); TextView tvDate = new TextView(tr.getContext()); TextView tvOwner = new TextView(tr.getContext()); TextView tvText = new TextView(tr.getContext()); lp.setMargins(0, 0, 5, 0); tvDate.setText(Const.timeFormat.format(time.getTime())); tvOwner.setLayoutParams(lp); tvOwner.setText(owner); if (owner.equals(MCAccidents.auth.getLogin())) { tvOwner.setBackgroundColor(Color.DKGRAY); } else { tvOwner.setBackgroundColor(Color.GRAY); } tvText.setMaxLines(10); tvText.setSingleLine(false); tvText.setText(text); tr.setTag(String.valueOf(id)); tr.addView(tvDate); tr.addView(tvOwner); tr.addView(tvText); tr.setOnLongClickListener(rowLongClick); return tr; } }
package com.github.nsnjson; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.*; import java.util.*; import static com.github.nsnjson.format.Format.*; import static com.github.nsnjson.format.Format.FIELD_VALUE; public class AbstractFormatTest { protected static NullNode getNull() { return NullNode.getInstance(); } protected static BooleanNode getBooleanTrue() { return BooleanNode.getTrue(); } protected static BooleanNode getBooleanFalse() { return BooleanNode.getFalse(); } protected static NumericNode getNumberInt() { return new IntNode(new Random().nextInt()); } protected static NumericNode getNumberLong() { return new LongNode(new Random().nextLong()); } protected static NumericNode getNumberDouble() { return new DoubleNode(new Random().nextDouble()); } protected static TextNode getEmptyString() { return new TextNode(""); } protected static TextNode getString() { return new TextNode(UUID.randomUUID().toString().replaceAll("-", "")); } protected static ArrayNode getEmptyArray() { return new ObjectMapper().createArrayNode(); } protected static ArrayNode getArray() { ArrayNode array = getEmptyArray(); array.add(getNull()); array.add(getBooleanTrue()); array.add(getBooleanFalse()); array.add(getNumberInt()); array.add(getNumberLong()); array.add(getNumberDouble()); array.add(getString()); return array; } protected static ObjectNode getEmptyObject() { return new ObjectMapper().createObjectNode(); } protected static ObjectNode getObject() { ObjectNode object = new ObjectMapper().createObjectNode(); object.set("null_field", getNull()); object.set("true_field", getBooleanTrue()); object.set("false_field", getBooleanFalse()); object.set("int_field", getNumberInt()); object.set("long_field", getNumberLong()); object.set("double_field", getNumberDouble()); object.set("string_field", getString()); return object; } protected static ObjectNode getNullPresentation() { ObjectNode presentation = new ObjectMapper().createObjectNode(); presentation.put(FIELD_TYPE, TYPE_MARKER_NULL); return presentation; } protected static ObjectNode getNumberIntPresentation(NumericNode value) { ObjectNode presentation = new ObjectMapper().createObjectNode(); presentation.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentation.put(FIELD_VALUE, value.asInt()); return presentation; } }
package com.github.tonivade.tinydb; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.number.OrderingComparison.lessThan; import static org.junit.Assert.assertThat; import java.util.Iterator; import org.junit.Rule; import org.junit.Test; import redis.clients.jedis.Jedis; import redis.clients.jedis.Pipeline; public class TinyDBTest { @Rule public final TinyDBRule rule = new TinyDBRule(); @Test public void testCommands() { try (Jedis jedis = createClientConnection()) { assertThat(jedis.ping(), equalTo("PONG")); assertThat(jedis.echo("Hi!"), equalTo("Hi!")); assertThat(jedis.set("a", "1"), equalTo("OK")); assertThat(jedis.strlen("a"), equalTo(1L)); assertThat(jedis.strlen("b"), equalTo(0L)); assertThat(jedis.exists("a"), equalTo(true)); assertThat(jedis.exists("b"), equalTo(false)); assertThat(jedis.get("a"), equalTo("1")); assertThat(jedis.get("b"), nullValue()); assertThat(jedis.getSet("a", "2"), equalTo("1")); assertThat(jedis.get("a"), equalTo("2")); assertThat(jedis.del("a"), equalTo(1L)); assertThat(jedis.get("a"), nullValue()); assertThat(jedis.eval("return 1"), equalTo(1L)); assertThat(jedis.quit(), equalTo("OK")); } } @Test public void testPipeline() { try (Jedis jedis = createClientConnection()) { Pipeline p = jedis.pipelined(); p.ping(); p.echo("Hi!"); p.set("a", "1"); p.strlen("a"); p.strlen("b"); p.exists("a"); p.exists("b"); p.get("a"); p.get("b"); p.getSet("a", "2"); p.get("a"); p.del("a"); p.get("a"); p.eval("return 1"); Iterator<Object> result = p.syncAndReturnAll().iterator(); assertThat(result.next(), equalTo("PONG")); assertThat(result.next(), equalTo("Hi!")); assertThat(result.next(), equalTo("OK")); assertThat(result.next(), equalTo(1L)); assertThat(result.next(), equalTo(0L)); assertThat(result.next(), equalTo(true)); assertThat(result.next(), equalTo(false)); assertThat(result.next(), equalTo("1")); assertThat(result.next(), nullValue()); assertThat(result.next(), equalTo("1")); assertThat(result.next(), equalTo("2")); assertThat(result.next(), equalTo(1L)); assertThat(result.next(), nullValue()); assertThat(result.next(), equalTo(1L)); jedis.quit(); } } @Test public void testEval() throws Exception { try (Jedis jedis = createClientConnection()) { assertThat(jedis.eval("return 1"), equalTo(1L)); } } @Test public void testEvalScript() throws Exception { try (Jedis jedis = createClientConnection()) { assertThat(jedis.eval("local keys = redis.call('keys', '*region*') for i,k in ipairs(keys) do local res = redis.call('del', k) end"), equalTo(1L)); } } @Test public void testLoad100000() { int times = 100000; try (Jedis jedis = createClientConnection()) { long start = System.nanoTime(); for (int i = 0; i < times; i++) { jedis.set(key(i), value(i)); } jedis.quit(); assertThat((System.nanoTime() - start) / times, lessThan(1000000L)); } } private Jedis createClientConnection() { return new Jedis(ITinyDB.DEFAULT_HOST, ITinyDB.DEFAULT_PORT, 10000); } private String value(int i) { return "value" + String.valueOf(i); } private String key(int i) { return "key" + String.valueOf(i); } }
package com.rox.emu.mem; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class MultiSourceMemoryTest { private Memory memoryBlockA; private Memory memoryBlockB; private MultiSourceMemory testMemory; @Before public void setup(){ memoryBlockA = new SimpleMemory(); memoryBlockB = new SimpleMemory(); testMemory = new MultiSourceMemory().maintaining(new SimpleMemory()) .withMapping(10, memoryBlockA) .withMapping(new int[] {20,21,22,23,24,25}, memoryBlockB); } @Test public void testNoMaintainedMemory(){ final Memory targetMemory = mock(SimpleMemory.class); final Memory logicalMemory = new MultiSourceMemory().withMapping(2, targetMemory); logicalMemory.getByte(2); try{ logicalMemory.getByte(1); fail("Expected an exception, there is no memory mapped to address 1"); }catch(NullPointerException npE){} } @Test public void testSimpleGetByte(){ memoryBlockA.setByteAt(10, 99); assertEquals(99, testMemory.getByte(10)); } @Test public void testSimplePutByte(){ testMemory.setByteAt(10, 99); assertEquals(99, memoryBlockA.getByte(10)); } @Test public void testSimpleGetBlock(){ int[] sampleData = new int[] {1,2,3,4,5}; memoryBlockB.setBlock(20, sampleData); assertTrue("Expected " + Arrays.toString(sampleData) + ", got " + Arrays.toString(testMemory.getBlock(20, 25)), Arrays.equals( sampleData, testMemory.getBlock(20, 25))); } @Test public void testSimpleSetBlock(){ int[] sampleData = new int[] {1,2,3,4,5}; testMemory.setBlock(20, sampleData); assertTrue("Expected " + Arrays.toString(sampleData) + ", got " + Arrays.toString(memoryBlockB.getBlock(20, 25)), Arrays.equals( sampleData, memoryBlockB.getBlock(20, 25))); } @Test public void testMultipleDestinationReset(){ final Memory memory1 = mock(Memory.class); testMemory = testMemory.withMapping(20, memory1); final Memory memory2 = mock(Memory.class); testMemory = testMemory.withMapping(30, memory2); testMemory = testMemory.withMapping(40, memory2); final Memory memory3 = mock(Memory.class); testMemory = testMemory.withMapping(50, memory3); testMemory = testMemory.withMapping(60, memory3); testMemory = testMemory.withMapping(70, memory3); testMemory.reset(); verify(memory1, times(1)).reset(); verify(memory2, times(1)).reset(); verify(memory3, times(1)).reset(); } }
package it.polimi.sr.sparql; import it.polimi.sr.mql.MQLQuery; import it.polimi.sr.mql.parser.MQLParser; import org.apache.commons.io.Charsets; import org.apache.commons.io.IOUtils; import org.apache.jena.query.QueryFactory; import org.apache.jena.query.QueryParseException; import org.apache.jena.riot.system.IRIResolver; import org.apache.jena.sparql.core.QueryCompare; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.parboiled.Parboiled; import org.parboiled.errors.ParseError; import org.parboiled.parserunners.ReportingParseRunner; import org.parboiled.support.ParsingResult; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.apache.commons.io.FileUtils.readFileToString; import static org.junit.Assert.assertEquals; @RunWith(Parameterized.class) public class Sparql11QueryTest { private static boolean res; private static String f; private static final String folder = "tests/"; @Parameters public static Collection<Object[]> data() throws IOException { List<Object[]> obj = new ArrayList<Object[]>(); for (String d : IOUtils.readLines(Sparql11QueryTest.class.getClassLoader() .getResourceAsStream(folder), Charsets.UTF_8)) { if (!d.contains("class")) { for (String f : IOUtils.readLines(Sparql11QueryTest.class.getClassLoader() .getResourceAsStream(folder + d + "/"), Charsets.UTF_8)) { if (!f.contains(".arq") && !f.contains(".sh") && (!f.contains("false") || !f.contains("bad"))) { obj.add(new Object[]{(folder + d + "/" + f), true}); } } } } return obj; } public Sparql11QueryTest(String f, boolean res) { this.res = res; this.f = f; } static String input; static org.apache.jena.query.Query toCompare; @Before public void load() throws URISyntaxException, IOException { } @Test public void test() { try { (new Sparql11QueryTest(f, res)).process(); } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }catch (QueryParseException epe){ epe.printStackTrace(); } } public static void process() throws URISyntaxException, IOException { System.out.println(f); input = readFileToString(new File(Sparql11QueryTest.class.getClassLoader().getResource(f).toURI())); System.out.println(input); toCompare = QueryFactory.create(input); MQLParser parser = Parboiled.createParser(MQLParser.class); parser.setResolver(IRIResolver.create()); ReportingParseRunner reportingParseRunner = new ReportingParseRunner(parser.Query()); ParsingResult<MQLQuery> result = reportingParseRunner.run(input); if (result.hasErrors()) { for (ParseError e : result.parseErrors) { System.out.println(e.getStartIndex()); System.out.println(e.getEndIndex()); System.out.println(input.substring(0, e.getStartIndex())); System.err.print(input.substring(e.getStartIndex(), e.getEndIndex())); System.out.println(input.substring(e.getEndIndex(), input.length() - 1)); } } org.apache.jena.query.Query q = result.parseTreeRoot.getChildren().get(0).getValue().getQ(); QueryCompare.PrintMessages = true; assertEquals(res, org.apache.jena.sparql.core.QueryCompare.equals(toCompare, q)); } }
package org.animotron.statement.math; import org.animotron.ATest; import org.animotron.expression.Expression; import org.animotron.expression.JExpression; import org.junit.Test; import static org.animotron.expression.JExpression._; import static org.animotron.expression.JExpression.value; /** * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> * */ public class MathTest extends ATest { @Test public void test_00() throws Exception { Expression e = new JExpression( _(SUM._, value(1), value(2), value(3), value(4)) ); assertStringResult(e, "10"); } @Test public void test_01() throws Exception { Expression e = new JExpression( _(MUL._, value(2), value(2)) ); assertStringResult(e, "4"); } @Test public void test_02() throws Exception { Expression e = new JExpression( _(MUL._, value(2), value(2.0)) ); assertStringResult(e, "4.0"); } @Test public void test_03() throws Exception { Expression e = new JExpression( _(MUL._, value(2.0), value(2)) ); assertStringResult(e, "4.0"); } @Test public void test_04() throws Exception { Expression e = new JExpression( _(MUL._, value(2.0), value(2.0)) ); assertStringResult(e, "4.0"); } @Test public void test_05() throws Exception { Expression e = new JExpression( _(DIV._, value(4.0), value(2.0)) ); assertStringResult(e, "2.0"); } @Test public void test_06() throws Exception { Expression e = new JExpression( _(DIV._, value(4), value(2)) ); assertStringResult(e, "2"); } @Test public void test_07() throws Exception { Expression e = new JExpression( _(SUB._, value(1), value(2), value(3.0), value(4)) ); assertStringResult(e, "-8.0"); } }
package orc.ast.extended.pattern; import java.util.LinkedList; import java.util.List; import orc.ast.simple.Call; import orc.ast.simple.Expression; import orc.ast.simple.Let; import orc.ast.simple.Parallel; import orc.ast.simple.Semi; import orc.ast.simple.Sequential; import orc.ast.simple.Silent; import orc.ast.simple.Where; import orc.ast.simple.WithLocation; import orc.ast.simple.arg.Argument; import orc.ast.simple.arg.Constant; import orc.ast.simple.arg.Field; import orc.ast.simple.arg.Site; import orc.ast.simple.arg.Var; import orc.error.compiletime.NonlinearPatternException; import orc.error.compiletime.PatternException; import orc.error.Locatable; import orc.error.SourceLocation; import orc.runtime.sites.Constructor; /** * * Base interface for the abstract syntax of patterns. * * Patterns exist only in the extended abstract syntax. They desugar into a * series of operations which terminate in variable bindings. * * @author dkitchin * */ public abstract class Pattern implements Locatable { private SourceLocation location = SourceLocation.UNKNOWN; /* Patterns are assumed to be strict unless set otherwise */ public boolean strict() { return true; } /** * Visit a pattern recursively, creating two products: * * An expression that will examine a value to determine * whether it matches a pattern, building an output tuple * of all value fragments which will be bound to variables. * * An expression transformer that will examine such an * output tuple and bind its elements to variables in * a given expression. * * @param fragment A variable holding the current fragment of the value to be matched * @param visitor A visitor object which accumulates an expression and a transformer * @throws PatternException */ public abstract void process(Var fragment, PatternSimplifier visitor) throws PatternException; /** * * A different entry point for process, taking only a source variable. * Creates a new visitor, visits the pattern, and then returns that visitor. * @throws PatternException */ public PatternSimplifier process(Var fragment) throws PatternException { PatternSimplifier pv = new PatternSimplifier(); process(fragment, pv); return pv; } /* Sites often used in pattern matching */ protected static Argument IF = new Site(orc.ast.sites.Site.IF); protected static Argument EQUAL = new Site(orc.ast.sites.Site.EQUAL); protected static Argument SOME = new Site(orc.ast.sites.Site.SOME); protected static Argument NONE = new Site(orc.ast.sites.Site.NONE); public static Argument TRYSOME = new Site(orc.ast.sites.Site.ISSOME); public static Argument TRYNONE = new Site(orc.ast.sites.Site.ISNONE); /* This site might be replaced by a special message */ protected static Argument TRYCONS = new Site(orc.ast.sites.Site.TRYCONS); /* This site might not be necessary */ protected static Argument TRYNIL = new Site(orc.ast.sites.Site.TRYNIL); /** * * Construct an expression comparing two arguments. * The result expression returns a signal if the arguments are equal, * and remains silent otherwise. * * @param s An argument to compare * @param t An argument to compare * @return An expression publishing a signal if s=t, silent otherwise */ public static Expression compare(Argument s, Argument t) { Var b = new Var(); // s = t Expression test = new Call(EQUAL, s, t); // (s = t) >b> if(b) Expression comp = new Sequential(test, new Call(IF,b), b); return comp; } /** * Construct an expression which publishes the ith element * of tuple s. * * @param s An argument bound to a tuple * @param i An index into a tuple (starting at 0) * @return An expression publishing s(i) */ public static Expression nth(Argument s, int i) { return new Call(s,new Constant(i)); } /** * * Constructs an expression which will try to deconstruct an * argument as if it were a list. It publishes (h,t) if the * argument s is viewable as a list h:t, and remains silent * otherwise. * * @param s */ public static Expression trycons(Argument s) { // TODO: Make trycons a special message return new Call(TRYCONS, s); } /** * * Constructs an expression which tests whether the argument * s can be treated as an empty list (nil). If so, it * publishes a signal; otherwise it remains silent. * * @param s */ public static Expression trynil(Argument s) { return new Call(TRYNIL, s); } /** * * Construct an expression to determine whether the argument * s may be viewed as a tuple of size n. If so, the expression * publishes a signal; otherwise it remains silent. * * @param s Argument to test * @param n Target arity */ public static Expression trysize(Argument s, int n) { // TODO: Make this field name a special constant // s.fits Expression fits = new Call(s, new Field("fits")); Var m = new Var(); Expression invoke = new Call(m, new Constant(n)); // s.fits >m> m(n) return new Sequential(fits, invoke, m); } /** * * Construct an expression which tries to find the inverse * of the site m, and apply it to s. While the result will * depend on the site itself, as a guideline the inverse * should obey the following specification: * * Let i = unapply(m,s). * If s = m(x) for some x, then i(s) = x. * Otherwise, i(s) remains silent. * * Currently we find the inverse via a special message. * * @see Constructor * * @param m The site to unapply * @param s Argument to the inversion */ public static Expression unapply(Argument m, Argument s) { Var i = new Var(); // TODO: Make the field name "?" a special constant return new Sequential(new Call(m, new Field("?")), new Call(i, s), i); } /** * Lifts a partial function to a total function, using * the ; combinator to detect a refusal to respond, * and publishing optional values instead of values. * * <code> some(x) ; none </code> * * @param x */ public static Expression lift(Var x) { return new Semi(new Call(SOME, x), new Call(NONE)); } /** * Constructs an optional case statement. * * <code> * case arg of * some(s) -> succ * | none -> fail * </code> * * @param arg * @param s * @param succ * @param fail */ public static Expression caseof(Var arg, Var s, Expression succ, Expression fail) { // trySome(arg) >s> succ Expression someb = new Sequential(new Call(TRYSOME, arg), succ, s); // tryNone(arg) >> fail Expression noneb = new Sequential(new Call(TRYNONE, arg), fail, new Var()); // trySome... | tryNone... return new Parallel(someb, noneb); } public void setSourceLocation(SourceLocation location) { this.location = location; } public SourceLocation getSourceLocation() { return location; } }
package org.voltdb; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.URLEncoder; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import junit.framework.TestCase; import org.voltdb.VoltDB.Configuration; import org.voltdb.client.Client; import org.voltdb.client.ClientFactory; import org.voltdb.client.ClientResponse; import org.voltdb.client.SyncCallback; import org.voltdb.compiler.VoltProjectBuilder; import org.voltdb.messaging.HostMessenger; import org.voltdb.network.VoltNetwork; import org.voltdb.regressionsuites.LocalCluster; import org.voltdb.utils.JarReader; public class TestRejoinEndToEnd extends TestCase { VoltProjectBuilder getBuilderForTest() throws UnsupportedEncodingException { String simpleSchema = "create table blah (" + "ival bigint default 0 not null, " + "PRIMARY KEY(ival));"; File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema); String schemaPath = schemaFile.getPath(); schemaPath = URLEncoder.encode(schemaPath, "UTF-8"); VoltProjectBuilder builder = new VoltProjectBuilder(); builder.addSchema(schemaPath); builder.addPartitionInfo("blah", "ival"); builder.addStmtProcedure("Insert", "insert into blah values (?);"); builder.addStmtProcedure("InsertSinglePartition", "insert into blah values (?);", "blah.ival:0"); return builder; } static class Context { long catalogCRC; ServerThread localServer; } /** * Simple code to copy a file from one place to another... * Java should have this built in... stupid java... */ static void copyFile(String fromPath, String toPath) { File inputFile = new File(fromPath); File outputFile = new File(toPath); try { FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { e.printStackTrace(); fail(); } } Context getServerReadyToReceiveNewNode() throws Exception { Context retval = new Context(); VoltProjectBuilder builder = getBuilderForTest(); boolean success = builder.compile(Configuration.getPathToCatalogForTest("rejoin.jar"), 1, 2, 1, "localhost", false); assertTrue(success); copyFile(builder.getPathToDeployment(), Configuration.getPathToCatalogForTest("rejoin.xml")); VoltDB.Configuration config = new VoltDB.Configuration(); config.m_pathToCatalog = Configuration.getPathToCatalogForTest("rejoin.jar"); config.m_pathToDeployment = Configuration.getPathToCatalogForTest("rejoin.xml"); retval.localServer = new ServerThread(config); // start the fake HostMessenger retval.catalogCRC = JarReader.crcForJar(Configuration.getPathToCatalogForTest("rejoin.jar")); VoltNetwork network2 = new VoltNetwork(); InetAddress leader = InetAddress.getByName("localhost"); HostMessenger host2 = new HostMessenger(network2, leader, 2, retval.catalogCRC, null); retval.localServer.start(); host2.waitForGroupJoin(); network2.start(); host2.sendReadyMessage(); retval.localServer.waitForInitialization(); HostMessenger host1 = VoltDB.instance().getHostMessenger(); //int host2id = host2.getHostId(); host2.closeForeignHostScoket(host1.getHostId()); // this is just to wait for the fault manager to kick in Thread.sleep(50); host2.shutdown(); // this is just to wait for the fault manager to kick in Thread.sleep(50); // wait until the fault manager has kicked in for (int i = 0; host1.countForeignHosts() > 0; i++) { if (i > 10) fail(); Thread.sleep(50); } assertEquals(0, host1.countForeignHosts()); return retval; } final int FAIL_NO_OPEN_SOCKET = 0; final int FAIL_TIMEOUT_ON_SOCKET = 1; final int FAIL_SKEW = 2; final int DONT_FAIL = 3; boolean failNext(int failType) throws Exception { Context context = getServerReadyToReceiveNewNode(); Client client = ClientFactory.createClient(); client.createConnection("localhost", null, null); ServerSocketChannel listener = null; if (failType != FAIL_NO_OPEN_SOCKET) { try { listener = ServerSocketChannel.open(); listener.socket().bind(new InetSocketAddress(VoltDB.DEFAULT_INTERNAL_PORT + 1)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(-1); } } SyncCallback scb = new SyncCallback(); boolean success = false; while (!success) { success = client.callProcedure(scb, "@Rejoin", "localhost", VoltDB.DEFAULT_INTERNAL_PORT + 1); if (!success) Thread.sleep(100); } SocketChannel socket = null; if (failType != FAIL_NO_OPEN_SOCKET) { socket = listener.accept(); listener.close(); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.socket().getOutputStream())); DataInputStream in = new DataInputStream(new BufferedInputStream(socket.socket().getInputStream())); int hostId = in.readInt(); assertEquals(hostId, 1); if (failType != FAIL_TIMEOUT_ON_SOCKET) { //COMMAND_SENDTIME_AND_CRC out.writeInt(4); out.flush(); // ignore what the other host says the time is in.readLong(); // fake a clock skew of 1ms if (failType == FAIL_SKEW) { out.writeLong(100000); // COMMAND_NTPFAIL out.writeInt(5); } else { out.writeLong(1); // COMMAND_COMPLETE out.writeInt(3); } out.flush(); } } scb.waitForResponse(); ClientResponse response = scb.getResponse(); switch (failType) { case FAIL_NO_OPEN_SOCKET: assertTrue(response.getStatus() != ClientResponse.SUCCESS); break; case FAIL_TIMEOUT_ON_SOCKET: assertTrue(response.getStatus() != ClientResponse.SUCCESS); break; case FAIL_SKEW: assertTrue(response.getStatus() != ClientResponse.SUCCESS); break; case DONT_FAIL: assertTrue(response.getStatus() == ClientResponse.SUCCESS); break; } if (failType != FAIL_NO_OPEN_SOCKET) socket.close(); context.localServer.shutdown(); context.localServer.join(); // this means there is nothing else to try return failType != DONT_FAIL; } /*public void testRejoinSysprocButFail() throws Exception { VoltProjectBuilder builder = getBuilderForTest(); boolean success = builder.compile(Configuration.getPathToCatalogForTest("rejoin.jar"), 1, 1, 0, "localhost", false); assertTrue(success); copyFile(builder.getPathToDeployment(), Configuration.getPathToCatalogForTest("rejoin.xml")); VoltDB.Configuration config = new VoltDB.Configuration(); config.m_pathToCatalog = Configuration.getPathToCatalogForTest("rejoin.jar"); config.m_pathToDeployment = Configuration.getPathToCatalogForTest("rejoin.xml"); ServerThread localServer = new ServerThread(config); localServer.start(); localServer.waitForInitialization(); Client client = ClientFactory.createClient(); client.createConnection("localhost", null, null); SyncCallback scb = new SyncCallback(); success = false; while (!success) { success = client.callProcedure(scb, "@Rejoin", "localhost", config.m_internalPort + 1); if (!success) Thread.sleep(100); } scb.waitForResponse(); ClientResponse response = scb.getResponse(); assertTrue(response.getStatusString().contains("Unable to find down node")); localServer.shutdown(); localServer.join(); } public void testWithFakeSecondHostMessenger() throws Exception { for (int i = 0; failNext(i); i++); }*/ public void testRejoin() throws Exception { VoltProjectBuilder builder = getBuilderForTest(); LocalCluster cluster = new LocalCluster("rejoin.jar", 1, 2, 1, BackendTarget.NATIVE_EE_JNI); boolean success = cluster.compile(builder, false); assertTrue(success); copyFile(builder.getPathToDeployment(), Configuration.getPathToCatalogForTest("rejoin.xml")); cluster.setHasLocalServer(false); cluster.startUp(); cluster.shutDownSingleHost(0); Thread.sleep(100); VoltDB.Configuration config = new VoltDB.Configuration(); config.m_pathToCatalog = Configuration.getPathToCatalogForTest("rejoin.jar"); config.m_pathToDeployment = Configuration.getPathToCatalogForTest("rejoin.xml"); config.m_rejoinToHostAndPort = "localhost:21213"; ServerThread localServer = new ServerThread(config); localServer.start(); localServer.waitForInitialization(); Thread.sleep(100); /*ClientResponse response; Client client; client = ClientFactory.createClient(); client.createConnection("localhost", null, null); response = client.callProcedure("InsertSinglePartition", 0); assertEquals(ClientResponse.SUCCESS, response.getStatus()); response = client.callProcedure("Insert", 1); assertEquals(ClientResponse.SUCCESS, response.getStatus()); client.close(); client = ClientFactory.createClient(); client.createConnection("localhost", 21213, null, null); response = client.callProcedure("InsertSinglePartition", 2); assertEquals(ClientResponse.SUCCESS, response.getStatus()); response = client.callProcedure("Insert", 3); assertEquals(ClientResponse.SUCCESS, response.getStatus()); client.close();*/ localServer.shutdown(); cluster.shutDown(); } }
package seedu.todo.guitests; import static org.junit.Assert.*; import static seedu.todo.testutil.AssertUtil.*; import java.time.LocalDateTime; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import seedu.todo.commons.util.DateUtil; import seedu.todo.controllers.UpdateController; import seedu.todo.models.Event; import seedu.todo.models.Task; public class UpdateCommandTest extends GuiTest { // Fixtures private LocalDateTime twoDaysFromNow = LocalDateTime.now().plusDays(2); private String twoDaysFromNowString = DateUtil.formatDate(twoDaysFromNow); private String twoDaysFromNowIsoString = DateUtil.formatIsoDate(twoDaysFromNow); private Event testEvent = new Event(); private Task testTask = new Task(); @Before public void initTestCase() { testEvent = new Event(); testTask = new Task(); console.runCommand("clear"); } @Test public void updateCommand_updateTaskName_success() { // Add a task console.runCommand("add Buy milk by 2016-10-15 2pm"); // Update the task String command = "update 1 name Buy bread"; testTask.setName("Buy bread"); testTask.setDueDate(DateUtil.parseDateTime("2016-10-15 14:00:00")); assertTaskVisibleAfterCmd(command, testTask); } @Test public void updateCommand_updateTaskWithDeadlineToNewDeadline_success() { // Add a task console.runCommand("add Buy milk by 2016-10-15 2pm"); // Update the task String command = "update 1 by today 5pm"; testTask.setName("Buy milk"); testTask.setDueDate(LocalDateTime.now().toLocalDate().atTime(17, 0)); assertTaskVisibleAfterCmd(command, testTask); } @Test public void updateCommand_updateFloatingTaskToNewDeadline_success() { // Add a task console.runCommand("add Buy milk"); // Update the task String command = "update 1 by today 5pm"; testTask.setName("Buy milk"); testTask.setDueDate(LocalDateTime.now().toLocalDate().atTime(17, 0)); assertTaskVisibleAfterCmd(command, testTask); } @Ignore @Test public void updateCommand_updateTaskWithDeadlineToFloatingTask() { // TODO: Make this pass // Add a task console.runCommand("add Buy milk by today"); // Update the task String command = "update 1 nodeadline"; testTask.setName("Buy milk"); testTask.setDueDate(DateUtil.NO_DATETIME_VALUE); assertTaskVisibleAfterCmd(command, testTask); } @Test public void updateCommand_updateEventName_success() { // Add a task console.runCommand(String.format("add event Presentation from %s 2pm to %s 9pm", twoDaysFromNowString, twoDaysFromNowString)); // Update the task String command = "update 1 name Updated presentation"; testEvent.setName("Updated presentation"); testEvent.setStartDate(DateUtil.parseDateTime(String.format("%s 14:00:00", twoDaysFromNowIsoString))); testEvent.setEndDate(DateUtil.parseDateTime(String.format("%s 21:00:00", twoDaysFromNowIsoString))); assertEventVisibleAfterCmd(command, testEvent); } @Test public void updateCommand_updateEventStartDate_success() { // Add a task console.runCommand(String.format("add event Presentation from %s 2pm to %s 9pm", twoDaysFromNowString, twoDaysFromNowString)); // Update the task String command = String.format("update 1 from %s 5pm", twoDaysFromNowString); testEvent.setName("Presentation"); testEvent.setStartDate(DateUtil.parseDateTime(String.format("%s 17:00:00", twoDaysFromNowIsoString))); testEvent.setEndDate(DateUtil.parseDateTime(String.format("%s 21:00:00", twoDaysFromNowIsoString))); assertEventVisibleAfterCmd(command, testEvent); } @Test public void updateCommand_updateEventEndDate_success() { // Add a task console.runCommand(String.format("add event Presentation from %s 2pm to %s 9pm", twoDaysFromNowString, twoDaysFromNowString)); // Update the task String command = String.format("update 1 to %s 5pm", twoDaysFromNowString); testEvent.setName("Presentation"); testEvent.setStartDate(DateUtil.parseDateTime(String.format("%s 14:00:00", twoDaysFromNowIsoString))); testEvent.setEndDate(DateUtil.parseDateTime(String.format("%s 17:00:00", twoDaysFromNowIsoString))); assertEventVisibleAfterCmd(command, testEvent); } @Test public void updateCommand_missingIndex_disambiguate() { console.runCommand("add Buy milk"); console.runCommand("update"); assertEquals("update <index> [name \"<name>\"] [by \"<deadline>\"]", console.getConsoleInputText()); assertSameDisambiguationMessage(UpdateController.MESSAGE_INVALID_ITEM_OR_PARAM, console); } @Test public void updateCommand_missingUpdateParams_disambiguate() { console.runCommand("add Buy milk"); console.runCommand("update 1"); assertEquals("update 1 [name \"<name>\"] [by \"<deadline>\"]", console.getConsoleInputText()); assertSameDisambiguationMessage(null, console); } @Test public void updateCommand_missingParamType_disambiguate() { console.runCommand("add Buy milk"); console.runCommand("update 1 Buy bread"); assertEquals("update <index> [name \"<name>\"] [by \"<deadline>\"]", console.getConsoleInputText()); assertSameDisambiguationMessage(UpdateController.MESSAGE_INVALID_ITEM_OR_PARAM, console); } @Test public void updateCommand_missingParamValue_disambiguate() { console.runCommand("add Buy milk"); console.runCommand("update 1 name"); assertEquals("update 1 [name \"<name>\"] [by \"<deadline>\"]", console.getConsoleInputText()); assertSameDisambiguationMessage(null, console); } @Test public void updateCommand_invalidIndex_disambiguate() { console.runCommand("add Buy milk"); console.runCommand("update 2 name Buy bread"); assertEquals("update 2 [name \"Buy bread\"] [by \"<deadline>\"]", console.getConsoleInputText()); assertSameDisambiguationMessage(UpdateController.MESSAGE_INVALID_ITEM_OR_PARAM, console); } @Test public void updateCommand_invalidDate_disambiguate() { console.runCommand(String.format("add Buy milk by %s", twoDaysFromNowIsoString)); console.runCommand("update 1 by invaliddate"); assertEquals("update 1 [name \"<name>\"] [by \"invaliddate\"]", console.getConsoleInputText()); assertSameDisambiguationMessage(UpdateController.MESSAGE_CANNOT_PARSE_DATE, console); } @Test public void updateEvent_endBeforeStart_disambiguate() { console.runCommand(String.format("add event Presentation from %s 2pm to %s 9pm", twoDaysFromNowIsoString, twoDaysFromNowIsoString)); console.runCommand("update 1 from today 9pm to today 2pm"); assertEquals("update 1 [name \"<name>\"] [from \"today 9pm\" to \"today 2pm\"]", console.getConsoleInputText()); assertSameDisambiguationMessage(null, console); } @Test public void updateTask_withStartEndDate_disambiguate() { console.runCommand(String.format("add Buy milk", twoDaysFromNowIsoString, twoDaysFromNowIsoString)); console.runCommand("update 1 from 2pm to today 9pm"); assertEquals("update 1 [name \"<name>\"] [by \"2pm\"]", console.getConsoleInputText()); assertSameDisambiguationMessage(null, console); } }
package io; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.List; import blocks.BlockedFile; import main.Core; import main.Utils; public class FileWatcher implements Runnable { private WatchKey watchKey; public FileWatcher() { Path regDir = Paths.get(Utils.defineDir()); try { WatchService fileWatcher = regDir.getFileSystem().newWatchService(); watchKey = regDir.register(fileWatcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); } catch (Exception e) { e.printStackTrace(); } Utils.print(this, "FileWatcher registered to normal directory"); } public void run() { while(true) { List<WatchEvent<?>> events = watchKey.pollEvents(); for(WatchEvent<?> we : events) { if(we.kind() == StandardWatchEventKinds.ENTRY_CREATE) { System.out.println("Created: " + we.context().toString()); new BlockedFile(Utils.defineDir() + "/" + we.context().toString()); Core.mainWindow.updateLibrary(); } if(we.kind() == StandardWatchEventKinds.ENTRY_DELETE) { System.out.println("Deleted: " + we.context().toString()); for(int i=0; i < Core.blockDex.size(); i++) { if(Core.blockDex.get(i).getName().equals(we.context().toString())) { Core.blockDex.remove(i); Core.mainWindow.updateLibrary(); break; } } } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package thredds.server.root; import org.springframework.web.servlet.mvc.AbstractController; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import thredds.servlet.DataRootHandler; import thredds.server.config.TdsContext; import thredds.server.views.InvCatalogXmlView; import thredds.server.views.FileView; import thredds.catalog.InvCatalog; import java.io.File; /** * _more_ * * @author edavis * @since 4.0 */ public class XmlController extends AbstractController { // private static org.slf4j.Logger log = // org.slf4j.LoggerFactory.getLogger( XmlController.class ); private TdsContext tdsContext; public void setTdsContext( TdsContext tdsContext ) { this.tdsContext = tdsContext; } protected ModelAndView handleRequestInternal( HttpServletRequest req, HttpServletResponse res ) throws Exception { String path = req.getServletPath(); DataRootHandler drh = DataRootHandler.getInstance(); InvCatalog cat = drh.getCatalog( path, null ); if ( cat == null ) { File publicFile = tdsContext.getPublicDocFileSource().getFile( path ); if ( publicFile == null ) { tdsContext.getDefaultRequestDispatcher().forward( req, res); return null; } return new ModelAndView( new FileView(), "file", publicFile); } return new ModelAndView( new InvCatalogXmlView(), "catalog", cat); } }
package jolie.net; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.server.rpc.RPC; import com.google.gwt.user.server.rpc.RPCRequest; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URLEncoder; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import jolie.lang.Constants; import jolie.Interpreter; import jolie.net.http.HttpMessage; import jolie.net.http.HttpParser; import jolie.net.http.HttpUtils; import jolie.net.http.JolieGWTConverter; import jolie.net.http.MultiPartFormDataParser; import jolie.net.protocols.SequentialCommProtocol; import jolie.runtime.ByteArray; import jolie.runtime.InputOperation; import jolie.runtime.InvalidIdException; import jolie.runtime.Value; import jolie.runtime.ValueVector; import jolie.runtime.VariablePath; import jolie.xml.XmlUtils; import joliex.gwt.client.JolieService; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * HTTP protocol implementation * @author Fabrizio Montesi */ public class HttpProtocol extends SequentialCommProtocol { private static class Parameters { private static String DEBUG = "debug"; } private String inputId = null; final private Transformer transformer; final private DocumentBuilderFactory docBuilderFactory; final private DocumentBuilder docBuilder; final private URI uri; private boolean received = false; final public static String CRLF = new String( new char[] { 13, 10 } ); public String name() { return "http"; } public HttpProtocol( VariablePath configurationPath, URI uri, TransformerFactory transformerFactory, DocumentBuilderFactory docBuilderFactory, DocumentBuilder docBuilder ) throws TransformerConfigurationException { super( configurationPath ); this.uri = uri; this.transformer = transformerFactory.newTransformer(); this.docBuilderFactory = docBuilderFactory; this.docBuilder = docBuilder; transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" ); } private void valueToDocument( Value value, Node node, Document doc ) { node.appendChild( doc.createTextNode( value.strValue() ) ); Element currentElement; for( Entry< String, ValueVector > entry : value.children().entrySet() ) { if ( !entry.getKey().startsWith( "@" ) ) { for( Value val : entry.getValue() ) { currentElement = doc.createElement( entry.getKey() ); node.appendChild( currentElement ); Map< String, ValueVector > attrs = jolie.xml.XmlUtils.getAttributesOrNull( val ); if ( attrs != null ) { for( Entry< String, ValueVector > attrEntry : attrs.entrySet() ) { currentElement.setAttribute( attrEntry.getKey(), attrEntry.getValue().first().strValue() ); } } valueToDocument( val, currentElement, doc ); } } } } private final static String BOUNDARY = "----Jol13H77p$$Bound4r1$$"; private static void send_appendCookies( CommMessage message, String hostname, StringBuilder headerBuilder ) { ValueVector cookieVec = message.value().getChildren( Constants.Predefined.COOKIES.token().content() ); StringBuilder cookieSB = new StringBuilder(); String domain; // TODO check for cookie expiration for( Value v : cookieVec ) { domain = v.getChildren( "domain" ).first().strValue(); if ( domain.isEmpty() || (!domain.isEmpty() && hostname.endsWith( domain )) ) { cookieSB.append( v.getChildren( "name" ).first().strValue() + "=" + v.getChildren( "value" ).first().strValue() + "; " ); } } if ( cookieSB.length() > 0 ) { headerBuilder.append( "Cookie: " ); headerBuilder.append( cookieSB ); headerBuilder.append( CRLF ); } } private static void send_appendSetCookieHeader( CommMessage message, StringBuilder headerBuilder ) { ValueVector cookieVec = message.value().getChildren( Constants.Predefined.COOKIES.token().content() ); // TODO check for cookie expiration for( Value v : cookieVec ) { headerBuilder.append( "Set-Cookie: " + v.getFirstChild( "name" ).strValue() + "=" + v.getFirstChild( "value" ).strValue() + "; " + "expires=" + v.getFirstChild( "expires" ).strValue() + "; " + "path=" + v.getFirstChild( "path" ).strValue() + "; " + "domain=" + v.getFirstChild( "domain" ).strValue() + ( (v.getFirstChild( "secure" ).intValue() > 0) ? "; secure" : "" ) + CRLF ); } } private String requestFormat = null; private static CharSequence parseAlias( String alias, Value value, String charset ) throws IOException { int offset = 0; String currStrValue; String currKey; StringBuilder result = new StringBuilder( alias ); Matcher m = Pattern.compile( "%\\{[^\\}]*\\}" ).matcher( alias ); while( m.find() ) { currKey = alias.substring( m.start()+2, m.end()-1 ); currStrValue = URLEncoder.encode( value.getFirstChild( currKey ).strValue(), charset ); result.replace( m.start() + offset, m.end() + offset, currStrValue ); offset += currStrValue.length() - 3 - currKey.length(); } return result; } private String send_getCharset( CommMessage message ) { String charset = "UTF8"; if ( message.value().hasChildren( jolie.lang.Constants.Predefined.CHARSET.token().content() ) ) { charset = message.value().getFirstChild( jolie.lang.Constants.Predefined.CHARSET.token().content() ).strValue(); } else if ( hasParameter( "charset" ) ) { charset = getStringParameter( "charset" ); } return charset; } private String send_getFormat( CommMessage message ) { String format = "xml"; if ( received && requestFormat != null ) { format = requestFormat; requestFormat = null; } else if ( message.value().hasChildren( jolie.lang.Constants.Predefined.FORMAT.token().content() ) ) { format = message.value().getFirstChild( jolie.lang.Constants.Predefined.FORMAT.token().content() ).strValue(); } else if ( hasParameter( "format" ) ) { format = getStringParameter( "format" ); } return format; } private class EncodedContent { private ByteArray content = null; private String contentType = null; } private EncodedContent send_encodeContent( CommMessage message, String charset, String format ) throws IOException { if ( charset == null ) { charset = "UTF8"; } EncodedContent ret = new EncodedContent(); if ( "xml".equals( format ) ) { Document doc = docBuilder.newDocument(); Element root = doc.createElement( message.operationName() + (( received ) ? "Response" : "") ); doc.appendChild( root ); valueToDocument( message.value(), root, doc ); Source src = new DOMSource( doc ); ByteArrayOutputStream tmpStream = new ByteArrayOutputStream(); Result dest = new StreamResult( tmpStream ); try { transformer.transform( src, dest ); } catch( TransformerException e ) { throw new IOException( e ); } ret.content = new ByteArray( tmpStream.toByteArray() ); ret.contentType = "text/xml"; } else if ( "binary".equals( format ) ) { if ( message.value().isByteArray() ) { ret.content = (ByteArray)message.value().valueObject(); ret.contentType = "application/octet-stream"; } } else if ( "html".equals( format ) ) { ret.content = new ByteArray( message.value().strValue().getBytes( charset ) ); ret.contentType = "text/html"; } else if ( "multipart/form-data".equals( format ) ) { ret.contentType = "multipart/form-data; boundary=" + BOUNDARY; StringBuilder builder = new StringBuilder(); for( Entry< String, ValueVector > entry : message.value().children().entrySet() ) { if ( !entry.getKey().startsWith( "@" ) ) { builder.append( "--" + BOUNDARY + CRLF ); builder.append( "Content-Disposition: form-data; name=\"" + entry.getKey() + '\"' + CRLF + CRLF ); builder.append( entry.getValue().first().strValue() + CRLF ); } } builder.append( "--" + BOUNDARY + "--" ); ret.content = new ByteArray( builder.toString().getBytes( charset ) ); } else if ( "x-www-form-urlencoded".equals( format ) ) { ret.contentType = "x-www-form-urlencoded"; Iterator< Entry< String, ValueVector > > it = message.value().children().entrySet().iterator(); Entry< String, ValueVector > entry; StringBuilder builder = new StringBuilder(); while( it.hasNext() ) { entry = it.next(); builder.append( entry.getKey() + "=" + URLEncoder.encode( entry.getValue().first().strValue(), "UTF-8" ) ); if ( it.hasNext() ) { builder.append( '&' ); } } ret.content = new ByteArray( builder.toString().getBytes( charset ) ); } else if ( "text/x-gwt-rpc".equals( format ) ) { try { if ( message.isFault() ) { ret.content = new ByteArray( RPC.encodeResponseForFailure( JolieService.class.getMethods()[0], JolieGWTConverter.jolieToGwtFault( message.fault() ) ).getBytes( charset ) ); } else { joliex.gwt.client.Value v = new joliex.gwt.client.Value(); JolieGWTConverter.jolieToGwtValue( message.value(), v ); ret.content = new ByteArray( RPC.encodeResponseForSuccess( JolieService.class.getMethods()[0], v ).getBytes( charset ) ); } } catch( SerializationException e ) { throw new IOException( e ); } } return ret; } private void send_appendResponseHeaders( CommMessage message, StringBuilder headerBuilder ) { String redirect = message.value().getFirstChild( Constants.Predefined.REDIRECT.token().content() ).strValue(); if ( redirect.isEmpty() ) { headerBuilder.append( "HTTP/1.1 200 OK" + CRLF ); } else { headerBuilder.append( "HTTP/1.1 303 See Other" + CRLF ); headerBuilder.append( "Location: " + redirect + CRLF ); } send_appendSetCookieHeader( message, headerBuilder ); } private void send_appendRequestMethod( StringBuilder headerBuilder ) { if ( hasParameter( "method" ) ) { headerBuilder.append( getStringParameter( "method" ).toUpperCase() ); } else { headerBuilder.append( "GET" ); } } private void send_appendRequestPath( CommMessage message, StringBuilder headerBuilder, String charset ) throws IOException { if ( uri.getPath().length() < 1 || uri.getPath().charAt( 0 ) != '/' ) { headerBuilder.append( '/' ); } headerBuilder.append( uri.getPath() ); /*if ( uri.toString().endsWith( "/" ) == false ) { headerBuilder.append( '/' ); }*/ if ( hasParameter( "aliases" ) && getParameterFirstValue( "aliases" ).hasChildren( message.operationName() ) ) { headerBuilder.append( parseAlias( getParameterFirstValue( "aliases" ).getFirstChild( message.operationName() ).strValue(), message.value(), charset ) ); } else { headerBuilder.append( message.operationName() ); } } private static void send_appendAuthorizationHeader( CommMessage message, StringBuilder headerBuilder ) { if ( message.value().hasChildren( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ) ) { Value v = message.value().getFirstChild( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ); //String realm = v.getFirstChild( "realm" ).strValue(); String userpass = v.getFirstChild( "userid" ).strValue() + ":" + v.getFirstChild( "password" ).strValue(); sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder(); userpass = encoder.encode( userpass.getBytes() ); headerBuilder.append( "Authorization: Basic " + userpass + CRLF ); } } private void send_appendRequestHeaders( CommMessage message, StringBuilder headerBuilder, String charset ) throws IOException { send_appendRequestMethod( headerBuilder ); headerBuilder.append( ' ' ); send_appendRequestPath( message, headerBuilder, charset ); headerBuilder.append( " HTTP/1.1" + CRLF ); headerBuilder.append( "Host: " + uri.getHost() + CRLF ); send_appendCookies( message, uri.getHost(), headerBuilder ); send_appendAuthorizationHeader( message, headerBuilder ); } private void send_appendGenericHeaders( CommMessage message, EncodedContent encodedContent, String charset, StringBuilder headerBuilder ) { String param; if ( checkBooleanParameter( "keepAlive" ) == false || channel().toBeClosed() ) { channel().setToBeClosed( true ); headerBuilder.append( "Connection: close" + CRLF ); } if ( encodedContent.content != null ) { param = message.value().getFirstChild( jolie.lang.Constants.Predefined.CONTENT_TYPE.token().content() ).strValue(); if ( !param.isEmpty() ) { encodedContent.contentType = param; } headerBuilder.append( "Content-Type: " + encodedContent.contentType ); if ( charset != null ) { headerBuilder.append( "; charset=" + charset.toLowerCase() ); } headerBuilder.append( CRLF ); param = message.value().getFirstChild( jolie.lang.Constants.Predefined.CONTENT_TRANSFER_ENCODING.token().content() ).strValue(); if ( !param.isEmpty() ) { headerBuilder.append( "Content-Transfer-Encoding: " + param + CRLF ); } headerBuilder.append( "Content-Length: " + (encodedContent.content.size() + 2) + CRLF ); } else { headerBuilder.append( "Content-Length: 0" + CRLF ); } } private void send_logDebugInfo( CharSequence header, EncodedContent encodedContent ) { if ( checkBooleanParameter( "debug" ) ) { StringBuilder debugSB = new StringBuilder(); debugSB.append( "[HTTP debug] Sending:\n" ); debugSB.append( header ); if ( getParameterVector( "debug" ).first().getFirstChild( "showContent" ).intValue() > 0 && encodedContent.content != null ) { debugSB.append( encodedContent.content.toString() ); } Interpreter.getInstance().logInfo( debugSB.toString() ); } } public void send( OutputStream ostream, CommMessage message, InputStream istream ) throws IOException { String charset = send_getCharset( message ); String format = send_getFormat( message ); EncodedContent encodedContent = send_encodeContent( message, charset, format ); StringBuilder headerBuilder = new StringBuilder(); if ( received ) { // We're responding to a request send_appendResponseHeaders( message, headerBuilder ); received = false; } else { // We're sending a notification or a solicit send_appendRequestHeaders( message, headerBuilder, charset ); } send_appendGenericHeaders( message, encodedContent, charset, headerBuilder ); headerBuilder.append( CRLF ); send_logDebugInfo( headerBuilder, encodedContent ); inputId = message.operationName(); if ( charset == null ) { charset = "UTF8"; } ostream.write( headerBuilder.toString().getBytes( charset ) ); if ( encodedContent.content != null ) { ostream.write( encodedContent.content.getBytes() ); ostream.write( CRLF.getBytes( charset ) ); } } private void parseXML( HttpMessage message, Value value ) throws IOException { try { if ( message.size() > 0 ) { DocumentBuilder builder = docBuilderFactory.newDocumentBuilder(); InputSource src = new InputSource( new ByteArrayInputStream( message.content() ) ); Document doc = builder.parse( src ); XmlUtils.documentToValue( doc, value ); } } catch( ParserConfigurationException pce ) { throw new IOException( pce ); } catch( SAXException saxe ) { throw new IOException( saxe ); } } private static void parseForm( HttpMessage message, Value value ) throws IOException { String line = new String( message.content(), "UTF8" ); String[] s, pair; s = line.split( "&" ); for( int i = 0; i < s.length; i++ ) { pair = s[i].split( "=", 2 ); value.getChildren( pair[0] ).first().setValue( pair[1] ); } } private static void parseMultiPartFormData( HttpMessage message, Value value ) throws IOException { MultiPartFormDataParser parser = new MultiPartFormDataParser( message, value ); parser.parse(); } private static String parseGWTRPC( HttpMessage message, Value value ) throws IOException { RPCRequest request = RPC.decodeRequest( new String( message.content(), "UTF8" ) ); String operationName = (String)request.getParameters()[0]; joliex.gwt.client.Value requestValue = (joliex.gwt.client.Value)request.getParameters()[1]; JolieGWTConverter.gwtToJolieValue( requestValue, value ); return operationName; } private static void recv_checkForSetCookie( HttpMessage message, Value value ) { ValueVector cookieVec = value.getChildren( Constants.Predefined.COOKIES.token().content() ); Value currValue; for( HttpMessage.Cookie cookie : message.setCookies() ) { currValue = Value.create(); currValue.getNewChild( "expires" ).setValue( cookie.expirationDate() ); currValue.getNewChild( "path" ).setValue( cookie.path() ); currValue.getNewChild( "name" ).setValue( cookie.name() ); currValue.getNewChild( "value" ).setValue( cookie.value() ); currValue.getNewChild( "domain" ).setValue( cookie.domain() ); currValue.getNewChild( "secure" ).setValue( (cookie.secure() ? 1 : 0) ); cookieVec.add( currValue ); } } private static void recv_checkForCookies( HttpMessage message, Value value ) { ValueVector cookieVec = value.getChildren( Constants.Predefined.COOKIES.token().content() ); Value v; for( Entry< String, String > entry : message.cookies().entrySet() ) { v = Value.create(); v.getNewChild( "name" ).setValue( entry.getKey() ); v.getNewChild( "value" ).setValue( entry.getValue() ); cookieVec.add( v ); } } private static void recv_parseQueryString( HttpMessage message, Value value ) { if ( message.requestPath() != null ) { try { Value qsValue = value.getFirstChild( Constants.Predefined.QUERY_STRING.token().content() ); String qs = message.requestPath().split( "\\?" )[1]; String[] params = qs.split( "&" ); for( String param : params ) { String[] kv = param.split( "=" ); qsValue.getNewChild( kv[0] ).setValue( kv[1] ); } } catch( ArrayIndexOutOfBoundsException e ) {} } } // Print debug information about a received message private void recv_logDebugInfo( HttpMessage message ) { StringBuilder debugSB = new StringBuilder(); debugSB.append( "[HTTP debug] Receiving:\n" ); debugSB.append( "HTTP Code: " + message.httpCode() + "\n" ); debugSB.append( "Resource: " + message.requestPath() + "\n" ); debugSB.append( "--> Header properties\n" ); for( Entry< String, String > entry : message.properties() ) { debugSB.append( '\t' + entry.getKey() + ": " + entry.getValue() + '\n' ); } for( HttpMessage.Cookie cookie : message.setCookies() ) { debugSB.append( "\tset-cookie: " + cookie.toString() + '\n' ); } for( Entry< String, String > entry : message.cookies().entrySet() ) { debugSB.append( "\tcookie: " + entry.getKey() + '=' + entry.getValue() + '\n' ); } if ( getParameterFirstValue( "debug" ).getFirstChild( "showContent" ).intValue() > 0 && message.content() != null ) { debugSB.append( "--> Message content\n" ); debugSB.append( new String( message.content() ) ); } Interpreter.getInstance().logInfo( debugSB.toString() ); } private void recv_parseMessage( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { String format = "xml"; if ( hasParameter( "format" ) ) { format = getStringParameter( "format" ); } String type = message.getProperty( "content-type" ).split( ";" )[0]; if ( "text/html".equals( type ) ) { decodedMessage.value.setValue( new String( message.content() ) ); } else if ( "application/x-www-form-urlencoded".equals( type ) ) { parseForm( message, decodedMessage.value ); } else if ( "text/xml".equals( type ) || "rest".equals( format ) ) { parseXML( message, decodedMessage.value ); } else if ( "text/x-gwt-rpc".equals( type ) ) { decodedMessage.operationName = parseGWTRPC( message, decodedMessage.value ); requestFormat = "text/x-gwt-rpc"; } else if ( "multipart/form-data".equals( type ) ) { parseMultiPartFormData( message, decodedMessage.value ); } else { decodedMessage.value.setValue( new String( message.content() ) ); } } private void recv_checkReceivingOperation( HttpMessage message, DecodedMessage decodedMessage ) { if ( decodedMessage.operationName == null ) { decodedMessage.operationName = message.requestPath().split( "\\?" )[0]; } InputOperation op = null; try { op = Interpreter.getInstance().getInputOperation( decodedMessage.operationName ); } catch( InvalidIdException e ) {} if ( op == null || !channel().parentListener().canHandleInputOperation( op ) ) { String defaultOpId = getParameterVector( "default" ).first().strValue(); if ( defaultOpId.length() > 0 ) { Value body = decodedMessage.value; decodedMessage.value = Value.create(); decodedMessage.value.getChildren( "data" ).add( body ); decodedMessage.value.getChildren( "operation" ).first().setValue( decodedMessage.operationName ); decodedMessage.operationName = defaultOpId; } } } private static void recv_checkForMessageProperties( HttpMessage message, Value messageValue ) { recv_checkForCookies( message, messageValue ); String property; if ( (property=message.getProperty( "user-agent" )) != null ) { messageValue.getNewChild( Constants.Predefined.USER_AGENT.token().content() ).setValue( property ); } } private class DecodedMessage { private String operationName = null; private Value value = Value.create(); } public CommMessage recv( InputStream istream, OutputStream ostream ) throws IOException { CommMessage retVal = null; DecodedMessage decodedMessage = new DecodedMessage(); HttpMessage message = new HttpParser( istream ).parse(); if ( hasParameter( "keepAlive" ) ) { channel().setToBeClosed( checkBooleanParameter( "keepAlive" ) == false ); } else { HttpUtils.recv_checkForChannelClosing( message, channel() ); } if ( checkBooleanParameter( Parameters.DEBUG ) ) { recv_logDebugInfo( message ); } if ( message.size() > 0 ) { recv_parseMessage( message, decodedMessage ); } if ( message.isResponse() ) { recv_checkForSetCookie( message, decodedMessage.value ); retVal = new CommMessage( inputId, "/", decodedMessage.value ); received = false; } else if ( !message.isError() ) { recv_parseQueryString( message, decodedMessage.value ); recv_checkReceivingOperation( message, decodedMessage ); recv_checkForMessageProperties( message, decodedMessage.value ); //TODO support resourcePath retVal = new CommMessage( decodedMessage.operationName, "/", decodedMessage.value ); received = true; } return retVal; } }
package org.smbarbour.mcu.util; import java.net.*; import j7compat.Files; //import java.nio.charset.StandardCharsets; //import java.nio.file.Files; //import java.nio.file.Path; //import java.nio.file.StandardCopyOption; //import java.nio.file.StandardOpenOption; import j7compat.Path; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.UUID; import java.awt.image.BufferedImage; import java.io.*; import javax.swing.ImageIcon; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FileUtils; import org.smbarbour.mcu.MCUApp; import org.smbarbour.mcu.Version; import org.smbarbour.mcu.util.Archive; import org.w3c.dom.*; public class MCUpdater { //private List<Module> modList = new ArrayList<Module>(); private Path MCFolder; private Path archiveFolder; private Path instanceRoot; private MCUApp parent; private String sep = System.getProperty("file.separator"); public MessageDigest md5; public ImageIcon defaultIcon; private String newestMC = ""; private Map<String,String> versionMap = new HashMap<String,String>(); private static MCUpdater INSTANCE; public static File getJarFile() { try { return new File(MCUpdater.class.getProtectionDomain().getCodeSource().getLocation().toURI()); } catch (URISyntaxException e) { e.printStackTrace(); } return null; } public static MCUpdater getInstance() { if( INSTANCE == null ) { INSTANCE = new MCUpdater(); } return INSTANCE; } public static String cpDelimiter() { String osName = System.getProperty("os.name"); if (osName.startsWith("Windows")) { return ";"; } else { return ":"; } } private MCUpdater() { try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } if(System.getProperty("os.name").startsWith("Windows")) { MCFolder = new Path(System.getenv("APPDATA")).resolve(".minecraft"); archiveFolder = new Path(System.getenv("APPDATA")).resolve(".MCUpdater"); } else if(System.getProperty("os.name").startsWith("Mac")) { MCFolder = new Path(System.getProperty("user.home")).resolve("Library").resolve("Application Support").resolve("minecraft"); archiveFolder = new Path(System.getProperty("user.home")).resolve("Library").resolve("Application Support").resolve("MCUpdater"); } else { MCFolder = new Path(System.getProperty("user.home")).resolve(".minecraft"); archiveFolder = new Path(System.getProperty("user.home")).resolve(".MCUpdater"); } try { defaultIcon = new ImageIcon(MCUpdater.class.getResource("/minecraft.png")); } catch( NullPointerException e ) { _debug( "Unable to load default icon?!" ); defaultIcon = new ImageIcon(new BufferedImage(32,32,BufferedImage.TYPE_INT_ARGB)); } // configure the download cache try { DownloadCache.init(archiveFolder.resolve("cache").toFile()); } catch (IllegalArgumentException e) { _debug( "Suppressed attempt to re-init download cache?!" ); } try { long start = System.currentTimeMillis(); URL md5s = new URL("http://files.mcupdater.com/md5.dat"); InputStreamReader input = new InputStreamReader(md5s.openStream()); BufferedReader buffer = new BufferedReader(input); String currentLine = null; while(true){ currentLine = buffer.readLine(); if(currentLine != null){ String entry[] = currentLine.split("\\|"); versionMap.put(entry[0], entry[1]); newestMC = entry[1]; // Most recent entry in md5.dat is the current release } else { break; } } buffer.close(); input.close(); _debug("Took "+(System.currentTimeMillis()-start)+"ms to load md5.dat"); _debug("newest Minecraft in md5.dat: " + newestMC); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public MCUApp getParent() { return parent; } public void setParent(MCUApp parent) { this.parent = parent; } public void writeServerList(List<ServerList> serverlist) { try { archiveFolder.toFile().mkdirs(); BufferedWriter writer = Files.newBufferedWriter(archiveFolder.resolve("mcuServers.dat")); Iterator<ServerList> it = serverlist.iterator(); Set<String> urls = new HashSet<String>(); while(it.hasNext()) { ServerList entry = it.next(); urls.add(entry.getPackUrl()); } Iterator<String> urlIterator = urls.iterator(); while (urlIterator.hasNext()) { writer.write(urlIterator.next()); writer.newLine(); } writer.close(); } catch( IOException x) { x.printStackTrace(); } } public List<Backup> loadBackupList() { List<Backup> bList = new ArrayList<Backup>(); try { BufferedReader reader = Files.newBufferedReader(archiveFolder.resolve("mcuBackups.dat")); String entry = reader.readLine(); while(entry != null) { String[] ele = entry.split("~~~~~"); bList.add(new Backup(ele[0], ele[1])); entry = reader.readLine(); } reader.close(); return bList; } catch(FileNotFoundException notfound) { _debug("File not found"); } catch(IOException ioe) { ioe.printStackTrace(); } return bList; } public void writeBackupList(List<Backup> backupList) { try { BufferedWriter writer = Files.newBufferedWriter(archiveFolder.resolve("mcuBackups.dat")); Iterator<Backup> it = backupList.iterator(); while(it.hasNext()) { Backup entry = it.next(); writer.write(entry.getDescription() + "~~~~~" + entry.getFilename()); writer.newLine(); } writer.close(); } catch(IOException ioe) { ioe.printStackTrace(); } } public List<ServerList> loadServerList(String defaultUrl) { List<ServerList> slList = new ArrayList<ServerList>(); try { Set<String> urls = new HashSet<String>(); urls.add(defaultUrl); BufferedReader reader = Files.newBufferedReader(archiveFolder.resolve("mcuServers.dat")); String entry = reader.readLine(); while(entry != null) { urls.add(entry); entry = reader.readLine(); } reader.close(); Iterator<String> it = urls.iterator(); while (it.hasNext()){ String serverUrl = it.next(); try { Element docEle = null; Document serverHeader = ServerPackParser.readXmlFromUrl(serverUrl); if (!(serverHeader == null)) { Element parent = serverHeader.getDocumentElement(); if (parent.getNodeName().equals("ServerPack")){ String mcuVersion = parent.getAttribute("version"); NodeList servers = parent.getElementsByTagName("Server"); for (int i = 0; i < servers.getLength(); i++){ docEle = (Element)servers.item(i); ServerList sl = new ServerList(docEle.getAttribute("id"), docEle.getAttribute("name"), serverUrl, docEle.getAttribute("newsUrl"), docEle.getAttribute("iconUrl"), docEle.getAttribute("version"), docEle.getAttribute("serverAddress"), ServerPackParser.parseBoolean(docEle.getAttribute("generateList")), docEle.getAttribute("revision")); sl.setMCUVersion(mcuVersion); slList.add(sl); } } else { slList.add(new ServerList(parent.getAttribute("id"), parent.getAttribute("name"), serverUrl, parent.getAttribute("newsUrl"), parent.getAttribute("iconUrl"), parent.getAttribute("version"), parent.getAttribute("serverAddress"), ServerPackParser.parseBoolean(parent.getAttribute("generateList")), parent.getAttribute("revision"))); } } else { _log("Unable to get server information from " + serverUrl); } } catch (Exception e) { e.printStackTrace(); } } // String[] arrString = entry.split("\\|"); // slList.add(new ServerList(arrString[0], arrString[1], arrString[2])); return slList; } catch( FileNotFoundException notfound) { _debug("File not found"); } catch (IOException x) { x.printStackTrace(); } return slList; } public Path getMCFolder() { return MCFolder; } public Path getArchiveFolder() { return archiveFolder; } public Path getInstanceRoot() { return instanceRoot; } public void setInstanceRoot(Path instanceRoot) { this.instanceRoot = instanceRoot; } public String getMCVersion() { File jar = MCFolder.resolve("bin").resolve("minecraft.jar").toFile(); byte[] hash; try { InputStream is = new FileInputStream(jar); hash = DigestUtils.md5(is); is.close(); } catch (FileNotFoundException e) { //e.printStackTrace(); return "Not found"; } catch (IOException e) { e.printStackTrace(); return "Error reading file"; } String hashString = new String(Hex.encodeHex(hash)); String version = lookupHash(hashString); if(!version.isEmpty()) { File backupJar = archiveFolder.resolve("mc-" + version + ".jar").toFile(); if(!backupJar.exists()) { backupJar.getParentFile().mkdirs(); copyFile(jar, backupJar); } return version; } else { return "Unknown version"; } } private String lookupHash(String hash) { String out = versionMap.get(hash); if (out == null) { out = ""; } return out; } private void copyFile(File jar, File backupJar) { try { InputStream in = new FileInputStream(jar); OutputStream out = new FileOutputStream(backupJar); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } catch(IOException ioe) { ioe.printStackTrace(); } } public void saveConfig(String description) { File folder = MCFolder.toFile(); List<File> contents = recurseFolder(folder, false); try { String uniqueName = UUID.randomUUID().toString() + ".zip"; Iterator<File> it = new ArrayList<File>(contents).iterator(); while(it.hasNext()) { File entry = it.next(); if(getExcludedNames(entry.getPath(), false) || entry.getPath().contains("temp")){ contents.remove(entry); } } Archive.createZip(archiveFolder.resolve(uniqueName).toFile(), contents, MCFolder, parent); Backup entry = new Backup(description, uniqueName); _debug("DEBUG: LoadBackupList"); List<Backup> bList = loadBackupList(); _debug("DEBUG: add"); bList.add(entry); _debug("DEBUG: writeBackupList"); writeBackupList(bList); } catch (IOException e) { e.printStackTrace(); } } private boolean getExcludedNames(String path, boolean forDelete) { if(path.contains("mcu" + sep)) { // never delete from the mcu folder return true; } if (path.contains("mods") && (path.contains(".zip") || path.contains(".jar"))) { // always delete mods in archive form return false; } if(path.contains("bin" + sep + "minecraft.jar")) { // always delete bin/minecraft.jar return false; } if(path.contains("bin" + sep)) { // never delete anything else in bin/ return true; } if(path.contains("resources") && !path.contains("mods")) { // never delete resources unless it is under the mods directory return true; } if(path.contains("saves")) { // never delete saves return true; } if(path.contains("screenshots")) { // never delete screenshots return true; } if(path.contains("stats")) { return true; } if(path.contains("texturepacks")) { return true; } if(path.contains("lastlogin")) { return true; } if(path.contains("mcuServers.dat")) { return true; } if(path.contains("instance.dat")) { return true; } if(path.contains("minecraft.jar")) { return true; } if(path.contains("options.txt")) { return forDelete; } if(path.contains("META-INF" + sep)) { return true; } // Temporary hardcoding of client specific mod configs (i.e. Don't clobber on update) if(path.contains("rei_minimap" + sep)) { return true; } if(path.contains("macros" + sep)) { return true; } if(path.contains("InvTweaks")) { return true; } if(path.contains("optionsof.txt")){ return true; } return false; } private List<File> recurseFolder(File folder, boolean includeFolders) { List<File> output = new ArrayList<File>(); List<File> input = new ArrayList<File>(Arrays.asList(folder.listFiles())); Iterator<File> fi = input.iterator(); if(includeFolders) { output.add(folder); } while(fi.hasNext()) { File entry = fi.next(); if(entry.isDirectory()) { List<File> subfolder = recurseFolder(entry, includeFolders); Iterator<File> sfiterator = subfolder.iterator(); while(sfiterator.hasNext()) { output.add(sfiterator.next()); } } else { output.add(entry); } } return output; } public void restoreBackup(File archive) { File folder = MCFolder.toFile(); List<File> contents = recurseFolder(folder, true); Iterator<File> it = new ArrayList<File>(contents).iterator(); while(it.hasNext()) { File entry = it.next(); if(getExcludedNames(entry.getPath(), true)){ contents.remove(entry); } } ListIterator<File> liClear = contents.listIterator(contents.size()); while(liClear.hasPrevious()) { File entry = liClear.previous(); entry.delete(); } Archive.extractZip(archive, MCFolder.toFile()); } public boolean checkForBackup(ServerList server) { File jar = archiveFolder.resolve("mc-" + server.getVersion() + ".jar").toFile(); return jar.exists(); } public boolean installMods(ServerList server, List<Module> toInstall, boolean clearExisting, Properties instData) throws FileNotFoundException { if (Version.requestedFeatureLevel(server.getMCUVersion(), "2.2")) { // Sort mod list for InJar Collections.sort(toInstall, new ModuleComparator()); } Path instancePath = instanceRoot.resolve(server.getServerId()); Boolean updateJar = clearExisting; if (!instancePath.resolve("bin").resolve("minecraft.jar").toFile().exists()) { updateJar = true; } Iterator<Module> iMods = toInstall.iterator(); while (iMods.hasNext() && !updateJar) { Module current = iMods.next(); if (current.getInJar()) { if (current.getMD5().isEmpty() || (!current.getMD5().equalsIgnoreCase(instData.getProperty("mod:" + current.getId(), "NoHash")))) { updateJar = true; } } } System.out.println(instancePath.toString()); List<File> contents = recurseFolder(instancePath.toFile(), true); File jar = archiveFolder.resolve("mc-" + server.getVersion() + ".jar").toFile(); if(!jar.exists()) { parent.log("! Unable to find a backup copy of minecraft.jar for "+server.getVersion()); throw new FileNotFoundException("A backup copy of minecraft.jar for version " + server.getVersion() + " was not found."); } if (clearExisting){ parent.setStatus("Clearing existing configuration"); parent.log("Clearing existing configuration..."); Iterator<File> it = new ArrayList<File>(contents).iterator(); while(it.hasNext()) { File entry = it.next(); if(getExcludedNames(entry.getPath(), true)){ contents.remove(entry); } } ListIterator<File> liClear = contents.listIterator(contents.size()); while(liClear.hasPrevious()) { File entry = liClear.previous(); entry.delete(); } } Iterator<Module> itMods = toInstall.iterator(); File tmpFolder = archiveFolder.resolve("temp").toFile(); tmpFolder.mkdirs(); File buildJar = archiveFolder.resolve("build.jar").toFile(); if(buildJar.exists()) { buildJar.delete(); } if (updateJar) { parent.setStatus("Preparing to build minecraft.jar"); parent.log("Preparing to build minecraft.jar..."); Archive.extractZip(jar, tmpFolder); } else { parent.log("No jar changes necessary. Skipping jar rebuild."); } File branding = new File(tmpFolder, "fmlbranding.properties"); try { branding.createNewFile(); Properties propBrand = new Properties(); propBrand.setProperty("fmlbranding", "MCUpdater: " + server.getName() + " (rev " + server.getRevision() + ")"); propBrand.store(new FileOutputStream(branding), "MCUpdater ServerPack branding"); } catch (IOException e1) { e1.printStackTrace(); } int modCount = toInstall.size(); int modsLoaded = 0; int errorCount = 0; // TODO: consolidate download logic for mods & configs while(itMods.hasNext()) { Module entry = itMods.next(); parent.setStatus("Mod: " + entry.getName()); parent.log("Mod: "+entry.getName()); try { _debug("Mod @ "+entry.getUrl()); URL modURL = new URL(entry.getUrl()); //String modFilename = modURL.getFile().substring(modURL.getFile().lastIndexOf('/')); File modPath; if(entry.getInJar()) { if (updateJar) { //modPath = new File(tmpFolder.getPath() + sep + loadOrder + ".zip"); //loadOrder++; //_log(modPath.getPath()); ModDownload jarMod; try { jarMod = new ModDownload(modURL, new File(tmpFolder, (entry.getId() + ".jar")), entry.getMD5()); if( jarMod.cacheHit ) { parent.log(" Adding to jar (cached)."); } else { parent.log(" Adding to jar (downloaded)."); } _debug(jarMod.url + " -> " + jarMod.getDestFile().getPath()); //FileUtils.copyURLToFile(modURL, modPath); Archive.extractZip(jarMod.getDestFile(), tmpFolder); jarMod.getDestFile().delete(); instData.setProperty("mod:" + entry.getId(), entry.getMD5()); } catch (Exception e) { ++errorCount; parent.log("! "+e.getMessage()); e.printStackTrace(); } } else { parent.log("Skipping jar mod: " + entry.getName()); } } else if (entry.getExtract()) { //modPath = new File(tmpFolder.getPath() + sep + modFilename); //modPath.getParentFile().mkdirs(); //_log(modPath.getPath()); ModDownload extractMod; try { extractMod = new ModDownload(modURL, new File(tmpFolder, (entry.getId() + ".jar")), entry.getMD5()); if( extractMod.cacheHit ) { parent.log(" Extracting to filesystem (cached)."); } else { parent.log(" Extracting to filesystem (downloaded)."); } _debug(extractMod.url + " -> " + extractMod.getDestFile().getPath()); //FileUtils.copyURLToFile(modURL, modPath); Path destPath = instancePath; if(!entry.getInRoot()) destPath = instancePath.resolve("mods"); Archive.extractZip(extractMod.getDestFile(), destPath.toFile()); extractMod.getDestFile().delete(); } catch (Exception e) { ++errorCount; parent.log("! "+e.getMessage()); e.printStackTrace(); } } else if (entry.getCoreMod()) { modPath = instancePath.resolve("coremods").resolve(entry.getId() + ".jar").toFile(); modPath.getParentFile().mkdirs(); try { ModDownload normalMod = new ModDownload(modURL, modPath, entry.getMD5()); if( normalMod.cacheHit ) { parent.log(" Installing in /coremods (cached)."); } else { parent.log(" Installing in /coremods (downloaded)."); } _debug(normalMod.url + " -> " + normalMod.getDestFile().getPath()); } catch (Exception e) { ++errorCount; parent.log("! "+e.getMessage()); e.printStackTrace(); } } else { if (entry.getPath().equals("")){ modPath = instancePath.resolve("mods").resolve(entry.getId() + ".jar").toFile(); } else { modPath = instancePath.resolve(entry.getPath()).toFile(); } modPath.getParentFile().mkdirs(); //_log("~~~ " + modPath.getPath()); try { ModDownload normalMod = new ModDownload(modURL, modPath, entry.getMD5()); if( normalMod.cacheHit ) { parent.log(" Installing in /mods (cached)."); } else { parent.log(" Installing in /mods (downloaded)."); } _debug(normalMod.url + " -> " + normalMod.getDestFile().getPath()); } catch (Exception e) { ++errorCount; parent.log("! "+e.getMessage()); e.printStackTrace(); } //FileUtils.copyURLToFile(modURL, modPath); } Iterator<ConfigFile> itConfigs = entry.getConfigs().iterator(); while(itConfigs.hasNext()) { final ConfigFile cfEntry = itConfigs.next(); final String MD5 = cfEntry.getMD5(); _debug(cfEntry.getUrl()); URL configURL = new URL(cfEntry.getUrl()); final File confFile = instancePath.resolve(cfEntry.getPath()).toFile(); confFile.getParentFile().mkdirs(); if( MD5 != null ) { final File cacheFile = DownloadCache.getFile(MD5); if( cacheFile.exists() ) { parent.log(" Found config for "+cfEntry.getPath()+" (cached)"); FileUtils.copyFile(cacheFile, confFile); continue; } } parent.log(" Found config for "+cfEntry.getPath()+", downloading..."); _debug(confFile.getPath()); FileUtils.copyURLToFile(configURL, confFile); // save in cache for future reference if( MD5 != null ) { final boolean cached = DownloadCache.cacheFile(confFile, MD5); if( cached ) { _debug("\nSaved in cache"); } } } } catch (MalformedURLException e) { ++errorCount; parent.log("! "+e.getMessage()); _log(e.getMessage()); } catch (IOException e) { ++errorCount; parent.log("! "+e.getMessage()); e.printStackTrace(); } modsLoaded++; parent.setProgressBar((int)( (65 / modCount) * modsLoaded + 25)); parent.log(" Done ("+modsLoaded+"/"+modCount+")"); } try { buildJar.createNewFile(); } catch (IOException e) { e.printStackTrace(); } parent.log("All mods loaded."); if( errorCount > 0 ) { parent.log("WARNING: Errors were detected with this update, please verify your files. There may be a problem with the serverpack configuration or one of your download sites."); return false; } copyFile(jar, buildJar); List<File> buildList = recurseFolder(tmpFolder,true); Iterator<File> blIt = new ArrayList<File>(buildList).iterator(); while(blIt.hasNext()) { File entry = blIt.next(); if(entry.getPath().contains("META-INF")) { buildList.remove(entry); } } Path binPath = instancePath.resolve("bin"); if (!updateJar) { try { Archive.updateArchive(binPath.resolve("minecraft.jar").toFile(), new File[]{ branding }); } catch (IOException e1) { e1.printStackTrace(); } } else { parent.log("Packaging updated jar..."); try { Archive.createJar(buildJar, buildList, tmpFolder.getPath() + sep); } catch (IOException e1) { parent.log("Failed to create jar!"); parent.log(e1.getMessage()); return false; //e1.printStackTrace(); } //Archive.patchJar(jar, buildJar, new ArrayList<File>(Arrays.asList(tmpFolder.listFiles()))); //copyFile(buildJar, new File(MCFolder + sep + "bin" + sep + "minecraft.jar")); try { Files.copy(new Path(buildJar), binPath.resolve("minecraft.jar")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } List<File> tempFiles = recurseFolder(tmpFolder,true); ListIterator<File> li = tempFiles.listIterator(tempFiles.size()); while(li.hasPrevious()) { File entry = li.previous(); entry.delete(); } return true; } public void writeMCServerFile(String name, String ip, String instance) { byte[] header = new byte[]{ 0x0A,0x00,0x00,0x09,0x00,0x07,0x73,0x65,0x72,0x76,0x65,0x72,0x73,0x0A, 0x00,0x00,0x00,0x01,0x01,0x00,0x0B,0x68,0x69,0x64,0x65,0x41,0x64,0x64, 0x72,0x65,0x73,0x73,0x01,0x08,0x00,0x04,0x6E,0x61,0x6D,0x65,0x00, (byte) (name.length() + 12), (byte) 0xC2,(byte) 0xA7,0x41,0x5B,0x4D,0x43,0x55,0x5D,0x20,(byte) 0xC2,(byte) 0xA7,0x46 }; byte[] nameBytes = name.getBytes(); byte[] ipBytes = ip.getBytes(); byte[] middle = new byte[]{0x08,0x00,0x02,0x69,0x70,0x00,(byte) ip.length()}; byte[] end = new byte[]{0x00,0x00}; int size = header.length + nameBytes.length + middle.length + ipBytes.length + end.length; byte[] full = new byte[size]; int pos = 0; System.arraycopy(header, 0, full, pos, header.length); pos += header.length; System.arraycopy(nameBytes, 0, full, pos, nameBytes.length); pos += nameBytes.length; System.arraycopy(middle, 0, full, pos, middle.length); pos += middle.length; System.arraycopy(ipBytes, 0, full, pos, ipBytes.length); pos += ipBytes.length; System.arraycopy(end, 0, full, pos, end.length); File serverFile = instanceRoot.resolve(instance).resolve("servers.dat").toFile(); try { serverFile.createNewFile(); FileOutputStream fos = new FileOutputStream(serverFile); fos.write(full,0,full.length); fos.close(); } catch (IOException e) { e.printStackTrace(); } } public static void openLink(URI uri) { try { Object o = Class.forName("java.awt.Desktop").getMethod("getDesktop", new Class[0]).invoke(null, new Object[0]); o.getClass().getMethod("browse", new Class[] { URI.class }).invoke(o, new Object[] { uri }); } catch (Throwable e) { _log("Failed to open link " + uri.toString()); } } private static void _log(String msg) { if( INSTANCE.parent != null ) { INSTANCE.parent.log(msg); } else { System.out.println(msg); } } private static void _debug(String msg) { System.out.println(msg); } public boolean checkVersionCache(String version) { File requestedJar = archiveFolder.resolve("mc-" + version + ".jar").toFile(); File newestJar = archiveFolder.resolve("mc-" + newestMC + ".jar").toFile(); if (requestedJar.exists()) return true; if (newestJar.exists()) { doPatch(requestedJar, newestJar, version); return true; } else { if (this.getParent().requestLogin()) { try { FileUtils.copyURLToFile(new URL("http://assets.minecraft.net/" + newestMC.replace(".","_") + "/minecraft.jar"), newestJar); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (!requestedJar.toString().equals(newestJar.toString())) { doPatch(requestedJar, newestJar, version); } return true; } else { return false; } } } private void doPatch(File requestedJar, File newestJar, String version) { try { URL patchURL = new URL("http://mcupdater.net46.net/mcu_patches/" + newestMC.replace(".", "") + "to" + version.replace(".","") + ".patch"); _debug(patchURL.toString()); File patchFile = archiveFolder.resolve("temp.patch").toFile(); FileUtils.copyURLToFile(patchURL, patchFile); Transmogrify.applyPatch(new Path(newestJar), new Path(requestedJar), new Path(patchFile)); patchFile.delete(); } catch (Exception e) { e.printStackTrace(); } } }
package jolie.net; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.server.rpc.RPC; import com.google.gwt.user.server.rpc.RPCRequest; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.URI; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import jolie.Interpreter; import jolie.lang.NativeType; import jolie.net.http.HttpMessage; import jolie.net.http.HttpParser; import jolie.net.http.HttpUtils; import jolie.net.http.json.JsonUtils; import joliex.gwt.server.JolieGWTConverter; import jolie.net.http.Method; import jolie.net.http.MultiPartFormDataParser; import jolie.net.ports.Interface; import jolie.net.protocols.CommProtocol; import jolie.runtime.ByteArray; import jolie.runtime.Value; import jolie.runtime.ValueVector; import jolie.runtime.VariablePath; import jolie.runtime.typing.OneWayTypeDescription; import jolie.runtime.typing.RequestResponseTypeDescription; import jolie.runtime.typing.Type; import jolie.runtime.typing.TypeCastingException; import jolie.util.LocationParser; import jolie.xml.XmlUtils; import joliex.gwt.client.JolieService; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * HTTP protocol implementation * @author Fabrizio Montesi */ public class HttpProtocol extends CommProtocol { private static final byte[] NOT_IMPLEMENTED_HEADER = "HTTP/1.1 501 Not Implemented".getBytes(); //private static final byte[] INTERNAL_SERVER_ERROR_HEADER = "HTTP/1.1 500 Internal Server error".getBytes(); private static class Parameters { private static String DEBUG = "debug"; private static String COOKIES = "cookies"; private static String METHOD = "method"; private static String ALIAS = "alias"; private static String MULTIPART_HEADERS = "multipartHeaders"; private static String CONCURRENT = "concurrent"; private static class MultiPartHeaders { private static String FILENAME = "filename"; } } private static class Headers { private static String JOLIE_MESSAGE_ID = "X-Jolie-MessageID"; } private String inputId = null; private final Transformer transformer; private final DocumentBuilderFactory docBuilderFactory; private final DocumentBuilder docBuilder; private final URI uri; private final boolean inInputPort; private MultiPartFormDataParser multiPartFormDataParser = null; public final static String CRLF = new String( new char[] { 13, 10 } ); public String name() { return "http"; } public boolean isThreadSafe() { return checkBooleanParameter( Parameters.CONCURRENT ); } public HttpProtocol( VariablePath configurationPath, URI uri, boolean inInputPort, TransformerFactory transformerFactory, DocumentBuilderFactory docBuilderFactory, DocumentBuilder docBuilder ) throws TransformerConfigurationException { super( configurationPath ); this.uri = uri; this.inInputPort = inInputPort; this.transformer = transformerFactory.newTransformer(); this.docBuilderFactory = docBuilderFactory; this.docBuilder = docBuilder; transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" ); } private void valueToDocument( Value value, Node node, Document doc ) { node.appendChild( doc.createTextNode( value.strValue() ) ); Element currentElement; for( Entry< String, ValueVector > entry : value.children().entrySet() ) { if ( !entry.getKey().startsWith( "@" ) ) { for( Value val : entry.getValue() ) { currentElement = doc.createElement( entry.getKey() ); node.appendChild( currentElement ); Map< String, ValueVector > attrs = jolie.xml.XmlUtils.getAttributesOrNull( val ); if ( attrs != null ) { for( Entry< String, ValueVector > attrEntry : attrs.entrySet() ) { currentElement.setAttribute( attrEntry.getKey(), attrEntry.getValue().first().strValue() ); } } valueToDocument( val, currentElement, doc ); } } } } public String getMultipartHeaderForPart( String operationName, String partName ) { if ( hasOperationSpecificParameter( operationName, Parameters.MULTIPART_HEADERS ) ) { Value v = getOperationSpecificParameterFirstValue( operationName, Parameters.MULTIPART_HEADERS ); if ( v.hasChildren( partName ) ) { v = v.getFirstChild( partName ); if ( v.hasChildren( Parameters.MultiPartHeaders.FILENAME ) ) { v = v.getFirstChild( Parameters.MultiPartHeaders.FILENAME ); return v.strValue(); } } } return null; } private final static String BOUNDARY = "----Jol13H77p$$Bound4r1$$"; private void send_appendCookies( CommMessage message, String hostname, StringBuilder headerBuilder ) { Value cookieParam = null; if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) { cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES ); } else if ( hasParameter( Parameters.COOKIES ) ) { cookieParam = getParameterFirstValue( Parameters.COOKIES ); } if ( cookieParam != null ) { Value cookieConfig; String domain; StringBuilder cookieSB = new StringBuilder(); for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) { cookieConfig = entry.getValue().first(); if ( message.value().hasChildren( cookieConfig.strValue() ) ) { domain = cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : ""; if ( domain.isEmpty() || hostname.endsWith( domain ) ) { cookieSB .append( entry.getKey() ) .append( '=' ) .append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() ) .append( ";" ); } } } if ( cookieSB.length() > 0 ) { headerBuilder .append( "Cookie: " ) .append( cookieSB ) .append( CRLF ); } } } private void send_appendSetCookieHeader( CommMessage message, StringBuilder headerBuilder ) { Value cookieParam = null; if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) { cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES ); } else if ( hasParameter( Parameters.COOKIES ) ) { cookieParam = getParameterFirstValue( Parameters.COOKIES ); } if ( cookieParam != null ) { Value cookieConfig; for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) { cookieConfig = entry.getValue().first(); if ( message.value().hasChildren( cookieConfig.strValue() ) ) { headerBuilder .append( "Set-Cookie: " ) .append( entry.getKey() ).append( '=' ) .append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() ) .append( "; expires=" ) .append( cookieConfig.hasChildren( "expires" ) ? cookieConfig.getFirstChild( "expires" ).strValue() : "" ) .append( "; domain=" ) .append( cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : "" ) .append( "; path=" ) .append( cookieConfig.hasChildren( "path" ) ? cookieConfig.getFirstChild( "path" ).strValue() : "" ); if ( cookieConfig.hasChildren( "secure" ) && cookieConfig.getFirstChild( "secure" ).intValue() > 0 ) { headerBuilder.append( "; secure" ); } headerBuilder.append( CRLF ); } } } } private String requestFormat = null; private void send_appendQuerystring( Value value, String charset, StringBuilder headerBuilder ) throws IOException { if ( value.children().isEmpty() == false ) { headerBuilder.append( '?' ); for( Entry< String, ValueVector > entry : value.children().entrySet() ) { headerBuilder .append( entry.getKey() ) .append( '=' ) .append( URLEncoder.encode( entry.getValue().first().strValue(), charset ) ) .append( '&' ); } } } private void send_appendParsedAlias( String alias, Value value, String charset, StringBuilder headerBuilder ) throws IOException { int offset = 0; String currStrValue; String currKey; StringBuilder result = new StringBuilder( alias ); Matcher m = Pattern.compile( "%(!)?\\{[^\\}]*\\}" ).matcher( alias ); while( m.find() ) { if ( m.group( 1 ) == null ) { // We have to use URLEncoder currKey = alias.substring( m.start() + 2, m.end() - 1 ); if ( "$".equals( currKey ) ) { currStrValue = URLEncoder.encode( value.strValue(), charset ); } else { currStrValue = URLEncoder.encode( value.getFirstChild( currKey ).strValue(), charset ); } } else { // We have to insert the string raw currKey = alias.substring( m.start() + 3, m.end() - 1 ); if ( "$".equals( currKey ) ) { currStrValue = value.strValue(); } else { currStrValue = value.getFirstChild( currKey ).strValue(); } } result.replace( m.start() + offset, m.end() + offset, currStrValue ); offset += currStrValue.length() - 3 - currKey.length(); } headerBuilder.append( result ); } private String getCharset() { String charset = "UTF-8"; if ( hasParameter( "charset" ) ) { charset = getStringParameter( "charset" ); } return charset; } private String send_getFormat() { String format = "xml"; if ( inInputPort && requestFormat != null ) { format = requestFormat; requestFormat = null; } else if ( hasParameter( "format" ) ) { format = getStringParameter( "format" ); } return format; } private static class EncodedContent { private ByteArray content = null; private String contentType = ""; private String contentDisposition=""; } private EncodedContent send_encodeContent( CommMessage message, Method method, String charset, String format ) throws IOException { EncodedContent ret = new EncodedContent(); if ( inInputPort == false && method == Method.GET ) { // We are building a GET request return ret; } if ( "xml".equals( format ) ) { Document doc = docBuilder.newDocument(); Element root = doc.createElement( message.operationName() + (( inInputPort ) ? "Response" : "") ); doc.appendChild( root ); if ( message.isFault() ) { Element faultElement = doc.createElement( message.fault().faultName() ); root.appendChild( faultElement ); valueToDocument( message.fault().value(), faultElement, doc ); } else { valueToDocument( message.value(), root, doc ); } Source src = new DOMSource( doc ); ByteArrayOutputStream tmpStream = new ByteArrayOutputStream(); Result dest = new StreamResult( tmpStream ); try { transformer.transform( src, dest ); } catch( TransformerException e ) { throw new IOException( e ); } ret.content = new ByteArray( tmpStream.toByteArray() ); ret.contentType = "text/xml"; } else if ( "binary".equals( format ) ) { if ( message.value().isByteArray() ) { ret.content = (ByteArray)message.value().valueObject(); ret.contentType = "application/octet-stream"; } } else if ( "html".equals( format ) ) { ret.content = new ByteArray( message.value().strValue().getBytes( charset ) ); ret.contentType = "text/html"; } else if ( "multipart/form-data".equals( format ) ) { ret.contentType = "multipart/form-data; boundary=" + BOUNDARY; StringBuilder builder = new StringBuilder(); for( Entry< String, ValueVector > entry : message.value().children().entrySet() ) { if ( !entry.getKey().startsWith( "@" ) ) { builder.append( "--" ).append( BOUNDARY ).append( CRLF ); builder.append( "Content-Disposition: form-data; name=\"" ).append( entry.getKey() ).append( '\"' ).append( CRLF ).append( CRLF ); builder.append( entry.getValue().first().strValue() ).append( CRLF ); } } builder.append( "--" + BOUNDARY + "--" ); ret.content = new ByteArray( builder.toString().getBytes( charset ) ); } else if ( "x-www-form-urlencoded".equals( format ) ) { ret.contentType = "application/x-www-form-urlencoded"; Iterator< Entry< String, ValueVector > > it = message.value().children().entrySet().iterator(); Entry< String, ValueVector > entry; StringBuilder builder = new StringBuilder(); while( it.hasNext() ) { entry = it.next(); builder.append( entry.getKey() ) .append( "=" ) .append( URLEncoder.encode( entry.getValue().first().strValue(), "UTF-8" ) ); if ( it.hasNext() ) { builder.append( '&' ); } } ret.content = new ByteArray( builder.toString().getBytes( charset ) ); } else if ( "text/x-gwt-rpc".equals( format ) ) { ret.contentType = "text/x-gwt-rpc"; try { if ( message.isFault() ) { ret.content = new ByteArray( RPC.encodeResponseForFailure( JolieService.class.getMethods()[0], JolieGWTConverter.jolieToGwtFault( message.fault() ) ).getBytes( charset ) ); } else { joliex.gwt.client.Value v = new joliex.gwt.client.Value(); JolieGWTConverter.jolieToGwtValue( message.value(), v ); ret.content = new ByteArray( RPC.encodeResponseForSuccess( JolieService.class.getMethods()[0], v ).getBytes( charset ) ); } } catch( SerializationException e ) { throw new IOException( e ); } } else if ( "json".equals( format ) ) { ret.contentType = "application/json"; StringBuilder jsonStringBuilder = new StringBuilder(); JsonUtils.valueToJsonString( message.value(), jsonStringBuilder ); ret.content = new ByteArray( jsonStringBuilder.toString().getBytes( charset ) ); } return ret; } private void send_appendResponseHeaders( CommMessage message, StringBuilder headerBuilder ) { String redirect = getStringParameter( "redirect" ); if ( redirect.isEmpty() ) { headerBuilder.append( "HTTP/1.1 200 OK" + CRLF ); } else { headerBuilder.append( "HTTP/1.1 303 See Other" + CRLF ); headerBuilder.append( "Location: " + redirect + CRLF ); } send_appendSetCookieHeader( message, headerBuilder ); headerBuilder.append( "Server: JOLIE" ).append( CRLF ); StringBuilder cacheControlHeader = new StringBuilder(); if ( hasParameter( "cacheControl" ) ) { Value cacheControl = getParameterFirstValue( "cacheControl" ); if ( cacheControl.hasChildren( "maxAge" ) ) { cacheControlHeader.append( "max-age=" ).append( cacheControl.getFirstChild( "maxAge" ).intValue() ); } } if ( cacheControlHeader.length() > 0 ) { headerBuilder.append( "Cache-Control: " ).append( cacheControlHeader ).append( CRLF ); } } private void send_appendRequestMethod( Method method, StringBuilder headerBuilder ) { headerBuilder.append( method.id() ); } private void send_appendRequestPath( CommMessage message, Method method, StringBuilder headerBuilder, String charset ) throws IOException { if ( uri.getPath().length() < 1 || uri.getPath().charAt( 0 ) != '/' ) { headerBuilder.append( '/' ); } headerBuilder.append( uri.getPath() ); String alias = getOperationSpecificStringParameter( message.operationName(), Parameters.ALIAS ); if ( alias.isEmpty() ) { headerBuilder.append( message.operationName() ); } else { send_appendParsedAlias( alias, message.value(), charset, headerBuilder ); } if ( method == Method.GET ) { send_appendQuerystring( message.value(), charset, headerBuilder ); } } private static void send_appendAuthorizationHeader( CommMessage message, StringBuilder headerBuilder ) { if ( message.value().hasChildren( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ) ) { Value v = message.value().getFirstChild( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ); //String realm = v.getFirstChild( "realm" ).strValue(); String userpass = v.getFirstChild( "userid" ).strValue() + ":" + v.getFirstChild( "password" ).strValue(); sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder(); userpass = encoder.encode( userpass.getBytes() ); headerBuilder.append( "Authorization: Basic " ).append( userpass ).append( CRLF ); } } private Method send_getRequestMethod( CommMessage message ) throws IOException { try { Method method; if ( hasOperationSpecificParameter( message.operationName(), Parameters.METHOD ) ) { method = Method.fromString( getOperationSpecificStringParameter( message.operationName(), Parameters.METHOD ).toUpperCase() ); } else if ( hasParameter( Parameters.METHOD ) ) { method = Method.fromString( getStringParameter( Parameters.METHOD ).toUpperCase() ); } else { method = Method.POST; } return method; } catch( Method.UnsupportedMethodException e ) { throw new IOException( e ); } } private void send_appendRequestHeaders( CommMessage message, Method method, StringBuilder headerBuilder, String charset ) throws IOException { send_appendRequestMethod( method, headerBuilder ); headerBuilder.append( ' ' ); send_appendRequestPath( message, method, headerBuilder, charset ); headerBuilder.append( " HTTP/1.1" + CRLF ); headerBuilder.append( "Host: " + uri.getHost() + CRLF ); send_appendCookies( message, uri.getHost(), headerBuilder ); send_appendAuthorizationHeader( message, headerBuilder ); } private void send_appendGenericHeaders( CommMessage message, EncodedContent encodedContent, String charset, StringBuilder headerBuilder ) { String param; if ( checkBooleanParameter( "keepAlive" ) == false || channel().toBeClosed() ) { channel().setToBeClosed( true ); headerBuilder.append( "Connection: close" + CRLF ); } if ( checkBooleanParameter( Parameters.CONCURRENT ) ) { headerBuilder.append( Headers.JOLIE_MESSAGE_ID ).append( ": " ).append( message.id() ).append( CRLF ); } if ( encodedContent.content != null ) { String contentType = getStringParameter( "contentType" ); if ( contentType.length() > 0 ) { encodedContent.contentType = contentType; } headerBuilder.append( "Content-Type: " + encodedContent.contentType ); if ( charset != null ) { headerBuilder.append( "; charset=" + charset.toLowerCase() ); } headerBuilder.append( CRLF ); param = getStringParameter( "contentTransferEncoding" ); if ( !param.isEmpty() ) { headerBuilder.append( "Content-Transfer-Encoding: " + param + CRLF ); } if ( contentDisposition.length() > 0 ) { encodedContent.contentDisposition = contentDisposition; headerBuilder.append( "Content-Disposition: " + encodedContent.contentDisposition ); } headerBuilder.append( "Content-Length: " + (encodedContent.content.size() + 2) + CRLF ); ///// here we deleling with the name of the fiel String contentDisposition = getStringParameter( "contentDisposition" ); //headerBuilder.append( "Content-Disposition: " + encodedContent.contentDisposition ); } else { headerBuilder.append( "Content-Length: 0" + CRLF ); } } private void send_logDebugInfo( CharSequence header, EncodedContent encodedContent ) { if ( checkBooleanParameter( "debug" ) ) { StringBuilder debugSB = new StringBuilder(); debugSB.append( "[HTTP debug] Sending:\n" ); debugSB.append( header ); if ( getParameterVector( "debug" ).first().getFirstChild( "showContent" ).intValue() > 0 && encodedContent.content != null ) { debugSB.append( encodedContent.content.toString() ); } Interpreter.getInstance().logInfo( debugSB.toString() ); } } public void send( OutputStream ostream, CommMessage message, InputStream istream ) throws IOException { Method method = send_getRequestMethod( message ); String charset = getCharset(); String format = send_getFormat(); EncodedContent encodedContent = send_encodeContent( message, method, charset, format ); StringBuilder headerBuilder = new StringBuilder(); if ( inInputPort ) { // We're responding to a request send_appendResponseHeaders( message, headerBuilder ); } else { // We're sending a notification or a solicit System.out.println("sono dentro dove devo modificare send InputPort ==False"); } send_appendGenericHeaders( message, encodedContent, charset, headerBuilder ); headerBuilder.append( CRLF ); send_logDebugInfo( headerBuilder, encodedContent ); inputId = message.operationName(); /*if ( charset == null ) { charset = "UTF8"; }*/ ostream.write( headerBuilder.toString().getBytes( charset ) ); if ( encodedContent.content != null ) { ostream.write( encodedContent.content.getBytes() ); ostream.write( CRLF.getBytes( charset ) ); } } private void parseXML( HttpMessage message, Value value ) throws IOException { try { if ( message.size() > 0 ) { DocumentBuilder builder = docBuilderFactory.newDocumentBuilder(); InputSource src = new InputSource( new ByteArrayInputStream( message.content() ) ); Document doc = builder.parse( src ); XmlUtils.documentToValue( doc, value ); } } catch( ParserConfigurationException pce ) { throw new IOException( pce ); } catch( SAXException saxe ) { throw new IOException( saxe ); } } private static void parseJson( HttpMessage message, Value value ) throws IOException { JsonUtils.parseJsonIntoValue( new InputStreamReader( new ByteArrayInputStream( message.content() ) ), value ); } private static void parseForm( HttpMessage message, Value value, String charset ) throws IOException { String line = new String( message.content(), "UTF8" ); String[] s, pair; s = line.split( "&" ); for( int i = 0; i < s.length; i++ ) { pair = s[i].split( "=", 2 ); value.getChildren( pair[0] ).first().setValue( URLDecoder.decode( pair[1], charset ) ); } } private void parseMultiPartFormData( HttpMessage message, Value value ) throws IOException { multiPartFormDataParser = new MultiPartFormDataParser( message, value ); multiPartFormDataParser.parse(); } private static String parseGWTRPC( HttpMessage message, Value value ) throws IOException { RPCRequest request = RPC.decodeRequest( new String( message.content(), "UTF8" ) ); String operationName = (String)request.getParameters()[0]; joliex.gwt.client.Value requestValue = (joliex.gwt.client.Value)request.getParameters()[1]; JolieGWTConverter.gwtToJolieValue( requestValue, value ); return operationName; } private void recv_checkForSetCookie( HttpMessage message, Value value ) throws IOException { if ( hasParameter( Parameters.COOKIES ) ) { String type; Value cookies = getParameterFirstValue( Parameters.COOKIES ); Value cookieConfig; Value v; for( HttpMessage.Cookie cookie : message.setCookies() ) { if ( cookies.hasChildren( cookie.name() ) ) { cookieConfig = cookies.getFirstChild( cookie.name() ); if ( cookieConfig.isString() ) { v = value.getFirstChild( cookieConfig.strValue() ); if ( cookieConfig.hasChildren( "type" ) ) { type = cookieConfig.getFirstChild( "type" ).strValue(); } else { type = "string"; } recv_assignCookieValue( cookie.value(), v, type ); } } /*currValue = Value.create(); currValue.getNewChild( "expires" ).setValue( cookie.expirationDate() ); currValue.getNewChild( "path" ).setValue( cookie.path() ); currValue.getNewChild( "name" ).setValue( cookie.name() ); currValue.getNewChild( "value" ).setValue( cookie.value() ); currValue.getNewChild( "domain" ).setValue( cookie.domain() ); currValue.getNewChild( "secure" ).setValue( (cookie.secure() ? 1 : 0) ); cookieVec.add( currValue );*/ } } } private void recv_assignCookieValue( String cookieValue, Value value, String typeKeyword ) throws IOException { NativeType type = NativeType.fromString( typeKeyword ); if ( NativeType.INT == type ) { try { value.setValue( new Integer( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if ( NativeType.STRING == type ) { value.setValue( cookieValue ); } else if ( NativeType.DOUBLE == type ) { try { value.setValue( new Double( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else { value.setValue( cookieValue ); } } private void recv_checkForCookies( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { Value cookies = null; if ( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.COOKIES ) ) { cookies = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.COOKIES ); } else if ( hasParameter( Parameters.COOKIES ) ) { cookies = getParameterFirstValue( Parameters.COOKIES ); } if ( cookies != null ) { Value v; String type; for( Entry< String, String > entry : message.cookies().entrySet() ) { if ( cookies.hasChildren( entry.getKey() ) ) { Value cookieConfig = cookies.getFirstChild( entry.getKey() ); if ( cookieConfig.isString() ) { v = decodedMessage.value.getFirstChild( cookieConfig.strValue() ); if ( cookieConfig.hasChildren( "type" ) ) { type = cookieConfig.getFirstChild( "type" ).strValue(); } else { type = "string"; } recv_assignCookieValue( entry.getValue(), v, type ); } } } } } private static void recv_parseQueryString( HttpMessage message, Value value ) { String queryString = message.requestPath() == null ? "" : message.requestPath(); String[] kv = queryString.split( "\\?" ); if ( kv.length > 1 ) { queryString = kv[1]; String[] params = queryString.split( "&" ); for( String param : params ) { kv = param.split( "=", 2 ); if ( kv.length > 1 ) { value.getFirstChild( kv[0] ).setValue( kv[1] ); } } } } /* * Prints debug information about a received message */ private void recv_logDebugInfo( HttpMessage message ) { StringBuilder debugSB = new StringBuilder(); debugSB.append( "[HTTP debug] Receiving:\n" ); debugSB.append( "HTTP Code: " + message.httpCode() + "\n" ); debugSB.append( "Resource: " + message.requestPath() + "\n" ); debugSB.append( "--> Header properties\n" ); for( Entry< String, String > entry : message.properties() ) { debugSB.append( '\t' + entry.getKey() + ": " + entry.getValue() + '\n' ); } for( HttpMessage.Cookie cookie : message.setCookies() ) { debugSB.append( "\tset-cookie: " + cookie.toString() + '\n' ); } for( Entry< String, String > entry : message.cookies().entrySet() ) { debugSB.append( "\tcookie: " + entry.getKey() + '=' + entry.getValue() + '\n' ); } if ( getParameterFirstValue( "debug" ).getFirstChild( "showContent" ).intValue() > 0 && message.content() != null ) { debugSB.append( "--> Message content\n" ); debugSB.append( new String( message.content() ) ); } Interpreter.getInstance().logInfo( debugSB.toString() ); } private void recv_parseMessage( HttpMessage message, DecodedMessage decodedMessage, String charset ) throws IOException { requestFormat = null; String format = "xml"; if ( hasParameter( "format" ) ) { format = getStringParameter( "format" ); } String type = message.getProperty( "content-type" ).split( ";" )[0]; if ( "text/html".equals( type ) ) { decodedMessage.value.setValue( new String( message.content() ) ); } else if ( "application/x-www-form-urlencoded".equals( type ) ) { parseForm( message, decodedMessage.value, charset ); } else if ( "text/xml".equals( type ) ) { parseXML( message, decodedMessage.value ); } else if ( "text/x-gwt-rpc".equals( type ) ) { decodedMessage.operationName = parseGWTRPC( message, decodedMessage.value ); requestFormat = "text/x-gwt-rpc"; } else if ( "multipart/form-data".equals( type ) ) { parseMultiPartFormData( message, decodedMessage.value ); } else if ( "application/octet-stream".equals( type ) ) { decodedMessage.value.setValue( new ByteArray( message.content() ) ); } else if ( "application/json".equals( type ) ) { parseJson( message, decodedMessage.value ); } else if ( "xml".equals( format ) || "rest".equals( format ) ) { parseXML( message, decodedMessage.value ); } else if ( "json".equals( format ) ) { parseJson( message, decodedMessage.value ); } else { decodedMessage.value.setValue( new String( message.content() ) ); } } private void recv_checkReceivingOperation( HttpMessage message, DecodedMessage decodedMessage ) { if ( decodedMessage.operationName == null ) { String requestPath = message.requestPath().split( "\\?" )[0]; decodedMessage.operationName = requestPath; Matcher m = LocationParser.RESOURCE_SEPARATOR_PATTERN.matcher( decodedMessage.operationName ); if ( m.find() ) { int resourceStart = m.end(); if ( m.find() ) { decodedMessage.resourcePath = requestPath.substring( resourceStart - 1, m.start() ); decodedMessage.operationName = requestPath.substring( m.end(), requestPath.length() ); } } } if ( decodedMessage.resourcePath.equals( "/" ) && !channel().parentInputPort().canHandleInputOperation( decodedMessage.operationName ) ) { String defaultOpId = getStringParameter( "default" ); if ( defaultOpId.length() > 0 ) { Value body = decodedMessage.value; decodedMessage.value = Value.create(); decodedMessage.value.getChildren( "data" ).add( body ); decodedMessage.value.getFirstChild( "operation" ).setValue( decodedMessage.operationName ); Value cookies = decodedMessage.value.getFirstChild( "cookies" ); for( Entry< String, String > cookie : message.cookies().entrySet() ) { cookies.getFirstChild( cookie.getKey() ).setValue( cookie.getValue() ); } decodedMessage.operationName = defaultOpId; } } } private void recv_checkForMultiPartHeaders( DecodedMessage decodedMessage ) { if ( multiPartFormDataParser != null ) { String target; for( Entry< String, MultiPartFormDataParser.PartProperties > entry : multiPartFormDataParser.getPartPropertiesSet() ) { if ( entry.getValue().filename() != null ) { target = getMultipartHeaderForPart( decodedMessage.operationName, entry.getKey() ); if ( target != null ) { decodedMessage.value.getFirstChild( target ).setValue( entry.getValue().filename() ); } } } multiPartFormDataParser = null; } } private void recv_checkForMessageProperties( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { recv_checkForCookies( message, decodedMessage ); recv_checkForMultiPartHeaders( decodedMessage );// message, decodedMessage ); String property; if ( (property=message.getProperty( "user-agent" )) != null && hasParameter( "userAgent" ) ) { getParameterFirstValue( "userAgent" ).setValue( property ); } } private static class DecodedMessage { private String operationName = null; private Value value = Value.create(); private String resourcePath = "/"; private long id = CommMessage.GENERIC_ID; } public CommMessage recv( InputStream istream, OutputStream ostream ) throws IOException { CommMessage retVal = null; DecodedMessage decodedMessage = new DecodedMessage(); HttpMessage message = new HttpParser( istream ).parse(); if ( message.isSupported() == false ) { ostream.write( NOT_IMPLEMENTED_HEADER ); ostream.write( CRLF.getBytes() ); ostream.write( CRLF.getBytes() ); ostream.flush(); return null; } String charset = getCharset(); if ( message.getProperty( "connection" ) != null ) { HttpUtils.recv_checkForChannelClosing( message, channel() ); } else if ( hasParameter( "keepAlive" ) ) { channel().setToBeClosed( checkBooleanParameter( "keepAlive" ) == false ); } if ( checkBooleanParameter( Parameters.DEBUG ) ) { recv_logDebugInfo( message ); } if ( message.size() > 0 ) { recv_parseMessage( message, decodedMessage, charset ); } if ( checkBooleanParameter( Parameters.CONCURRENT ) ) { String messageId = message.getProperty( Headers.JOLIE_MESSAGE_ID ); if ( messageId != null ) { try { decodedMessage.id = Long.parseLong( messageId ); } catch( NumberFormatException e ) {} } } if ( message.isResponse() ) { recv_checkForSetCookie( message, decodedMessage.value ); retVal = new CommMessage( decodedMessage.id, inputId, decodedMessage.resourcePath, decodedMessage.value, null ); } else if ( message.isError() == false ) { if ( message.isGet() ) { recv_parseQueryString( message, decodedMessage.value ); } recv_checkReceivingOperation( message, decodedMessage ); recv_checkForMessageProperties( message, decodedMessage ); retVal = new CommMessage( decodedMessage.id, decodedMessage.operationName, decodedMessage.resourcePath, decodedMessage.value, null ); } if ( "/".equals( retVal.resourcePath() ) && channel().parentPort() != null && channel().parentPort().getInterface().containsOperation( retVal.operationName() ) ) { try { // The message is for this service Interface iface = channel().parentPort().getInterface(); OneWayTypeDescription oneWayTypeDescription = iface.oneWayOperations().get( retVal.operationName() ); if ( oneWayTypeDescription != null && message.isResponse() == false ) { // We are receiving a One-Way message oneWayTypeDescription.requestType().cast( retVal.value() ); } else { RequestResponseTypeDescription rrTypeDescription = iface.requestResponseOperations().get( retVal.operationName() ); if ( retVal.isFault() ) { Type faultType = rrTypeDescription.faults().get( retVal.fault().faultName() ); if ( faultType != null ) { faultType.cast( retVal.value() ); } } else { if ( message.isResponse() ) { rrTypeDescription.responseType().cast( retVal.value() ); } else { rrTypeDescription.requestType().cast( retVal.value() ); } } } } catch( TypeCastingException e ) { // TODO: do something here? } } return retVal; } }
package fr.utbm.lo43.entities; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import org.newdawn.slick.geom.Vector2f; import org.newdawn.slick.state.StateBasedGame; /** * * @author Thomas Gredin * * Classe Button * * Cette classe permet de crer un boton trois tats (idle, hover, pressed) * On peut galement mettre un callback qui permettra de dcrire les actions * qui seront excuts lors de l'appuie sur le bouton */ public class Button extends EntityClickable implements EntityDrawable { private Image img_actual; private Image img_idle; private Image img_hover; private Image img_pressed; /** * Constructeur. * @param _position * @param _img_idle * @param _img_hover * @param _img_pressed */ public Button(Vector2f _position, String _img_idle, String _img_hover, String _img_pressed) { super(_position); try { img_idle = new Image(_img_idle); img_hover = new Image(_img_hover); img_pressed = new Image(_img_pressed); } catch (SlickException e) { e.printStackTrace(); } img_actual = img_idle; size.x = img_actual.getWidth(); size.y = img_actual.getHeight(); drawable = true; } /** * Constructeur. * @param _position * @param height * @param width * @param _img_idle * @param _img_hover * @param _img_pressed */ public Button(Vector2f _position, float height, float width,String _img_idle, String _img_hover, String _img_pressed) { super(_position); try { img_idle = new Image(_img_idle); img_hover = new Image(_img_hover); img_pressed = new Image(_img_pressed); } catch (SlickException e) { e.printStackTrace(); } img_actual = img_idle; size.x = width; size.y = height; } @Override public void render(Graphics arg2) { img_actual.draw(position.x, position.y, size.x, size.y); } @Override public void update(GameContainer gc, StateBasedGame sbg, int delta) { super.update(gc, sbg, delta); /** * Logique de changement d'image suivant la position de la souris */ if (isMouseHover) { if (isMouseHoverAndPressed) { img_actual = img_pressed; } else { img_actual = img_hover; } } else { img_actual = img_idle; } } /** * Permet de mettre en place l'action qui sera men quand le bouton de la * souris sera cliqu * * @param _mouseClicked * L'interface surcharge */ public void setEventCallback(EventEntityMouseClicked _mouseClicked) { clickedEvent = _mouseClicked; } }
package trickyexamples; import java.util.ConcurrentModificationException; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class RemoveDuringIteration { public static void main(String[] args) { final Set<Integer> set = new HashSet<Integer>(); for (int i = 0; i < 10; i++) { set.add(i); } for (int i = 0; i < 2; i++) { Thread t1 = new Thread() { @Override public void run() { iterateAndRemove(set); super.run(); } }; t1.start(); } } /** * Sometimes this method throws during iteration a {@link ConcurrentModificationException} because * of the remove. * * @param set */ private static void iterateAndRemove(Set<Integer> set) { System.out.println("Before remove"); for (Integer i : set) { System.out.println(i); } Iterator<Integer> it = set.iterator(); while (it.hasNext()) { Integer i = it.next(); if (i % 2 == 0) { // set.remove(i); it.remove(); } } System.out.println("\nAfter remove"); for (Integer i : set) { System.out.println(i); } } }
package uk.co.plogic.gwt.lib.widget; import java.util.ArrayList; import java.util.logging.Logger; import uk.co.plogic.gwt.lib.dom.DomElementByClassNameFinder; import uk.co.plogic.gwt.lib.dom.DomParser; import uk.co.plogic.gwt.lib.ui.layout.ResponsiveLayoutImageResource; import uk.co.plogic.gwt.lib.ui.layout.ResponsiveSizing; import uk.co.plogic.gwt.lib.ui.layout.ResponsiveSizingAccepted; import com.google.gwt.animation.client.Animation; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Element; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.AbsolutePanel; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.FocusPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HasVerticalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.ProvidesResize; import com.google.gwt.user.client.ui.RequiresResize; import com.google.gwt.user.client.ui.Widget; /** * A Widget which holds other widgets which can be rotated through showing * one at a time. * * The width and height need to be set in pixels. This can be done with * setSize() or setSizingWidget(). * * * @author si * */ public class Carousel extends Composite implements RequiresResize, ProvidesResize, ResponsiveSizingAccepted { final Logger logger = Logger.getLogger("Carousel"); FocusPanel holdingPanel = new FocusPanel(); AbsolutePanel viewport = new AbsolutePanel(); ResponsiveLayoutImageResource images; HorizontalPanel fixedHeader; // optional - when it exists, it is added to viewport int headerOffset = 0; // if there is a fixed header section // navigation- automatically visible on multi page boolean showFooter = true; FlowPanel fixedFooter; HorizontalPanel navPanel; HorizontalPanel dotsPanel; int footerOffset = 24; // height of fixed footer section - TODO, possible with just CSS? int width = 1; int height = 1; ResponsiveSizing responsiveSizing; String responsiveMode = "unknown"; boolean isShowing = true; int currentWidget = 0; int visibleWidgetsCount = 0; // order of pages matters so use ArrayList ArrayList<Widget> widgets = new ArrayList<Widget>(); // id -> {element, Widget} ArrayList<WidgetElement> originalElements = new ArrayList<WidgetElement>(); static int animationDuration = 350; public static String CAROUSEL_PAGE_CLASS = "carousel_page"; public static String CAROUSEL_HEADER_CLASS = "carousel_header"; public static String CAROUSEL_FOOTER_CLASS = "carousel_footer"; public static String CAROUSEL_CLASS = "carousel"; class WidgetElement { Widget w; Element e; ResponsiveSizing r; public WidgetElement(Widget w, Element e, ResponsiveSizing r) { this.w = w; this.e = e; this.r = r; } } class AnimatedViewpointQueueItem { int direction; int widgetToShowIndex; boolean animate; public AnimatedViewpointQueueItem(int d, int wi, boolean a) { direction = d; widgetToShowIndex = wi; animate = a; } } class AnimateViewpoint extends Animation { int direction; Widget w1; Widget w2; double w1_start; double w2_start; public AnimateViewpoint(int direction, Widget w1, Widget w2) { this.direction = direction; this.w1 = w1; this.w2 = w2; w1_start = viewport.getWidgetLeft(w1); w2_start = viewport.getWidgetLeft(w2); } @Override protected void onUpdate(double progress) { int currentPos = (int) (w1_start + (width * progress * direction)); viewport.setWidgetPosition(w1, currentPos, headerOffset); currentPos = (int) (w2_start + (width * progress * direction)); viewport.setWidgetPosition(w2, currentPos, headerOffset); } } public Carousel(Element e) { this(); pagesFromDomElement(e); } public Carousel() { images = GWT.create(ResponsiveLayoutImageResource.class); //viewport.addStyleName("carousel_viewpoint"); holdingPanel.addStyleName(CAROUSEL_CLASS); holdingPanel.add(viewport); // holdingPanel.addAttachHandler(new Handler(){ // @Override // public void onAttachOrDetach(AttachEvent event) { // if( event.isAttached() ) { // logger.finer("just got attached "+viewport.getOffsetHeight()+" "+holdingPanel.getOffsetHeight()); // onResize(); // } else { // logger.finer("just got detached"); initWidget(holdingPanel); setup(); } protected void setup() { setupControls(); } public void setSizing(ResponsiveSizing r) { responsiveSizing = r; } public void setResponsiveMode(String mode) { responsiveMode = mode; } /** * Called by the parent of this Carousel to indicate that it is now * visible. It's useful in the supercarousel responsive mode where * not all carousels are visible and an action is needed on becoming * visible. * * @param visible */ public void show(boolean visible) { isShowing = visible; } /** * Remove header (CAROUSEL_HEADER_CLASS) and page (CAROUSEL_PAGE_CLASS) * elements from parentElement. Add classes back into the widgets that * are constructed from the child elements. * @param parentElement */ protected void pagesFromDomElement(Element parentElement) { DomParser domParser = new DomParser(); final ArrayList<Element> doomedDomElements = new ArrayList<Element>(); domParser.addHandler(new DomElementByClassNameFinder(CAROUSEL_PAGE_CLASS) { @Override public void onDomElementFound(Element e, String id) { HTML page = new HTML(e.getInnerHTML()); page.setStyleName(CAROUSEL_PAGE_CLASS); doomedDomElements.add(e); addWidget(page, e, null); // maybe all carousel_page items should have these in their CSS? String eStyle = e.getAttribute("style"); page.getElement().setAttribute("style", eStyle+"overflow:auto;"); page.setWidth("100%"); } }); domParser.addHandler(new DomElementByClassNameFinder(CAROUSEL_HEADER_CLASS) { @Override public void onDomElementFound(Element e, String id) { fixedHeader = new HorizontalPanel(); fixedHeader.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE); fixedHeader.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); HTML h = new HTML(e.getInnerHTML()); fixedHeader.add(h); fixedHeader.setStyleName(CAROUSEL_HEADER_CLASS); doomedDomElements.add(e); viewport.add(fixedHeader, 0, 0); } }); domParser.parseDom(parentElement); for(Element e : doomedDomElements) { e.removeFromParent(); } } /** * redraw widget and pages within the carousel */ @Override public void onResize() { if( responsiveSizing == null ) { logger.finer("responsiveSizing not set, can't resize carousel"); return; } width = responsiveSizing.getWidth(); height = responsiveSizing.getHeight(); if( width < 2 || height < 2 ) { // save some CPU time when the browser hasn't quite finished firing up logger.finer("ignoring carousel resize"); return; } viewport.setPixelSize(width, height); logger.finer("Resize with "+width+"x"+height); if(fixedHeader!=null) headerOffset = fixedHeader.getOffsetHeight(); else headerOffset = 0; int contentsHeight = height-headerOffset; visibleWidgetsCount = 0; for(int i=0; i<widgets.size(); i++) { Widget w = widgets.get(i); if( w.isVisible() ) visibleWidgetsCount++; } // current widget has just gone invisible if( widgets.size()>0 && ! widgets.get(currentWidget).isVisible()) moveTo(1, nextWidgetIndex(1), true); // choose next one that is visible if( showFooter && visibleWidgetsCount > 1) { //viewport.add(fixedFooter, 0, height-footerOffset); viewport.setWidgetPosition(fixedFooter, 0, height-footerOffset); fixedFooter.setVisible(true); contentsHeight -= footerOffset; } else { fixedFooter.setVisible(false); } updateControls(currentWidget); if( contentsHeight<1 ) contentsHeight = 1; for(int i=0; i<widgets.size(); i++) { Widget w = widgets.get(i); w.setHeight(""+contentsHeight+"px"); if (w instanceof RequiresResize) { ((RequiresResize) w).onResize(); } if( i == currentWidget ) { // visible viewport.setWidgetPosition(w, 0, headerOffset); } else { // ensure it's hidden viewport.setWidgetPosition(w, 0, height); } } } protected void setupControls() { if( fixedFooter != null ) return; fixedFooter = new FlowPanel(); FlowPanel footerContainer = new FlowPanel(); footerContainer.setStyleName("carousel_footer_container"); fixedFooter.add(footerContainer); navPanel = new HorizontalPanel(); navPanel.setStyleName("carousel_footer_centre"); footerContainer.add(navPanel); dotsPanel = new HorizontalPanel(); Image previous = new Image(images.leftArrow()); previous.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { moveTo(-1, nextWidgetIndex(-1), true); } }); Image next = new Image(images.rightArrow()); next.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { moveTo(1, nextWidgetIndex(1), true); } }); fixedFooter.setStyleName(CAROUSEL_FOOTER_CLASS); fixedFooter.setHeight(footerOffset+"px"); navPanel.add(previous); navPanel.add(dotsPanel); navPanel.add(next); viewport.add(fixedFooter); setFooterVisibility(showFooter); } protected void updateControls(int selectedWidget) { dotsPanel.clear(); Image im; for(int i=0; i<visibleWidgetsCount; i++) { if( selectedWidget == i ) im = new Image(images.dot_selected()); else im = new Image(images.dot()); im.setStyleName("carousel_footer_dot"); dotsPanel.add(im); // don't show any more dots if the panel is overflowing, remove last dot // TODO make this less visually misleading if( navPanel.getElement().getScrollWidth() > holdingPanel.getOffsetWidth() ) { logger.finer("dots have overflowed"); dotsPanel.remove(i); break; } } } /** * return position in widget array of next visible widget * given the direction of travel through the carousel * @param direction * @return */ protected int nextWidgetIndex(int direction) { if( direction < -1 || direction > 1) return -1; if( visibleWidgetsCount < 1 ) // safety to avoid infinite loop below return -1; int widgetsCount = widgets.size(); int widgetToShowIndex = currentWidget; do { widgetToShowIndex += direction; if( widgetToShowIndex < 0 ) widgetToShowIndex = widgetsCount-1; if( widgetToShowIndex > widgetsCount-1 ) widgetToShowIndex = 0; } while(! widgets.get(widgetToShowIndex).isVisible()); return widgetToShowIndex; } /** * Move one place. Plan is to make this capable of moving to arbitrary * position. For now, just + or - 1 place. The hide on invisible feature * for pages means a little more thought is needed. * * @param direction 1 or -1 */ public void moveTo(int direction, int widgetToShowIndex, boolean animate) { if(widgetToShowIndex < 0 || widgetToShowIndex>widgets.size()-1) return; Widget widgetToShow = widgets.get(widgetToShowIndex); Widget current = widgets.get(currentWidget); if( animate ) { // position widgetToShow to one side of viewpoint viewport.setWidgetPosition(widgetToShow, width*direction, headerOffset); AnimateViewpoint av = new AnimateViewpoint( direction*-1, widgetToShow, current); av.run(animationDuration); } else { viewport.setWidgetPosition(current, 0, height+10); viewport.setWidgetPosition(widgetToShow, 0, headerOffset); } currentWidget = widgetToShowIndex; updateControls(currentWidget); } /** * * use null for any that aren't applicable * * @param elementId * @param w * @param originalElement * @param r */ public void addWidget(Widget w, Element originalElement, ResponsiveSizing r) { widgets.add(w); originalElements.add(new WidgetElement(w, originalElement, r)); if( w.isVisible() ) visibleWidgetsCount++; // put it somewhere out of sight viewport.add(w, 0, height+10); // if( w instanceof ResponsiveSizingAccepted ) { // int heightAdj = -1*headerOffset; // if(showFooter) // heightAdj -= footerOffset; // ResponsiveSizing rs = new ResponsiveSizing(viewport); // rs.setPixelAdjustments(heightAdj, -5); // ResponsiveSizingAccepted rsa = (ResponsiveSizingAccepted) w; // rsa.setSizing(rs); } public void setFooterVisibility(boolean visible) { showFooter = visible; if( showFooter ) viewport.setWidgetPosition(fixedFooter, 0, height-footerOffset); else viewport.setWidgetPosition(fixedFooter, 0, height+10); } public ResponsiveSizing getSizing() { return responsiveSizing; } }
package mondrian.rolap.sql; import mondrian.olap.MondrianProperties; import mondrian.rolap.BatchTestCase; import mondrian.spi.Dialect; import mondrian.spi.impl.*; import mondrian.test.SqlPattern; import mondrian.test.TestContext; import java.sql.SQLException; import java.util.*; import static mondrian.spi.Dialect.DatabaseProduct.MYSQL; import static mondrian.spi.Dialect.DatabaseProduct.POSTGRESQL; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; /** * Test for <code>SqlQuery</code>. * * @author Thiyagu * @since 06-Jun-2007 */ public class SqlQueryTest extends BatchTestCase { private String origWarnIfNoPatternForDialect; private MondrianProperties prop = MondrianProperties.instance(); protected void setUp() throws Exception { super.setUp(); origWarnIfNoPatternForDialect = prop.WarnIfNoPatternForDialect.get(); // This test warns of missing sql patterns for MYSQL. final Dialect dialect = getTestContext().getDialect(); if (prop.WarnIfNoPatternForDialect.get().equals("ANY") || dialect.getDatabaseProduct() == MYSQL) { prop.WarnIfNoPatternForDialect.set( dialect.getDatabaseProduct().toString()); } else { // Do not warn unless the dialect is "MYSQL", or // if the test chooses to warn regardless of the dialect. prop.WarnIfNoPatternForDialect.set("NONE"); } } protected void tearDown() throws Exception { super.tearDown(); prop.WarnIfNoPatternForDialect.set(origWarnIfNoPatternForDialect); } public void testToStringForSingleGroupingSetSql() { if (!isGroupingSetsSupported()) { return; } for (boolean b : new boolean[]{false, true}) { Dialect dialect = getTestContext().getDialect(); SqlQuery sqlQuery = new SqlQuery(dialect, b); sqlQuery.addSelect("c1", null); sqlQuery.addSelect("c2", null); sqlQuery.addGroupingFunction("gf0"); sqlQuery.addFromTable("s", "t1", "t1alias", null, null, true); sqlQuery.addWhere("a=b"); ArrayList<String> groupingsetsList = new ArrayList<String>(); groupingsetsList.add("gs1"); groupingsetsList.add("gs2"); groupingsetsList.add("gs3"); sqlQuery.addGroupingSet(groupingsetsList); String expected; String lineSep = System.getProperty("line.separator"); if (!b) { expected = "select c1 as \"c0\", c2 as \"c1\", grouping(gf0) as \"g0\" " + "from \"s\".\"t1\" =as= \"t1alias\" where a=b " + "group by grouping sets ((gs1, gs2, gs3))"; } else { expected = "select" + lineSep + " c1 as \"c0\"," + lineSep + " c2 as \"c1\"," + lineSep + " grouping(gf0) as \"g0\"" + lineSep + "from" + lineSep + " \"s\".\"t1\" =as= \"t1alias\"" + lineSep + "where" + lineSep + " a=b" + lineSep + "group by grouping sets (" + lineSep + " (gs1, gs2, gs3))"; } assertEquals( dialectize(dialect.getDatabaseProduct(), expected), dialectize( sqlQuery.getDialect().getDatabaseProduct(), sqlQuery.toString())); } } public void testOrderBy() throws SQLException { // Test with requireAlias = true assertEquals( "\norder by\n" + " CASE WHEN alias IS NULL THEN 1 ELSE 0 END, alias ASC", makeTestSqlQuery("expr", "alias", true, true, true, true) .toString()); // requireAlias = false assertEquals( "\norder by\n" + " CASE WHEN expr IS NULL THEN 1 ELSE 0 END, expr ASC", makeTestSqlQuery("expr", "alias", true, true, true, false) .toString()); // nullable = false assertEquals( "\norder by\n" + " expr ASC", makeTestSqlQuery("expr", "alias", true, false, true, false) .toString()); // ascending=false, collateNullsLast=false assertEquals( "\norder by\n" + " CASE WHEN alias IS NULL THEN 0 ELSE 1 END, alias DESC", makeTestSqlQuery("expr", "alias", false, true, false, true) .toString()); } /** * Builds a SqlQuery with flags set according to params. * Uses a Mockito spy to construct a dialect which will give the desired * boolean value for reqOrderByAlias. */ private SqlQuery makeTestSqlQuery( String expr, String alias, boolean ascending, boolean nullable, boolean collateNullsLast, boolean reqOrderByAlias) { JdbcDialectImpl dialect = spy(new JdbcDialectImpl()); when(dialect.requiresOrderByAlias()).thenReturn(reqOrderByAlias); SqlQuery query = new SqlQuery(dialect, true); query.addOrderBy( expr, alias, ascending, true, nullable, collateNullsLast); return query; } public void testToStringForForcedIndexHint() { Map<String, String> hints = new HashMap<String, String>(); hints.put("force_index", "myIndex"); String unformattedMysql = "select c1 as `c0`, c2 as `c1` " + "from `s`.`t1` as `t1alias`" + " FORCE INDEX (myIndex)" + " where a=b"; String formattedMysql = "select\n" + " c1 as `c0`,\n" + " c2 as `c1`\n" + "from\n" + " `s`.`t1` as `t1alias` FORCE INDEX (myIndex)\n" + "where\n" + " a=b"; SqlPattern[] unformattedSqlPatterns = { new SqlPattern( MYSQL, unformattedMysql, null)}; SqlPattern[] formattedSqlPatterns = { new SqlPattern( MYSQL, formattedMysql, null)}; for (boolean formatted : new boolean[]{false, true}) { Dialect dialect = getTestContext().getDialect(); SqlQuery sqlQuery = new SqlQuery(dialect, formatted); sqlQuery.setAllowHints(true); sqlQuery.addSelect("c1", null); sqlQuery.addSelect("c2", null); sqlQuery.addGroupingFunction("gf0"); sqlQuery.addFromTable("s", "t1", "t1alias", null, hints, true); sqlQuery.addWhere("a=b"); SqlPattern[] expected; if (!formatted) { expected = unformattedSqlPatterns; } else { expected = formattedSqlPatterns; } assertSqlQueryToStringMatches(sqlQuery, expected); } } private void assertSqlQueryToStringMatches( SqlQuery query, SqlPattern[] patterns) { Dialect dialect = getTestContext().getDialect(); Dialect.DatabaseProduct d = dialect.getDatabaseProduct(); boolean patternFound = false; for (SqlPattern sqlPattern : patterns) { if (!sqlPattern.hasDatabaseProduct(d)) { // If the dialect is not one in the pattern set, skip the // test. If in the end no pattern is located, print a warning // message if required. continue; } patternFound = true; String trigger = sqlPattern.getTriggerSql(); trigger = dialectize(d, trigger); assertEquals( dialectize(dialect.getDatabaseProduct(), trigger), dialectize( query.getDialect().getDatabaseProduct(), query.toString())); } // Print warning message that no pattern was specified for the current // dialect. if (!patternFound) { String warnDialect = MondrianProperties.instance().WarnIfNoPatternForDialect.get(); if (warnDialect.equals(d.toString())) { System.out.println( "[No expected SQL statements found for dialect \"" + dialect.toString() + "\" and test not run]"); } } } public void testPredicatesAreOptimizedWhenPropertyIsTrue() { if (prop.ReadAggregates.get() && prop.UseAggregates.get()) { // Sql pattner will be different if using aggregate tables. // This test cover predicate generation so it's sufficient to // only check sql pattern when aggregate tables are not used. return; } String mdx = "select {[Time].[1997].[Q1],[Time].[1997].[Q2]," + "[Time].[1997].[Q3]} on 0 from sales"; String accessSql = "select `time_by_day`.`the_year` as `c0`, " + "`time_by_day`.`quarter` as `c1`, " + "sum(`sales_fact_1997`.`unit_sales`) as `m0` " + "from `time_by_day` as `time_by_day`, " + "`sales_fact_1997` as `sales_fact_1997` " + "where `sales_fact_1997`.`time_id` = " + "`time_by_day`.`time_id` and " + "`time_by_day`.`the_year` = 1997 group by " + "`time_by_day`.`the_year`, `time_by_day`.`quarter`"; String mysqlSql = "select " + "`time_by_day`.`the_year` as `c0`, `time_by_day`.`quarter` as `c1`, " + "sum(`sales_fact_1997`.`unit_sales`) as `m0` " + "from " + "`time_by_day` as `time_by_day`, `sales_fact_1997` as `sales_fact_1997` " + "where " + "`sales_fact_1997`.`time_id` = `time_by_day`.`time_id` and " + "`time_by_day`.`the_year` = 1997 " + "group by `time_by_day`.`the_year`, `time_by_day`.`quarter`"; SqlPattern[] sqlPatterns = { new SqlPattern( Dialect.DatabaseProduct.ACCESS, accessSql, accessSql), new SqlPattern(MYSQL, mysqlSql, mysqlSql)}; assertSqlEqualsOptimzePredicates(true, mdx, sqlPatterns); } public void testTableNameIsIncludedWithParentChildQuery() { String sql = "select `employee`.`employee_id` as `c0`, " + "`employee`.`full_name` as `c1`, " + "`employee`.`marital_status` as `c2`, " + "`employee`.`position_title` as `c3`, " + "`employee`.`gender` as `c4`, " + "`employee`.`salary` as `c5`, " + "`employee`.`education_level` as `c6`, " + "`employee`.`management_role` as `c7` " + "from `employee` as `employee` " + "where `employee`.`supervisor_id` = 0 " + "group by `employee`.`employee_id`, `employee`.`full_name`, " + "`employee`.`marital_status`, `employee`.`position_title`, " + "`employee`.`gender`, `employee`.`salary`," + " `employee`.`education_level`, `employee`.`management_role`" + " order by Iif(`employee`.`employee_id` IS NULL, 1, 0)," + " `employee`.`employee_id` ASC"; final String mdx = "SELECT " + " GENERATE(" + " {[Employees].[All Employees].[Sheri Nowmer]}," + "{" + " {([Employees].CURRENTMEMBER)}," + " HEAD(" + " ADDCALCULATEDMEMBERS([Employees].CURRENTMEMBER.CHILDREN), 51)" + "}," + "ALL" + ") DIMENSION PROPERTIES PARENT_LEVEL, CHILDREN_CARDINALITY, PARENT_UNIQUE_NAME ON AXIS(0) \n" + "FROM [HR] CELL PROPERTIES VALUE, FORMAT_STRING"; SqlPattern[] sqlPatterns = { new SqlPattern(Dialect.DatabaseProduct.ACCESS, sql, sql) }; assertQuerySql(mdx, sqlPatterns); } public void testPredicatesAreNotOptimizedWhenPropertyIsFalse() { if (prop.ReadAggregates.get() && prop.UseAggregates.get()) { // Sql pattner will be different if using aggregate tables. // This test cover predicate generation so it's sufficient to // only check sql pattern when aggregate tables are not used. return; } String mdx = "select {[Time].[1997].[Q1],[Time].[1997].[Q2]," + "[Time].[1997].[Q3]} on 0 from sales"; String accessSql = "select `time_by_day`.`the_year` as `c0`, " + "`time_by_day`.`quarter` as `c1`, " + "sum(`sales_fact_1997`.`unit_sales`) as `m0` " + "from `time_by_day` as `time_by_day`, " + "`sales_fact_1997` as `sales_fact_1997` " + "where `sales_fact_1997`.`time_id` = " + "`time_by_day`.`time_id` and `time_by_day`.`the_year` " + "= 1997 and `time_by_day`.`quarter` in " + "('Q1', 'Q2', 'Q3') group by " + "`time_by_day`.`the_year`, `time_by_day`.`quarter`"; String mysqlSql = "select " + "`time_by_day`.`the_year` as `c0`, `time_by_day`.`quarter` as `c1`, " + "sum(`sales_fact_1997`.`unit_sales`) as `m0` " + "from " + "`time_by_day` as `time_by_day`, `sales_fact_1997` as `sales_fact_1997` " + "where " + "`sales_fact_1997`.`time_id` = `time_by_day`.`time_id` and " + "`time_by_day`.`the_year` = 1997 and " + "`time_by_day`.`quarter` in ('Q1', 'Q2', 'Q3') " + "group by `time_by_day`.`the_year`, `time_by_day`.`quarter`"; SqlPattern[] sqlPatterns = { new SqlPattern( Dialect.DatabaseProduct.ACCESS, accessSql, accessSql), new SqlPattern(MYSQL, mysqlSql, mysqlSql)}; assertSqlEqualsOptimzePredicates(false, mdx, sqlPatterns); } public void testPredicatesAreOptimizedWhenAllTheMembersAreIncluded() { if (prop.ReadAggregates.get() && prop.UseAggregates.get()) { // Sql pattner will be different if using aggregate tables. // This test cover predicate generation so it's sufficient to // only check sql pattern when aggregate tables are not used. return; } String mdx = "select {[Time].[1997].[Q1],[Time].[1997].[Q2]," + "[Time].[1997].[Q3],[Time].[1997].[Q4]} on 0 from sales"; String accessSql = "select `time_by_day`.`the_year` as `c0`, " + "`time_by_day`.`quarter` as `c1`, " + "sum(`sales_fact_1997`.`unit_sales`) as `m0` from " + "`time_by_day` as `time_by_day`, `sales_fact_1997` as" + " `sales_fact_1997` where `sales_fact_1997`.`time_id`" + " = `time_by_day`.`time_id` and `time_by_day`." + "`the_year` = 1997 group by `time_by_day`.`the_year`," + " `time_by_day`.`quarter`"; String mysqlSql = "select " + "`time_by_day`.`the_year` as `c0`, `time_by_day`.`quarter` as `c1`, " + "sum(`sales_fact_1997`.`unit_sales`) as `m0` " + "from " + "`time_by_day` as `time_by_day`, `sales_fact_1997` as `sales_fact_1997` " + "where " + "`sales_fact_1997`.`time_id` = `time_by_day`.`time_id` and " + "`time_by_day`.`the_year` = 1997 " + "group by `time_by_day`.`the_year`, `time_by_day`.`quarter`"; SqlPattern[] sqlPatterns = { new SqlPattern( Dialect.DatabaseProduct.ACCESS, accessSql, accessSql), new SqlPattern(MYSQL, mysqlSql, mysqlSql)}; assertSqlEqualsOptimzePredicates(true, mdx, sqlPatterns); assertSqlEqualsOptimzePredicates(false, mdx, sqlPatterns); } private void assertSqlEqualsOptimzePredicates( boolean optimizePredicatesValue, String inputMdx, SqlPattern[] sqlPatterns) { boolean intialValueOptimize = prop.OptimizePredicates.get(); try { prop.OptimizePredicates.set(optimizePredicatesValue); assertQuerySql(inputMdx, sqlPatterns); } finally { prop.OptimizePredicates.set(intialValueOptimize); } } public void testToStringForGroupingSetSqlWithEmptyGroup() { if (!isGroupingSetsSupported()) { return; } final Dialect dialect = getTestContext().getDialect(); for (boolean b : new boolean[]{false, true}) { SqlQuery sqlQuery = new SqlQuery(getTestContext().getDialect(), b); sqlQuery.addSelect("c1", null); sqlQuery.addSelect("c2", null); sqlQuery.addFromTable("s", "t1", "t1alias", null, null, true); sqlQuery.addWhere("a=b"); sqlQuery.addGroupingFunction("g1"); sqlQuery.addGroupingFunction("g2"); ArrayList<String> groupingsetsList = new ArrayList<String>(); groupingsetsList.add("gs1"); groupingsetsList.add("gs2"); groupingsetsList.add("gs3"); sqlQuery.addGroupingSet(new ArrayList<String>()); sqlQuery.addGroupingSet(groupingsetsList); String expected; if (b) { expected = "select\n" + " c1 as \"c0\",\n" + " c2 as \"c1\",\n" + " grouping(g1) as \"g0\",\n" + " grouping(g2) as \"g1\"\n" + "from\n" + " \"s\".\"t1\" =as= \"t1alias\"\n" + "where\n" + " a=b\n" + "group by grouping sets (\n" + " (),\n" + " (gs1, gs2, gs3))"; } else { expected = "select c1 as \"c0\", c2 as \"c1\", grouping(g1) as \"g0\", " + "grouping(g2) as \"g1\" from \"s\".\"t1\" =as= \"t1alias\" where a=b " + "group by grouping sets ((), (gs1, gs2, gs3))"; } assertEquals( dialectize(dialect.getDatabaseProduct(), expected), dialectize( sqlQuery.getDialect().getDatabaseProduct(), sqlQuery.toString())); } } public void testToStringForMultipleGroupingSetsSql() { if (!isGroupingSetsSupported()) { return; } final Dialect dialect = getTestContext().getDialect(); for (boolean b : new boolean[]{false, true}) { SqlQuery sqlQuery = new SqlQuery(dialect, b); sqlQuery.addSelect("c0", null); sqlQuery.addSelect("c1", null); sqlQuery.addSelect("c2", null); sqlQuery.addSelect("m1", null, "m1"); sqlQuery.addFromTable("s", "t1", "t1alias", null, null, true); sqlQuery.addWhere("a=b"); sqlQuery.addGroupingFunction("c0"); sqlQuery.addGroupingFunction("c1"); sqlQuery.addGroupingFunction("c2"); ArrayList<String> groupingSetlist1 = new ArrayList<String>(); groupingSetlist1.add("c0"); groupingSetlist1.add("c1"); groupingSetlist1.add("c2"); sqlQuery.addGroupingSet(groupingSetlist1); ArrayList<String> groupingsetsList2 = new ArrayList<String>(); groupingsetsList2.add("c1"); groupingsetsList2.add("c2"); sqlQuery.addGroupingSet(groupingsetsList2); String expected; if (b) { expected = "select\n" + " c0 as \"c0\",\n" + " c1 as \"c1\",\n" + " c2 as \"c2\",\n" + " m1 as \"m1\",\n" + " grouping(c0) as \"g0\",\n" + " grouping(c1) as \"g1\",\n" + " grouping(c2) as \"g2\"\n" + "from\n" + " \"s\".\"t1\" =as= \"t1alias\"\n" + "where\n" + " a=b\n" + "group by grouping sets (\n" + " (c0, c1, c2),\n" + " (c1, c2))"; } else { expected = "select c0 as \"c0\", c1 as \"c1\", c2 as \"c2\", m1 as \"m1\", " + "grouping(c0) as \"g0\", grouping(c1) as \"g1\", grouping(c2) as \"g2\" " + "from \"s\".\"t1\" =as= \"t1alias\" where a=b " + "group by grouping sets ((c0, c1, c2), (c1, c2))"; } assertEquals( dialectize(dialect.getDatabaseProduct(), expected), dialectize( sqlQuery.getDialect().getDatabaseProduct(), sqlQuery.toString())); } } /** * Verifies that the correct SQL string is generated for literals of * SQL type "double". * * <p>Mondrian only generates SQL DOUBLE values in a special format for * LucidDB; therefore, this test is a no-op on other databases. */ public void testDoubleInList() { final Dialect dialect = getTestContext().getDialect(); if (dialect.getDatabaseProduct() != Dialect.DatabaseProduct.LUCIDDB) { return; } propSaver.set(prop.IgnoreInvalidMembers, true); propSaver.set(prop.IgnoreInvalidMembersDuringQuery, true); // assertQuerySql(testContext, query, patterns); // Test when the double value itself cotnains "E". String dimensionSqlExpression = "cast(cast(\"salary\" as double)*cast(1000.0 as double)/cast(3.1234567890123456 as double) as double)\n"; String cubeFirstPart = "<Cube name=\"Sales 3\">\n" + " <Table name=\"sales_fact_1997\"/>\n" + " <Dimension name=\"StoreEmpSalary\" foreignKey=\"store_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Salary\" primaryKey=\"store_id\">\n" + " <Table name=\"employee\"/>\n" + " <Level name=\"Salary\" column=\"salary\" type=\"Numeric\" uniqueMembers=\"true\" approxRowCount=\"10000000\">\n" + " <KeyExpression>\n" + " <SQL dialect=\"luciddb\">\n"; String cubeSecondPart = " </SQL>\n" + " </KeyExpression>\n" + " </Level>\n" + " </Hierarchy>\n" + " </Dimension>" + " <Measure name=\"Store Cost\" column=\"store_cost\" aggregator=\"sum\"/>\n" + "</Cube>"; String cube = cubeFirstPart + dimensionSqlExpression + cubeSecondPart; String query = "select " + "{[StoreEmpSalary].[All Salary].[6403.162057613773],[StoreEmpSalary].[All Salary].[1184584.980658548],[StoreEmpSalary].[All Salary].[1344664.0320988924], " + " [StoreEmpSalary].[All Salary].[1376679.8423869612],[StoreEmpSalary].[All Salary].[1408695.65267503],[StoreEmpSalary].[All Salary].[1440711.462963099], " + " [StoreEmpSalary].[All Salary].[1456719.3681071333],[StoreEmpSalary].[All Salary].[1472727.2732511677],[StoreEmpSalary].[All Salary].[1488735.1783952022], " + " [StoreEmpSalary].[All Salary].[1504743.0835392366],[StoreEmpSalary].[All Salary].[1536758.8938273056],[StoreEmpSalary].[All Salary].[1600790.5144034433], " + " [StoreEmpSalary].[All Salary].[1664822.134979581],[StoreEmpSalary].[All Salary].[1888932.806996063],[StoreEmpSalary].[All Salary].[1952964.4275722008], " + " [StoreEmpSalary].[All Salary].[1984980.2378602696],[StoreEmpSalary].[All Salary].[2049011.8584364073],[StoreEmpSalary].[All Salary].[2081027.6687244761], " + " [StoreEmpSalary].[All Salary].[2113043.479012545],[StoreEmpSalary].[All Salary].[2145059.289300614],[StoreEmpSalary].[All Salary].[2.5612648230455093E7]} " + " on rows, {[Measures].[Store Cost]} on columns from [Sales 3]"; // Notice there are a few members missing in this sql. This is a LucidDB // bug wrt comparison involving "approximate number literals". // Mondrian properties "IgnoreInvalidMembers" and // "IgnoreInvalidMembersDuringQuery" are required for this MDX to // finish, even though the the generated sql(below) and the final result // are both incorrect. String loadSqlLucidDB = "select cast(cast(\"salary\" as double)*cast(1000.0 as double)/cast(3.1234567890123456 as double) as double) as \"c0\", " + "sum(\"sales_fact_1997\".\"store_cost\") as \"m0\" " + "from \"employee\" as \"employee\", \"sales_fact_1997\" as \"sales_fact_1997\" " + "where \"sales_fact_1997\".\"store_id\" = \"employee\".\"store_id\" and " + "cast(cast(\"salary\" as double)*cast(1000.0 as double)/cast(3.1234567890123456 as double) as double) in " + "(6403.162057613773E0, 1184584.980658548E0, 1344664.0320988924E0, " + "1376679.8423869612E0, 1408695.65267503E0, 1440711.462963099E0, " + "1456719.3681071333E0, 1488735.1783952022E0, " + "1504743.0835392366E0, 1536758.8938273056E0, " + "1664822.134979581E0, 1888932.806996063E0, 1952964.4275722008E0, " + "1984980.2378602696E0, 2049011.8584364073E0, " + "2113043.479012545E0, 2145059.289300614E0, 2.5612648230455093E7) " + "group by cast(cast(\"salary\" as double)*cast(1000.0 as double)/cast(3.1234567890123456 as double) as double)"; SqlPattern[] patterns = { new SqlPattern( Dialect.DatabaseProduct.LUCIDDB, loadSqlLucidDB, loadSqlLucidDB) }; TestContext testContext = TestContext.instance().create( null, cube, null, null, null, null); assertQuerySql(testContext, query, patterns); } public void testInvalidSqlMemberLookup() { String sqlMySql = "select `store`.`store_type` as `c0` from `store` as `store` " + "where UPPER(`store`.`store_type`) = UPPER('Time.Weekly') " + "group by `store`.`store_type` " + "order by ISNULL(`store`.`store_type`), `store`.`store_type` ASC"; String sqlOracle = "select \"store\".\"store_type\" as \"c0\" from \"store\" \"store\" " + "where UPPER(\"store\".\"store_type\") = UPPER('Time.Weekly') " + "group by \"store\".\"store_type\" " + "order by \"store\".\"store_type\" ASC"; SqlPattern[] patterns = { new SqlPattern(MYSQL, sqlMySql, sqlMySql), new SqlPattern( Dialect.DatabaseProduct.ORACLE, sqlOracle, sqlOracle), }; assertNoQuerySql( "select {[Time.Weekly].[All Time.Weeklys]} ON COLUMNS from [Sales]", patterns); } /** * This test makes sure that a level which specifies an * approxRowCount property prevents Mondrian from executing a * count() sql query. It was discovered in bug MONDRIAN-711 * that the aggregate tables predicates optimization code was * not considering the approxRowCount property. It is fixed and * this test will ensure it won't happen again. */ public void testApproxRowCountOverridesCount() { final String cubeSchema = "<Cube name=\"ApproxTest\"> \n" + " <Table name=\"sales_fact_1997\"/> \n" + " <Dimension name=\"Gender\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Gender\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Gender\" column=\"gender\" uniqueMembers=\"true\" approxRowCount=\"2\"/>\n" + " </Hierarchy>\n" + " </Dimension>" + " <Measure name=\"Unit Sales\" column=\"unit_sales\" aggregator=\"sum\"/> \n" + "</Cube>"; final String mdxQuery = "SELECT {[Gender].[Gender].Members} ON ROWS, {[Measures].[Unit Sales]} ON COLUMNS FROM [ApproxTest]"; final String forbiddenSqlOracle = "select count(distinct \"customer\".\"gender\") as \"c0\" from \"customer\" \"customer\""; final String forbiddenSqlMysql = "select count(distinct `customer`.`gender`) as `c0` from `customer` `customer`;"; SqlPattern[] patterns = { new SqlPattern( Dialect.DatabaseProduct.ORACLE, forbiddenSqlOracle, null), new SqlPattern( MYSQL, forbiddenSqlMysql, null) }; final TestContext testContext = TestContext.instance().create( null, cubeSchema, null, null, null, null); assertQuerySqlOrNot( testContext, mdxQuery, patterns, true, true, true); } public void testLimitedRollupMemberRetrievableFromCache() throws Exception { final String mdx = "select NON EMPTY { [Store].[Store].[Store State].members } on 0 from [Sales]"; final TestContext context = TestContext.instance().create( null, null, null, null, null, " <Role name='justCA'>\n" + " <SchemaGrant access='all'>\n" + " <CubeGrant cube='Sales' access='all'>\n" + " <HierarchyGrant hierarchy='[Store]' access='custom' rollupPolicy='partial'>\n" + " <MemberGrant member='[Store].[USA].[CA]' access='all'/>\n" + " </HierarchyGrant>\n" + " </CubeGrant>\n" + " </SchemaGrant>\n" + " </Role>\n").withRole("justCA"); String pgSql = "select \"store\".\"store_country\" as \"c0\"," + " \"store\".\"store_state\" as \"c1\"" + " from \"sales_fact_1997\" as \"sales_fact_1997\"," + " \"store\" as \"store\" " + "where (\"store\".\"store_country\" = 'USA') " + "and (\"store\".\"store_state\" = 'CA') " + "and \"sales_fact_1997\".\"store_id\" = \"store\".\"store_id\" " + "group by \"store\".\"store_country\", \"store\".\"store_state\" " + "order by \"store\".\"store_country\" ASC NULLS LAST," + " \"store\".\"store_state\" ASC NULLS LAST"; SqlPattern pgPattern = new SqlPattern(POSTGRESQL, pgSql, pgSql.length()); String mySql = "select `store`.`store_country` as `c0`," + " `store`.`store_state` as `c1`" + " from `store` as `store`, `sales_fact_1997` as `sales_fact_1997` " + "where `sales_fact_1997`.`store_id` = `store`.`store_id` " + "and `store`.`store_country` = 'USA' " + "and `store`.`store_state` = 'CA' " + "group by `store`.`store_country`, `store`.`store_state` " + "order by ISNULL(`store`.`store_country`) ASC," + " `store`.`store_country` ASC," + " ISNULL(`store`.`store_state`) ASC, `store`.`store_state` ASC"; SqlPattern myPattern = new SqlPattern(MYSQL, mySql, mySql.length()); SqlPattern[] patterns = {pgPattern, myPattern}; context.executeQuery(mdx); assertQuerySqlOrNot(context, mdx, patterns, true, false, false); } } // End SqlQueryTest.java
/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 et: */ package jp.oist.flint.form.sub; import jp.oist.flint.control.DirectoryChooser; import jp.oist.flint.control.FileChooser; import jp.oist.flint.dao.DaoException; import jp.oist.flint.dao.TaskDao; import jp.oist.flint.executor.PhspSimulator; import jp.oist.flint.export.ExportReceiver; import jp.oist.flint.export.ExportWorker; import jp.oist.flint.filesystem.Filename; import jp.oist.flint.filesystem.Workspace; import jp.oist.flint.form.IFrame; import jp.oist.flint.form.MainFrame; import jp.oist.flint.form.job.CombinationModel; import jp.oist.flint.form.job.ExportAllWorker; import jp.oist.flint.form.job.GadgetDialog; import jp.oist.flint.form.job.IParameterInfo; import jp.oist.flint.form.job.IProgressManager; import jp.oist.flint.form.job.JobList; import jp.oist.flint.form.job.JobViewerComponent; import jp.oist.flint.form.job.ParameterFilter; import jp.oist.flint.form.job.PlotWindow; import jp.oist.flint.garuda.GarudaClient; import jp.oist.flint.job.Job; import jp.oist.flint.job.Progress; import jp.oist.flint.phsp.entity.ParameterSet; import jp.oist.flint.util.Utility; import jp.physiome.Ipc; import jp.sbi.garuda.platform.commons.net.GarudaConnectionNotInitializedException; import java.awt.CardLayout; import java.awt.Cursor; import java.awt.Dimension; import java.awt.HeadlessException; import java.awt.Window; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.sql.SQLException; import java.util.ArrayList; import java.util.Map; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import javax.swing.DefaultListSelectionModel; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.SwingWorker; public class JobWindow extends javax.swing.JFrame implements MouseListener, MouseMotionListener, IProgressManager, PropertyChangeListener { private final static String PANELKEY_LIST = "jobwindow.cardlayout.joblist"; private final static String PANELKEY_VIEWER = "jobwindow.cardlayout.jobviewer"; private final static String STATUSBAR_CARD_MESSAGE = "jobwindow.statusbar.message"; private final static String STATUSBAR_CARD_PROGRESS = "jobwindow.statusbar.progress"; private JobList mJobList; private JobViewerComponent mJobViewer; private final SubFrame mParent; private ListSelectionModel mSelectionModel; private CombinationModel mDataModel; private final PhspSimulator mSimulator; private JobViewerContextMenuHandler mContextMenuHandler; public JobWindow(SubFrame parent, PhspSimulator simulator, String title) throws IOException { super(title); mParent = parent; mSimulator = simulator; URL iconUrl = getClass().getResource("/jp/oist/flint/image/icon.png"); setIconImage(new ImageIcon(iconUrl).getImage()); initComponents(); initEvents(); } private void initEvents () { mSelectionModel = new DefaultListSelectionModel(); mDataModel = new CombinationModel(); mContextMenuHandler = new JobViewerContextMenuHandler(); JobList list = newJobList(); setJobList(list); JobViewerComponent viewer = newJobViewer(null); setJobViewer(viewer); pack(); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { setVisible(false); } }); } private JobList newJobList () { JobList jobList = new JobList(); jobList.setName(PANELKEY_LIST); jobList.setParameterInfo(mDataModel); jobList.setModel(mDataModel); jobList.setSelectionModel(mSelectionModel); jobList.setContextMenuHandler(mContextMenuHandler); return jobList; } private void setJobList (JobList newComponent) { pnl_Body.add(newComponent, PANELKEY_LIST); mJobList = newComponent; } private JobViewerComponent newJobViewer (IParameterInfo pInfo) { JobViewerComponent viewer = JobViewerComponent.factory(pInfo); viewer.setModel(mDataModel); viewer.setSelectionModel(mSelectionModel); viewer.setContextMenuHandler(mContextMenuHandler); return viewer; } private void setJobViewer (JobViewerComponent newComponent) { newComponent.addMouseListener(this); newComponent.addMouseMotionListener(this); JScrollPane scrollPane = new JScrollPane(newComponent); scrollPane.setName(PANELKEY_VIEWER); scrollPane.setPreferredSize(new Dimension(640, 480)); scrollPane.setOpaque(false); scrollPane.getVerticalScrollBar().setUnitIncrement(16); pnl_Body.add(scrollPane, PANELKEY_VIEWER); mJobViewer = newComponent; } public JobViewerComponent getJobViewer () { return mJobViewer; } public void load (ParameterSet parameterSet) { if (mSelectionModel != null) mSelectionModel.clearSelection(); mDataModel.load(parameterSet, new ParameterFilter () { @Override public boolean accept (Number[] values) { return values.length > 1; } }); mDataModel.setParameterIsDummy(parameterSet instanceof ParameterSet.Dummy); JobViewerComponent viewer = newJobViewer(mDataModel); setJobViewer(viewer); btn_Viewer.setVisible(!mDataModel.getParameterIsDummy()); btn_Viewer.repaint(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); pnl_Head = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); lbl_View = new javax.swing.JLabel(); btn_List = new javax.swing.JToggleButton(); btn_Viewer = new javax.swing.JToggleButton(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); btn_ExportAll = new javax.swing.JButton(); pnl_Body = new javax.swing.JPanel(); pnl_StatusBar = new javax.swing.JPanel(); lbl_StatusBar = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); pb_StatusBar = new javax.swing.JProgressBar(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); pnl_Head.setBorder(javax.swing.BorderFactory.createEmptyBorder(2, 0, 2, 0)); pnl_Head.setMaximumSize(new java.awt.Dimension(32767, 50)); pnl_Head.setMinimumSize(new java.awt.Dimension(10, 50)); pnl_Head.setOpaque(false); pnl_Head.setPreferredSize(new java.awt.Dimension(700, 50)); pnl_Head.setRequestFocusEnabled(false); pnl_Head.setLayout(new java.awt.BorderLayout()); jPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(2, 0, 2, 0)); jPanel1.setMaximumSize(new java.awt.Dimension(32767, 50)); jPanel1.setMinimumSize(new java.awt.Dimension(350, 50)); jPanel1.setOpaque(false); jPanel1.setPreferredSize(new java.awt.Dimension(350, 50)); jPanel1.setRequestFocusEnabled(false); java.awt.FlowLayout flowLayout1 = new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0); flowLayout1.setAlignOnBaseline(true); jPanel1.setLayout(flowLayout1); jPanel4.setMaximumSize(new java.awt.Dimension(32767, 50)); jPanel4.setMinimumSize(new java.awt.Dimension(300, 50)); jPanel4.setPreferredSize(new java.awt.Dimension(300, 50)); jPanel4.setLayout(new javax.swing.BoxLayout(jPanel4, javax.swing.BoxLayout.LINE_AXIS)); lbl_View.setText("View : "); jPanel4.add(lbl_View); buttonGroup1.add(btn_List); btn_List.setSelected(true); btn_List.setText("List"); btn_List.setActionCommand("jobwindow.action.joblist"); btn_List.setAutoscrolls(true); btn_List.setMaximumSize(new java.awt.Dimension(100, 22)); btn_List.setMinimumSize(new java.awt.Dimension(100, 22)); btn_List.setPreferredSize(new java.awt.Dimension(100, 22)); btn_List.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_ListActionPerformed(evt); } }); jPanel4.add(btn_List); buttonGroup1.add(btn_Viewer); btn_Viewer.setText("Chart"); btn_Viewer.setActionCommand("jobwindow.action.jobviewer"); btn_Viewer.setAutoscrolls(true); btn_Viewer.setMaximumSize(new java.awt.Dimension(100, 22)); btn_Viewer.setMinimumSize(new java.awt.Dimension(100, 22)); btn_Viewer.setPreferredSize(new java.awt.Dimension(100, 22)); btn_Viewer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_ViewerActionPerformed(evt); } }); jPanel4.add(btn_Viewer); jPanel1.add(jPanel4); pnl_Head.add(jPanel1, java.awt.BorderLayout.WEST); jPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(2, 0, 2, 0)); jPanel2.setMaximumSize(new java.awt.Dimension(32767, 50)); jPanel2.setMinimumSize(new java.awt.Dimension(350, 50)); jPanel2.setOpaque(false); jPanel2.setPreferredSize(new java.awt.Dimension(350, 50)); jPanel2.setRequestFocusEnabled(false); java.awt.FlowLayout flowLayout2 = new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT, 5, 0); flowLayout2.setAlignOnBaseline(true); jPanel2.setLayout(flowLayout2); jPanel3.setMaximumSize(new java.awt.Dimension(32767, 50)); jPanel3.setMinimumSize(new java.awt.Dimension(110, 50)); jPanel3.setName(""); // NOI18N jPanel3.setPreferredSize(new java.awt.Dimension(110, 50)); jPanel3.setLayout(new javax.swing.BoxLayout(jPanel3, javax.swing.BoxLayout.LINE_AXIS)); btn_ExportAll.setText("Export All"); btn_ExportAll.setActionCommand("jobwindow.action.exportAll"); btn_ExportAll.setEnabled(false); btn_ExportAll.setMaximumSize(new java.awt.Dimension(110, 22)); btn_ExportAll.setMinimumSize(new java.awt.Dimension(110, 22)); btn_ExportAll.setPreferredSize(new java.awt.Dimension(110, 22)); btn_ExportAll.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_ExportAllActionPerformed(evt); } }); jPanel3.add(btn_ExportAll); jPanel2.add(jPanel3); pnl_Head.add(jPanel2, java.awt.BorderLayout.EAST); getContentPane().add(pnl_Head, java.awt.BorderLayout.NORTH); pnl_Body.setBackground(java.awt.Color.white); pnl_Body.setLayout(new java.awt.CardLayout()); getContentPane().add(pnl_Body, java.awt.BorderLayout.CENTER); pnl_StatusBar.setBorder(javax.swing.BorderFactory.createEtchedBorder()); pnl_StatusBar.setPreferredSize(new java.awt.Dimension(800, 20)); pnl_StatusBar.setLayout(new java.awt.CardLayout()); lbl_StatusBar.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); lbl_StatusBar.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 0, 0)); lbl_StatusBar.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); pnl_StatusBar.add(lbl_StatusBar, "jobwindow.statusbar.message"); jPanel5.setLayout(new javax.swing.BoxLayout(jPanel5, javax.swing.BoxLayout.LINE_AXIS)); pb_StatusBar.setMaximumSize(new java.awt.Dimension(32767, 18)); pb_StatusBar.setMinimumSize(new java.awt.Dimension(20, 18)); pb_StatusBar.setPreferredSize(new java.awt.Dimension(148, 18)); jPanel5.add(pb_StatusBar); pnl_StatusBar.add(jPanel5, "jobwindow.statusbar.progress"); getContentPane().add(pnl_StatusBar, java.awt.BorderLayout.PAGE_END); pack(); }// </editor-fold>//GEN-END:initComponents private void btn_ViewerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_ViewerActionPerformed CardLayout cardLayout = (CardLayout)pnl_Body.getLayout(); int selectedIndex = mSelectionModel.getMinSelectionIndex(); cardLayout.show(pnl_Body, PANELKEY_VIEWER); if (selectedIndex >= 0) mJobViewer.ensureIndexIsVisible(selectedIndex); }//GEN-LAST:event_btn_ViewerActionPerformed private void btn_ListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_ListActionPerformed CardLayout cardLayout = (CardLayout)pnl_Body.getLayout(); int selectedIndex = mSelectionModel.getMinSelectionIndex(); cardLayout.show(pnl_Body, PANELKEY_LIST); if (selectedIndex >= 0) mJobList.ensureIndexIsVisible(selectedIndex); }//GEN-LAST:event_btn_ListActionPerformed private void btn_ExportAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_ExportAllActionPerformed try { exportAll(); } catch (DaoException | IOException | SQLException ex) { showErrorDialog(ex.getMessage(), "Error on exporting simulation data"); } }//GEN-LAST:event_btn_ExportAllActionPerformed public int getSelectedIndex () { return mJobViewer.getSelectedIndex(); } public int[] getSelectedIndices () { return mJobViewer.getSelectedIndices(); } private void showMessageDialog (String msg, String title) { JOptionPane.showMessageDialog(this, msg, title, JOptionPane.INFORMATION_MESSAGE); } private void showErrorDialog (String msg, String title) { JOptionPane.showMessageDialog(this, msg, title, JOptionPane.ERROR_MESSAGE); } /* * Implements IProgressManager */ @Override public void setProgress(int index, Progress progress) { mJobViewer.setProgress(index, progress); mJobList.setProgress(index, progress); repaint(); } @Override public int getProgress (int index) { return mJobList.getProgress(index); } @Override public boolean isCancelled (int index) { return mJobList.isCancelled(index); } @Override public void setCancelled (int index, boolean cancelled) { mJobList.setCancelled(index, cancelled); mJobViewer.setCancelled(index, cancelled); } @Override public int indexOf (Object key) { Map<String, Number> combination = (Map<String, Number>)key; Number[] target = new Number[combination.size()]; String[] titles = mDataModel.getTitles(); for (int i=0; i<titles.length; i++) target[i] = combination.get(titles[i]); return mDataModel.indexOf(target); } /* * Implements MouseListener, ouse */ @Override public void mouseClicked (MouseEvent evt) { } @Override public void mouseEntered (MouseEvent evt) { } @Override public void mouseExited (MouseEvent evt) { lbl_StatusBar.setText(""); } @Override public void mousePressed(MouseEvent evt) { } @Override public void mouseReleased(MouseEvent evt) { } /* * Implements MouseMotionListener */ @Override public void mouseMoved (MouseEvent evt) { if (evt.getSource() instanceof JobViewerComponent.Empty) return; Map<Integer, Number>values = mJobViewer.getValuesAtHover(evt.getPoint()); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); if (values == null || values.isEmpty()) { lbl_StatusBar.setText(""); return; } setCursor(new Cursor(Cursor.HAND_CURSOR)); StringBuilder sb = new StringBuilder(); for (Map.Entry<Integer, Number> v : values.entrySet()) sb.append(String.format("%s=%s ", mDataModel.getTitle(v.getKey()), v.getValue())); lbl_StatusBar.setText(sb.toString()); } @Override public void mouseDragged(MouseEvent evt) { } /* * Implements JobViewComponent.Handler */ public void plotPerformed (JobViewerComponent.Event evt) { Ipc.SimulationTrack st; try { if (evt == null || evt.getIndex() < 0) throw new IOException("Please choose the job."); int index = evt.getIndex(); if (mSimulator.getSimulationDao() == null) throw new IOException("Don't run the simulation."); TaskDao taskDao = mSimulator.getSimulationDao() .obtainTask(mParent.getRelativeModelPath()); if (taskDao == null) throw new IOException("Job Directory does not exist."); File trackFile = taskDao.getTrackFile(); st = Ipc.SimulationTrack.parseFrom((new FileInputStream(trackFile))); Number[] values = mDataModel.getValues(index); String[] titles = mDataModel.getTitles(); int jobId = taskDao.indexOf(values, titles); StringBuilder sb = new StringBuilder(); for (int i=0; i<titles.length; i++) sb.append(String.format("%s=%s ", titles[i], values[i])); PlotWindow plotWindow = new PlotWindow(mParent, sb.toString(), taskDao, jobId); plotWindow.setLocationRelativeTo(mParent); plotWindow.setVisible(true); plotWindow.processSimulationTrack(st); plotWindow.renderPlot(); } catch (DaoException | IOException | SQLException ex) { if (mParent != null) { IFrame frame = (IFrame)mParent; frame.showErrorDialog("It has not finished yet.", "ERROR"); } } } private void exportAll() throws DaoException, IOException, SQLException { if (mSimulator.getSimulationDao() == null) return; // nothing to do InputDialogForExport inputDialog = new InputDialogForExport(this); String extension = inputDialog.show(); if (extension == null) return; String defaultDir = System.getProperty("user.home"); DirectoryChooser chooser = new DirectoryChooser(this, "Choose a target directory", defaultDir); if (!chooser.showDialog()) return; final File selectedDir = chooser.getSelectedDirectory(); if (!selectedDir.exists()) { int result = JOptionPane.showConfirmDialog(mParent, String.format("%s does not exist; do you want to create the new directory and proceed?", selectedDir.getName()), "", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.NO_OPTION) return; if (!selectedDir.mkdirs()) { showErrorDialog("failed to create directory: " + selectedDir.toPath(), "Error on exporting simulation data"); return; } } ConfirmDialogForOverwritingFile confirmDialog = new ConfirmDialogForOverwritingFile(this); File listFile = new File(selectedDir, "simulation.txt"); if (listFile.exists()) { int result = confirmDialog.show(listFile); switch (result) { case JOptionPane.YES_OPTION: if (!listFile.delete()) { showErrorDialog("failed to delete " + listFile.toPath(), "Error on exporting simulation data"); return; } break; default: return; // quit } } ArrayList<File> isdFiles = new ArrayList<>(); ArrayList<File> targetFiles = new ArrayList<>(); ArrayList<Map<String, Number>> parameters = new ArrayList<>(); TaskDao taskDao = mSimulator.getSimulationDao().obtainTask(mParent.getRelativeModelPath()); int numJobs = taskDao.getCount(); int numDigits = String.valueOf(numJobs).getBytes(StandardCharsets.UTF_8).length; for (int i=1; i<=numJobs; i++) { Job job = taskDao.obtainJob(i); File isdFile = job.getIsdFile(); File targetFile = Filename.getVariant(mParent.getModelFile(), selectedDir, i, numDigits, extension); if (targetFile.exists()) { int result = confirmDialog.show(targetFile); switch (result) { case JOptionPane.YES_OPTION: if (!targetFile.delete()) { showErrorDialog("failed to delete " + targetFile.toPath(), "Error on exporting simulation data"); return; } break; case JOptionPane.NO_OPTION: continue; // skip this file default: return; // quit; } } isdFiles.add(isdFile); targetFiles.add(targetFile); parameters.add(job.getCombination()); } final ExportAllWorker worker = new ExportAllWorker(mParent, this, extension, listFile, isdFiles, targetFiles, parameters); worker.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); Object nv = evt.getNewValue(); if ("state".equals(propertyName) && SwingWorker.StateValue.STARTED.equals(nv)) { Window window = SwingUtilities.windowForComponent(mParent); ((MainFrame)window).setEditable(false); } else if ("state".equals(propertyName) && SwingWorker.StateValue.DONE.equals(nv)) { Window window = SwingUtilities.windowForComponent(mParent); ((MainFrame)window).setEditable(true); try { if (worker.get()) { if (worker.isCancelled()) { showMessageDialog("Exporting is cancelled.", "Export cancelled"); } else { showMessageDialog("Exported simulation data to " + selectedDir.getPath(), "Export completed"); } } else { showErrorDialog("An error happened during export.", "Export failed"); } } catch (CancellationException ex) { showMessageDialog("Exporting is cancelled.", "Export cancelled"); } catch (InterruptedException | ExecutionException | HeadlessException ex) { showErrorDialog(ex.getMessage(), "Error on exporting simulation data"); } } } }); worker.execute(); } public void exportPerformed(JobViewerComponent.Event evt) { try { if (evt == null || evt.getIndex() < 0) throw new IOException("Please choose the job."); if (mSimulator.getSimulationDao() == null) throw new IOException("It has not finished yet."); TaskDao taskDao = mSimulator.getSimulationDao().obtainTask(mParent.getRelativeModelPath()); if (taskDao == null) throw new IOException("It has not finished yet."); int jobId = taskDao.indexOf(mDataModel.getValues( evt.getIndex()), mDataModel.getTitles()); if (jobId < 0) throw new IOException("It has not finished yet."); File isdFile = taskDao.obtainJob(jobId).getIsdFile(); if (!isdFile.exists()) throw new IOException("It has not finished yet."); InputDialogForExport inputDialog = new InputDialogForExport(this); String ext = inputDialog.show(); if (ext == null) return; String baseName = Utility.getFileName(mParent.getModelFile().getName()); File defaultFile = new File(mParent.getModelFile().getParent(), baseName + "_" + jobId + "." + ext); FileChooser fileChooser = new FileChooser(mParent, "Export file", FileChooser.Mode.SAVE, defaultFile); if (fileChooser.showDialog()) { final File file = fileChooser.getSelectedFile(); if (file.exists()) { int ans = JOptionPane.showConfirmDialog(this, "Is it OK to replace the existing file?", "Replace the existing file?", JOptionPane.YES_NO_OPTION); if (ans != JOptionPane.YES_OPTION) return; } if ("csv".equalsIgnoreCase(ext)) { // export as CSV ExportReceiver receiver = new ExportReceiver(this); final ExportWorker worker = new ExportWorker((IFrame)mParent, receiver, isdFile, file); receiver.setWorker(worker); // make cancellation possible worker.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); Object newValue = evt.getNewValue(); if ("state".equals(propertyName) && SwingWorker.StateValue.DONE.equals(newValue)) { try { if (worker.get()) showMessageDialog("Exported successfully to " + file.getPath(), "CSV Exported"); } catch (CancellationException ce) { showMessageDialog("Exporting is cancelled.", "Export cancelled"); } catch (InterruptedException ex) { showErrorDialog("Export interrupted\n\n" + ex.getMessage(), "CSV Export interrupted"); } catch (ExecutionException ex) { showErrorDialog("Export aborted\n\n" + ex.getMessage(), "CSV Export aborted "); } } } }); worker.execute(); } else { // export as ISD Workspace.publishFile(isdFile, file); showMessageDialog("Exported successfully to " + file.getPath(), "ISD Exported"); } } } catch (DaoException | IOException | SQLException ex) { showErrorDialog("Export failed\n\n" + ex.getMessage(), "Export failed"); } } public void sendViaGarudaPerformed(JobViewerComponent.Event evt) { try { if (evt == null || evt.getIndex() < 0) throw new IOException("Please choose the job."); if (mSimulator.getSimulationDao() == null) throw new IOException("It has not finished yet."); TaskDao taskDao = mSimulator.getSimulationDao().obtainTask(mParent.getRelativeModelPath()); if (taskDao == null) throw new IOException("It has not finished yet."); int jobId = taskDao.indexOf(mDataModel.getValues( evt.getIndex()), mDataModel.getTitles()); if (jobId < 0) throw new IOException("It has not finished yet."); File isdFile = taskDao.obtainJob(jobId).getIsdFile(); if (!isdFile.exists()) throw new IOException("It has not finished yet."); GadgetDialog dialog = new GadgetDialog(this, mParent, isdFile); dialog.setLocationRelativeTo(this); GarudaClient.requestForLoadableGadgets(dialog, "csv"); } catch (GarudaConnectionNotInitializedException gcnie) { showErrorDialog(gcnie.getMessage(), "Error with Garuda"); } catch (DaoException | IOException | SQLException ex) { showErrorDialog("Sending file failed\n\n" + ex.getMessage(), "Sending file failed"); } } public void cancelJobPerformed (JobViewerComponent.Event evt) { File tmp; TaskDao taskDao; try { if (evt == null || evt.getIndex() < 0) throw new IOException("Please choose the job."); if (mSimulator.getSimulationDao() == null) throw new IOException("It has not yet started"); taskDao = mSimulator.getSimulationDao().obtainTask(mParent.getRelativeModelPath()); if (taskDao == null) throw new IOException("It has not yet started"); int ans = JOptionPane.showConfirmDialog(this, "Would you like to cancel simulation job?", "Cancel simulation?", JOptionPane.YES_NO_OPTION); if (ans != JOptionPane.YES_OPTION) return; int rowId = taskDao.indexOf(mDataModel.getValues( evt.getIndex()), mDataModel.getTitles()); Job job = taskDao.obtainJob(rowId); if (job.cancel()) { mJobViewer.setCancelled(evt.getIndex(), true); mJobList.setCancelled(evt.getIndex(), true); } } catch (DaoException | IOException | SQLException ex) { showErrorDialog("Cancellation failed\n\n" + ex.getMessage(), "Cancellation failed"); return; } } /* PropertyChangeListener */ @Override public void propertyChange(PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); Object nv = evt.getNewValue(); if ("state".equals(propertyName)) { if (SwingWorker.StateValue.DONE.equals(nv)) { btn_ExportAll.setEnabled(true); } } } /* * Inner classes */ private class JobViewerContextMenuHandler extends JobViewerComponent.ContextMenuHandler { @Override public void handleEvent(JobViewerComponent.Event evt) { String action = evt.getAction(); if (action == null) return; switch (action) { case "view": plotPerformed(evt); break; case "export": exportPerformed(evt); break; case "sendViaGaruda": sendViaGarudaPerformed(evt); break; case "cancelJob": cancelJobPerformed(evt); break; } } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btn_ExportAll; private javax.swing.JToggleButton btn_List; private javax.swing.JToggleButton btn_Viewer; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JLabel lbl_StatusBar; private javax.swing.JLabel lbl_View; private javax.swing.JProgressBar pb_StatusBar; private javax.swing.JPanel pnl_Body; private javax.swing.JPanel pnl_Head; private javax.swing.JPanel pnl_StatusBar; // End of variables declaration//GEN-END:variables }
package vnmr.ui.shuf; import java.net.*; import java.io.*; import java.util.*; import java.sql.*; import java.text.*; import vnmr.templates.*; import vnmr.bo.*; import vnmr.ui.SessionShare; import vnmr.util.*; //import postgresql.util.*; public class FillDBManager { /** The connection to the database */ protected java.sql.Connection db = null; /** Our statement to run sql queries with */ protected Statement sql = null; // A way to turn off the locator function protected static boolean locatoroff=false; static protected long dateLimitMS=0; // An arbitrary future date in miliseconds. private static long FUTURE_DATE = (long)2000000 * 1000000; /** Version Number for screated. Change this number any time something has changed so that the database a user has needs to be destroyed and recreated. */ // private static final String DBVERSION = "031027"; private static final String DBVERSION = "xxxx"; /** The name of the DataBase. Individual tables are within this. */ protected static final String dbName = "vnmr"; public static final String DB_ATTR_INTEGER = "int"; public static final String DB_ATTR_FLOAT8 = "float8"; public static final String DB_ATTR_TEXT = "text"; public static final String DB_ATTR_INTEGER_ARRAY= "int[]"; public static final String DB_ATTR_FLOAT8_ARRAY = "float8[]"; public static final String DB_ATTR_TEXT_ARRAY = "text[]"; public static final String DB_ATTR_DATE = "timestamp"; public static final int NUM_TAGS = 5; public static final String T_REAL = "1"; public static final String T_STRING = "2"; public static final String ST_INTEGER = "7"; public static final int MAX_ARRAY_STR_LEN = 40; // Lists of all attributes to put into the locator protected HashArrayList shufDataParams; protected HashArrayList shufStudyParams; protected HashArrayList shufProtocolParams; protected HashArrayList shufImageParams; // Limited list of attributes to use in menus public HashArrayList shufDataParamsLimited; public HashArrayList shufStudyParamsLimited; public HashArrayList shufProtocolParamsLimited; public HashArrayList shufImageParamsLimited; // Directory list for finding all appmode param_list's. When operating // in a given appmode, we normally only have access to that subdirectory // under the system dir. For filling the shufXXXParams, we need access // to all of the files. Experimental is in the base dir, so do not // include it. Add new appmodes if they are created. protected String[] appmodFileList = {"imaging/shuffler/", "walkup/shuffler/"}; public String localHost; public String dbHost; public static LocAttrList attrList=null; public static FillDBManager fillDBManager; // Flag whether we are in vnmrj or the managedb standalone. public static boolean managedb=false; public static SymLinkMap symLinkMap; public static SavedDirList savedDirList; // Members for message handling to allow shorter commands. protected static int TYPE = Messages.TYPE; protected static int INFO = Messages.INFO; protected static int WARN = Messages.WARN; protected static int ERROR = Messages.ERROR; protected static int DEBUG = Messages.DEBUG; protected static int GROUP = Messages.GROUP; protected static int ACQ = Messages.ACQ; protected static int OTHER = Messages.OTHER; protected static int OUTPUT = Messages.OUTPUT; protected static int LOG = Messages.LOG; protected static int MBOX = Messages.MBOX; protected static int STDOUT = Messages.STDOUT; protected static int STDERR = Messages.STDERR; private static int connectMessage = 1; private static int dbMessage = 1; // Temporary way to allow coding for new and old postgres. public static String newpostgres = "false"; public FillDBManager() { // Do all the main constructor stuff constructorCommonCode(); symLinkMap = new SymLinkMap(); } // End FillDBManager() public FillDBManager(boolean makeSymLinkMap) { // Do all the main constructor stuff constructorCommonCode(); if(makeSymLinkMap) symLinkMap = new SymLinkMap(); } // End FillDBManager() private void constructorCommonCode() { // Load the driver // Read these persistence files readLocatorOff(true); readDateLimit(); if(!locatorOff()){ try { if(newpostgres.equals("true")) Class.forName("org.postgresql.Driver"); else Class.forName("postgresql.Driver"); } catch(ClassNotFoundException e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Cannot find Class postgresql.Driver"); return; } } // Get host name once and save for future use. try{ InetAddress inetAddress = InetAddress.getLocalHost(); localHost = inetAddress.getHostName(); } catch(UnknownHostException ex) { Messages.postError("Problem getting hostname. Check that /etc/hosts file" + " has the computer name along with \'localhost\'."); System.exit(1); } // Get dbHost. dbHost = System.getProperty("dbhost"); if(dbHost == null) { Messages.postDebug("The environment variable 'dbhost'" + " is missing in the managedb\n" + "and/or vnmrj startup script. This variable" + " should be set to the host\n" + "where the database manager is running." + " It may be set to the string\n" + "'localhost', to default to the current host."); dbHost = localHost; } else if(dbHost.equals("localhost")) { // use the local host. dbHost = localHost; } /* Fill the param_list with params to put into shuffler. */ boolean limited = false; // Not limited param set shufDataParams = ReadParamListFile(Shuf.DB_VNMR_DATA, limited); // Use shufStudyParams for DB_STUDY and DB_LCSTUDY shufStudyParams = ReadParamListFile(Shuf.DB_STUDY, limited); shufProtocolParams = ReadParamListFile(Shuf.DB_PROTOCOL, limited); shufImageParams = ReadParamListFile(Shuf.DB_IMAGE_DIR, limited); // Fill the lists with a limited param set for menus limited = true; // Limited param set shufDataParamsLimited = ReadParamListFile(Shuf.DB_VNMR_DATA, limited); shufStudyParamsLimited = ReadParamListFile(Shuf.DB_STUDY, limited); shufProtocolParamsLimited = ReadParamListFile(Shuf.DB_PROTOCOL,limited); shufImageParamsLimited = ReadParamListFile(Shuf.DB_IMAGE_DIR, limited); String curuser = System.getProperty("user.name"); LoginService loginService = LoginService.getDefault(); Hashtable userHash = loginService.getuserHash(); User user = (User)userHash.get(curuser); savedDirList = new SavedDirList(user); fillDBManager = this; } public static void main(String[] args) { boolean recursive; boolean makeSymLinkMap = true; DBCommunInfo info = new DBCommunInfo(); String usage = new String("Usage:\n" + "managedb createdb " + "| destroydb | addfile fullpath user " + "| removeentry fullpath host\n" + " | removeentrydir dir " + "| filldb dir user table [sleepMs]\n" + " | filldb_nonrecursive dir user table " + "| cleanup | update [sleepMs]\n" + " | updatetable table | updatelocattr " + "| checkDBversion | status\n" + " | updateloop [sleepMs] " + "| setattr table fullpath attr value\n" + " | updateappdirs " + " | getVnmrjVersion [ debug debug_category]"); // Flag that we are executing from the managedb main(). managedb = true; // We want managedb to log its messages to a different file // from vnmrj, so set the name here we want to use. Messages.setLogFileName("ManagedbMsgLog"); String user = System.getProperty("user.name"); Messages.postMessage(Messages.OTHER|Messages.LOG, "******************************************"); Messages.postMessage(Messages.OTHER|Messages.LOG, "******* Starting managedb as " + user + " ********"); String cmdString = ""; for(int i=0; i < args.length; i++) { cmdString = cmdString.concat(" " + args[i]); } Messages.postMessage(Messages.OTHER|Messages.LOG, "Command: managedb" + cmdString); Messages.postMessage(Messages.OTHER|Messages.LOG, "******************************************"); if(args.length < 1) { Messages.postMessage(OTHER|ERROR|STDOUT, usage); System.exit(0); } // For the createdb command, we cannot make the SymLinkMap object // because there are no tables for the DB yet. Since it is not // actually needed for this command, just don't try to make one. if(args[0].equals("createdb")) makeSymLinkMap = false; FillDBManager dbManager = new FillDBManager(makeSymLinkMap); if(args[0].endsWith("debug")) { Messages.postError("When the debug option is used, it MUST be " + "the LAST option on the command line."); System.exit(0); } else if(args[0].equals("status") || args[0].equals("dbStatus")) { // Output number of items in each DB category if(!locatorOff()) dbManager.dbStatus(); System.exit(0); } else if(args[0].equals("createdb")) { if(!locatorOff()) { dbManager.createEmptyDBandTables(); dbManager.closeDBConnection(); } System.exit(0); } if(args[0].equals("destroydb")) { if(!locatorOff()) { dbManager.destroyDB(); dbManager.closeDBConnection(); } System.exit(0); } // Connect to the DB dbManager.makeDBConnection(); if(args[0].equals("checkDBversion")) { String result = dbManager.checkDBversion(); // Print the result which will be okay or bad. System.out.print(result); System.exit(0); } if(args[0].equals("getVnmrjVersion")) { String result = dbManager.getVnmrjVersion(); // Print the version. System.out.print(result); System.exit(0); } // Create and fill LocAttrList attrList = new LocAttrList(dbManager); if(args[0].equals("addfile")) { if(args.length < 3) { Messages.postMessage(OTHER|ERROR|STDOUT, usage); System.exit(0); } dbManager.addFileCommand(args[1], args[2]); dbManager.closeDBConnection(); System.exit(0); } else if(args[0].equals("removeentry") || args[0].equals("removefile")) { dbManager.removeEntryCommand(args); dbManager.closeDBConnection(); System.exit(0); } else if(args[0].equals("removeentrydir")) { dbManager.removeFilesInPath(args[1]); dbManager.closeDBConnection(); System.exit(0); } else if(args[0].equals("cleanup")) { dbManager.cleanupDBList(info); dbManager.closeDBConnection(); System.exit(0); } else if(args[0].equals("setattr")) { if(args.length < 5) { Messages.postMessage(OTHER|ERROR|STDOUT, usage); System.exit(0); } boolean foundit = false; for(int i=0; i<Shuf.OBJTYPE_LIST.length; i++) { if(args[3].equals(Shuf.OBJTYPE_LIST[i])) { foundit = true; break; } } String value = args[4]; if(foundit) { // attr is an objtype, do the conversion Vector mp = MountPaths.getPathAndHost(args[4]); String dhost = (String) mp.get(Shuf.HOST); String dpath = (String) mp.get(Shuf.PATH); value = dhost + ":" + dpath; } String fullpath; fullpath = dbManager.getDefaultPath(args[1], args[2]); dbManager.setNonTagAttributeValue(args[1], fullpath, dbManager.localHost, args[3], "text", value); System.exit(0); } else if(args[0].equals("update")) { // If the locator is turned off, don't update anything if(locatorOff() || locatoroff) { Messages.postDebug("Locator Off, skipping DB update"); System.exit(0); } // Check DB version String result = dbManager.checkDBversion(); if(result.equals("bad")) { Messages.postMessage(OTHER|ERROR|STDOUT, "DataBase contents version is not correct. \n" + " If using a remote DB server, it must have " + "the same vnmrj version as this machine.\n" + " If vnmrj version is correct, run \'dbsetup\' on " + dbManager.dbHost + " to create a new DB version." ); System.exit(0); } // Optional 2nd arg is sleepMs long sleepMs = 0; if(args.length > 1 && !args[1].endsWith("debug")) { sleepMs = Integer.parseInt(args[1]); } LoginService loginService = LoginService.getDefault(); Hashtable userHash = loginService.getuserHash(); try { if(DebugOutput.isSetFor("updatedb")) Messages.postDebug("Update starting updateDB" + " with sleepMs " + sleepMs); dbManager.updateDB(userHash, sleepMs); // Write out the attrList, else for large DB, vnmrj // can take several minutes to start while it creates this list. dbManager.attrList.writePersistence(); } catch (InterruptedException ie) { // Don't do anything, just let things close. } dbManager.closeDBConnection(); System.exit(0); } else if(args[0].equals("updateloop")) { if(locatorOff()) System.exit(0); // The following bourn shell script code can be used in the // vnmrj startup script to start this loop as a separate // process running under nice. // When this is called via vnmrj, only the first debug option // will be passed in. the rt.exec() command does not allow // passing of a quoted string of args as one arg. // Check DB version String result = dbManager.checkDBversion(); if(result.equals("bad")) { Messages.postMessage(OTHER|ERROR|STDOUT, "DataBase contents version is not correct. \n" + " Run 'dbsetup' to create a new version." ); System.exit(0); } // Optional 2nd arg is sleepMs long sleepMs = 1000; if(args.length > 1 && !args[1].endsWith("debug")) { sleepMs = Integer.parseInt(args[1]); } LoginService loginService = LoginService.getDefault(); Hashtable userHash = loginService.getuserHash(); try { // Give time for vnmrj to have started up // Don't use this if not starting from vnmrj // Thread.sleep(120000); if(DebugOutput.isSetFor("updateloop")) Messages.postDebug("Updateloop starting fillAllListsFromDB" + " with sleepMs " + sleepMs/2); // First be sure the LocAttrList is up to date attrList.fillAllListsFromDB(sleepMs/2); } catch (Exception e) { Messages.writeStackTrace(e); // Now just continue. } while(true) { if(DebugOutput.isSetFor("updateloop")) Messages.postDebug("Updateloop starting updateDB cycle " + "with sleepMs " + sleepMs); try { boolean workspace = false; dbManager.updateDB(userHash, sleepMs, workspace); if(DebugOutput.isSetFor("updateloop")) Messages.postDebug("Updateloop finished updateDB"); // sleep Thread.sleep(200000); } catch (InterruptedException ie) { // Don't do anything, just let things close. } } } else if(args[0].equals("updatetable")) { // Check DB version String result = dbManager.checkDBversion(); if(result.equals("bad")) { Messages.postMessage(OTHER|ERROR|STDOUT, "DataBase contents version is not correct. \n" + " Run 'dbsetup' to create a new version." ); System.exit(0); } if(args.length < 2) { Messages.postMessage(OTHER|ERROR|STDOUT, usage); System.exit(0); } try { dbManager.updateThisTable(args[1]); } catch (Exception e) { Messages.postError("Problem updating DB for type = " + args[1]); Messages.writeStackTrace(e); } dbManager.closeDBConnection(); System.exit(0); } // Add files found in the appdirs areas for all users // This can be used when using a previous DB and wanting to add the // appdir files from the new install area else if(args[0].equals("updateappdirs")) { if(locatorOff()) System.exit(0); try { // Get the user list LoginService loginService = LoginService.getDefault(); Hashtable users = loginService.getuserHash(); boolean workspace = false; boolean appdirOnly = true; // Update using the appdirs for all users but not the datadirs // This get things like protocols, shims and panelsNcomponents // that have special directories. // It does not get data, par study, image_dir dbManager.updateDB(users, 0, workspace, appdirOnly); // Get data, par study, image_dir in vnmrsystem String sysdir = System.getProperty("sysdir"); String owner = "agilent"; recursive = true; // We need to fill from all of the /vnmr, /vnmr/imaging etc // directories IF they are in the appdir list. We do not // want all appdirs because we don't want the users home. // We do not want all /vnmr possibilities because if it // is a liq only site, we don't want imaging etc. // So, go through the appdir list and take dirs that start // with sysdir. We have to do this for each user. ArrayList appDirsToUse = new ArrayList(); // Go thru the users for(Enumeration en = users.elements(); en.hasMoreElements(); ) { User userobj = (User) en.nextElement(); // Get appdirs for this user ArrayList appDirs=userobj.getAppDirectories(); // Go through the list and keep dirs in sysdir for(int i=0; i < appDirs.size(); i++) { String dir = (String)appDirs.get(i); if(dir.startsWith(sysdir)) { // Weed out duplicates if(!appDirsToUse.contains(dir)) appDirsToUse.add(dir); } } } // Now loop through the appDirsToUse and fill some tables for (int i = 0; i < appDirsToUse.size(); i++) { String dirToUse = (String) appDirsToUse.get(i); if(DebugOutput.isSetFor("updateappdirs")) Messages.postDebug("updateappdirs filling dir: " + dirToUse); dbManager.fillATable(Shuf.DB_VNMR_DATA, dirToUse, owner, recursive, info); dbManager.fillATable(Shuf.DB_VNMR_PAR, dirToUse, owner, recursive, info); dbManager.fillATable(Shuf.DB_STUDY, dirToUse, owner, recursive, info); dbManager.fillATable(Shuf.DB_IMAGE_DIR, dirToUse, owner, recursive, info); dbManager.fillATable(Shuf.DB_PROTOCOL, dirToUse, owner, recursive, info); } } catch (Exception e) { Messages.postError("Problem with managedb updateappdirs"); Messages.writeStackTrace(e); } } else if(args[0].equals("updatelocattr")) { if(locatorOff()) System.exit(0); try { // Fill the list dbManager.attrList.fillAllListsFromDB(0); // Write the persistence file dbManager.attrList.writePersistence(); } catch (Exception e) { Messages.postError("Problem updating locator attribute list"); Messages.writeStackTrace(e); } dbManager.closeDBConnection(); System.exit(0); } else if(args[0].startsWith("filldb")) { if(locatorOff() || locatoroff) { Messages.postDebug("Locator Off, skipping DB filldb"); System.exit(0); } // Check DB version String result = dbManager.checkDBversion(); if(result.equals("bad")) { Messages.postMessage(OTHER|ERROR|STDOUT, "DataBase contents version is not correct. \n" + " Run 'dbsetup' to create a new version." ); System.exit(0); } if(args.length < 4) { Messages.postMessage(OTHER|ERROR|STDOUT, usage); System.exit(0); } // Optional 5th arg is sleepMs long sleepMs = 0; if(args.length > 4 && !args[4].endsWith("debug")) { sleepMs = Integer.parseInt(args[4]); } if(args[0].equals("filldb")) recursive = true; else recursive = false; String objType = args[3]; // Allow a type of all, then do all objTypes if(objType.equals("all")) { dbManager.fillAllTables(args[1], args[2], recursive, info, sleepMs); } else { // Update the Attribute list for this objType dbManager.attrList.updateSingleList((args[3]), sleepMs); dbManager.fillATable(args[3], args[1], args[2], recursive, info, sleepMs); } if(info.numFilesAdded > 0) Messages.postMessage(OTHER|INFO|LOG|STDOUT, "\nNumber of Files added = " + info.numFilesAdded); dbManager.updateMacro(Shuf.DB_COMMAND_MACRO); dbManager.updateMacro(Shuf.DB_PPGM_MACRO); } else { Messages.postMessage(OTHER|ERROR|STDOUT, "No such option, " + args[0]); Messages.postMessage(OTHER|INFO|STDOUT, usage); System.exit(0); } dbManager.closeDBConnection(); System.exit(0); } // Remove all of the file in all tables that are in a subdirectory of the // arg path. This is designed for use during install to remove all items // what were in the previous "/vnmr" directory. That is, since the // actual directory probably still exists, we end up with /vnmr files // from each install. To reuse the database after install, we need to // cleanout the previous /vnmr files. public void removeFilesInPath(String path) { if (locatorOff() && !managedb) return; for(int i=0; i < Shuf.OBJTYPE_LIST.length; i++) { String objType = Shuf.OBJTYPE_LIST[i]; // be sure path ends with a terminator, else we could remove // files in a directory that just starts with this name. if(!path.endsWith(File.separator)) { path = path.concat(File.separator); } String cmd = "DELETE from " + objType + " where fullpath like \'%" + path + "%\'"; if(DebugOutput.isSetFor("removeentrydir")) Messages.postDebug("removeentrydir: sql cmd: " + cmd); try { executeUpdate(cmd); } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem removing " + path + " files from DB"); Messages.writeStackTrace(e,"Error caught in removeFilesInPath"); } } } } public boolean addFileCommand(String fullpath, String owner) { String filename; String objType; int index; boolean success; // Insist on fullpath starting at root if(!fullpath.startsWith("/")) { Messages.postMessage(OTHER|ERROR|STDOUT, "The fullpath must start with '/'"); return false; } // First get the filename. That should be everything after // the last '/' index = fullpath.lastIndexOf("/"); filename = fullpath.substring(index +1); objType = getType(fullpath, filename); if(objType.equals("?")) { Messages.postError("Unknown File Type " + fullpath); return false; } // Add it. // Force all vnmrj to update if displaying this type boolean notify=true; // Force the update of this file, even is time stamp is okay. // If only a file like studypar is modified, the study time stamp // will show it is up to date. boolean force=true; success = addFileToDB(objType, filename, fullpath, owner, notify,force); if(success) Messages.postMessage(OTHER|INFO|STDOUT, filename + " added to database."); return success; } public ArrayList getTagListFromDB(String objType) throws SQLException { ArrayList output; java.sql.ResultSet rs; int numTagCol; String value; output = new ArrayList(); /* I have not found a way to get SQL to give DISTINCT results across several columns. Thus we have to get the tag values for each tag column and weed out duplicated for ourselves. */ /* Get the number of tag columns. */ try { numTagCol = numTagColumns(objType); } catch (SQLException pe) { throw pe; } String user = System.getProperty("user.name"); for(int i=0; i < numTagCol; i++) { try { // Initially I used DISTINCT here, but some of the // items took 10-30 sec. Taking out the DISTINCT // gives us back all of the rows and they get // weeded out below. rs = executeQuery("SELECT \"tag" + i + "\" FROM " + objType); if(rs == null) return output; while(rs.next()) { // There is only one column of results, thus, col 1 value = rs.getString(1); // Trap out null and user:null // Also trap for only the current user if(value != null && !value.equals("null") && !value.equals(user + ":" + "null") && value.startsWith(user + ":")) { int index = value.indexOf(':'); if(index >= 0) value = value.substring(index +1); value = value.trim(); // Only add it if we do not already have it. if(!output.contains(value)) { // Be sure it is not whitespace if(value.length() > 0) { output.add(value); } } } } // Try to keep it using minimal cpu Thread.sleep(5000); } catch (Exception e) { } } // Alphabetize or numeric order Collections.sort(output, new NumericStringComparator()); return output; } public String getAttributeValue(String objType, String fullpath, String host, String attr) { java.sql.ResultSet rs; String value; String dhost, dpath; try { Vector mp = MountPaths.getCanonicalPathAndHost(fullpath); dhost = (String) mp.get(Shuf.HOST); dpath = (String) mp.get(Shuf.PATH); } catch (Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem getting cononical path for\n " + fullpath); Messages.writeStackTrace(e); return ""; } String host_fullpath = new String(dhost + ":" + dpath); /* Create SQL command */ String cmd = new String("SELECT " + attr + " FROM " + objType + " WHERE host_fullpath = \'" + host_fullpath + "\'"); // Execute the sql select command try { rs = executeQuery(cmd); if(rs == null) return ""; if(rs.next()) { // getString() gives the string representation even if // the column type is int or float or date value = rs.getString(1); return value; } } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postError("Problem getting the value for \n " + attr + " in " + fullpath); Messages.writeStackTrace(e, "Error caught in getAttributeValue"); } } return null; } /** Same as getAttributeValue(), but posts No Errors. Instead, when an error occurs, it returns an empty string. */ public String getAttributeValueNoError(String objType, String fullpath, String host, String attr) { java.sql.ResultSet rs; String value; String dhost, dpath; try { Vector mp = MountPaths.getCanonicalPathAndHost(fullpath); dhost = (String) mp.get(Shuf.HOST); dpath = (String) mp.get(Shuf.PATH); } catch (Exception e) { // No errors posted return ""; } String host_fullpath = new String(dhost + ":" + dpath); /* Create SQL command */ String cmd = new String("SELECT " + attr + " FROM " + objType + " WHERE host_fullpath = \'" + host_fullpath + "\'"); // Execute the sql select command try { rs = executeQuery(cmd); if(rs == null) return ""; if(rs.next()) { // getString() gives the string representation even if // the column type is int or float or date value = rs.getString(1); return value; } } catch (Exception e) { // No errors posted return ""; } return ""; } public boolean addFileToDB (String objType, String filename, String fullpath, String owner) { // Default to sending notification of the change the the DB boolean notify = true; return addFileToDB(objType, filename, fullpath, owner, notify); } public boolean addFileToDB (String objType, String filename, String fullpath, String owner, boolean notify) { boolean force = false; return addFileToDB(objType, filename, fullpath, owner, notify, force); } public boolean addFileToDB (String objType, String filename, String fullpath, String owner, boolean notify, boolean force) { boolean success; long exists; DBCommunInfo info = new DBCommunInfo(); String dhost, dpath; java.util.Date starttime=null; if(DebugOutput.isSetFor("addFileToDB") || DebugOutput.isSetFor("locTiming")) starttime = new java.util.Date(); // The CanonicalPath is the real absolute path NOT using // any symbolic links. It is the real path. try { Vector mp = MountPaths.getCanonicalPathAndHost(fullpath); dhost = (String) mp.get(Shuf.HOST); dpath = (String) mp.get(Shuf.PATH); } catch (Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem getting cononical path for\n " + fullpath); Messages.writeStackTrace(e); return false; } // Is this host and fullpath unique? exists = isDBKeyUniqueAndUpToDate(objType, dhost + ":" + dpath, fullpath); if(exists == 0) { // The entry exists in the DB and is up to data, but we are // requested to force an update, remove the entry if(force) removeEntryFromDB(objType, dhost + ":" + dpath, info); // The entry exists in the DB and is up to data // If not a study nor automation, then return. Study's and // automation's may have files beneath them that need attention // so continue. else if(!objType.equals(Shuf.DB_STUDY) && !objType.equals(Shuf.DB_LCSTUDY) && !objType.equals(Shuf.DB_AUTODIR)) return false; } else if(exists == -1) { // The entry exists and is out of date. Remove it and // continue with adding it back in. removeEntryFromDB(objType, dhost + ":" + dpath, info); } try { // If this fullpath is for a system file, set the user to agilent String sysdir = System.getProperty("sysdir"); if(sysdir != null) { UNFile sysfile = new UNFile(sysdir); if(sysfile != null) { // Need to compare the canonical path String csysdir = sysfile.getCanonicalPath(); if(fullpath.startsWith(csysdir + "/")) owner = "agilent"; } } } catch (Exception e) { } /* We need to call the correct function to add these. */ if(objType.equals(Shuf.DB_VNMR_DATA)) { success = addVnmrFileToDB(filename, fullpath, owner, objType, 0, null); // Check to see if this vnmr_data is in a study. // If so, set the "study" attribute getStudyParentAndSet(objType, fullpath); } else if(objType.equals(Shuf.DB_VNMR_PAR)) success = addVnmrFileToDB(filename, fullpath, owner, objType, 0, null); else if(objType.equals(Shuf.DB_VNMR_RECORD)) success = addVnmrFileToDB(filename, fullpath, owner, objType, 0, null); else if(objType.equals(Shuf.DB_VNMR_REC_DATA)) success = addVnmrFileToDB(filename, fullpath, owner, objType, 0, null); else if(objType.equals(Shuf.DB_WORKSPACE)) success = addVnmrFileToDB(filename, fullpath, owner, objType, 0, null); else if(objType.equals(Shuf.DB_SHIMS)) success = addVnmrFileToDB(filename, fullpath, owner, objType, 0, null); else if(objType.equals(Shuf.DB_IMAGE_DIR)) { success = addImageDirToDB(filename, fullpath, owner, objType, 0); // Check to see if this image_dir is in a study. // If so, set the "study" attribute getStudyParentAndSet(objType, fullpath); } else if(objType.equals(Shuf.DB_COMPUTED_DIR)) success = addImageDirToDB(filename, fullpath, owner, objType, 0); else if(objType.equals(Shuf.DB_IMAGE_FILE)) success = addVnmrFileToDB(filename, fullpath, owner, objType, 0, null); else if(objType.equals(Shuf.DB_PANELSNCOMPONENTS)) { Object ret = addXmlFileToDB(filename, fullpath, owner, objType); if(ret == null) success = false; else success = true; } else if(objType.equals(Shuf.DB_STUDY) || objType.equals(Shuf.DB_LCSTUDY)) success = addStudyToDB(filename, fullpath, owner, objType, 0); else if(objType.equals(Shuf.DB_AUTODIR)) success = addAutodirToDB(filename, fullpath, owner, objType, 0); else if(objType.equals(Shuf.DB_PROTOCOL)) { DBCommunInfo dbInfo = addXmlFileToDB(filename, fullpath, owner, objType); if(dbInfo == null) success = false; else { // For Protocols, we have to get attr from .xml and procpar // The call to addXmlFileToDB started the process and the // partial information is in info. Send that to the call to // addVnmrFileToDB and let it finish creating the Insert command // for adding to the DB. success = addVnmrFileToDB(filename, fullpath, owner, objType, 0, dbInfo); } } else if(objType.equals(Shuf.DB_TRASH)) success = addTrashFileToDB(fullpath); else { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem adding " + fullpath + " to DB"); Messages.postMessage(OTHER|ERROR|LOG, " table = " + objType + " not found"); return false; } try { // Tell all DB connections it has changed. executeUpdate("NOTIFY UpdateHappened"); } catch(Exception e) { Messages.postMessage(OTHER|WARN|LOG, "NOTIFY CMD: " + e); } if(DebugOutput.isSetFor("addFileToDB") || DebugOutput.isSetFor("locTiming")) { java.util.Date endtime = new java.util.Date(); long timems = endtime.getTime() - starttime.getTime(); Messages.postDebug("addFileToDB: Time(ms) for adding\n " + fullpath + " = " + timems); } // Set this dir into the SavedDirList if successful if(success && (objType.equals(Shuf.DB_VNMR_DATA) || objType.equals(Shuf.DB_VNMR_PAR) || objType.equals(Shuf.DB_STUDY) || objType.equals(Shuf.DB_LCSTUDY) || objType.equals(Shuf.DB_AUTODIR))) { // we want the parent dir of fullpath. UNFile file = new UNFile(fullpath); String parent = file.getParent(); // Now add this dir to SavedDirList if necessary savedDirList.addToList(parent); } if(notify) { // Send notification that this table of the DB has been modified sendTableModifiedNotification(objType); } return success; } // Determine if this item is within a study. If it is, return // the HostFullpath for the parent study this item resides within. // Look for either the parent directory or the grandparent or // great grandparent directory that contains a studypar file. // If a study is found, set the value into the "study" attribute // for this item. protected boolean getStudyParentAndSet(String objType, String fullpath) { String dhost, dpath; // Get dhost and dpath try { Vector mp = MountPaths.getCanonicalPathAndHost(fullpath); dhost = (String) mp.get(Shuf.HOST); dpath = (String) mp.get(Shuf.PATH); } catch (Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem getting cononical path for\n " + fullpath); Messages.writeStackTrace(e); return false; } // Get the parent directory. String parent = ""; int index = fullpath.lastIndexOf(File.separator); if(index > 0) parent = fullpath.substring(0, index); String parPath = new String(parent + File.separator + "studypar"); UNFile file = new UNFile(parPath); // Does it exist? if(file.isFile()) { // Yes, this item is within a study, set the // 'study' attribute for this. try { Vector mp = MountPaths.getCanonicalPathAndHost(parent); dhost = (String) mp.get(Shuf.HOST); dpath = (String) mp.get(Shuf.PATH); } catch (Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem getting cononical path for\n " + parent); Messages.writeStackTrace(e); return false; } String parentHostFullpath = dhost + ":" + dpath; setNonTagAttributeValue(objType, fullpath, localHost, "study", "text", parentHostFullpath); } else { String grandparent = ""; index = parent.lastIndexOf(File.separator); if(index > 0) grandparent = parent.substring(0, index); parPath = new String(grandparent + File.separator + "studypar"); file = new UNFile(parPath); // Does it exist? if(file.isFile()) { // Yes, this item is within a study, set the // 'study' attribute for this. try { Vector mp = MountPaths.getCanonicalPathAndHost(grandparent); dhost = (String) mp.get(Shuf.HOST); dpath = (String) mp.get(Shuf.PATH); } catch (Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem getting cononical path for\n " + grandparent); Messages.writeStackTrace(e); return false; } String grandparentHostFullpath = dhost + ":" + dpath; setNonTagAttributeValue(objType, fullpath, localHost, "study", "text", grandparentHostFullpath); } else { String ggrandparent = ""; index = grandparent.lastIndexOf(File.separator); if(index > 0) ggrandparent = grandparent.substring(0, index); parPath = new String(ggrandparent + File.separator + "studypar"); file = new UNFile(parPath); // Does it exist? if(file.isFile()) { // Yes, this item is within a study, set the // 'study' attribute for this. try { Vector mp = MountPaths.getCanonicalPathAndHost(ggrandparent); dhost = (String) mp.get(Shuf.HOST); dpath = (String) mp.get(Shuf.PATH); } catch (Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem getting cononical path for\n " + ggrandparent); Messages.writeStackTrace(e); return false; } String ggrandparentHostFullpath = dhost + ":" + dpath; setNonTagAttributeValue(objType, fullpath, localHost, "study", "text", ggrandparentHostFullpath); } } } return true; } public boolean removeEntryCommand(String[] args) { boolean success; String objType; String fullpath; boolean status; DBCommunInfo info = new DBCommunInfo(); String dhost, dpath; fullpath = args[1]; // Insist on fullpath starting at root if(!fullpath.startsWith("/")) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "The fullpath must start with '/'"); return false; } try { Vector mp = MountPaths.getCanonicalPathAndHost(fullpath); dhost = (String) mp.get(Shuf.HOST); dpath = (String) mp.get(Shuf.PATH); } catch (Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem getting cononical path for\n " + fullpath); Messages.writeStackTrace(e); return false; } objType = getType(fullpath); // Be sure this hostfullpath exist in the DB. The method // removeEntryFromDB() does not really know if the file was there // and thus removed. status = isDBKeyUnique(objType, dhost + ":" + dpath); if(status == true) { // If isDBKeyUnique() is true, then the file does not exist. Messages.postMessage(OTHER|ERROR|LOG|MBOX, dhost + ":" + dpath + " is not in the DB."); return false; } // Remove it success = removeEntryFromDB(objType, dpath, dhost, info); if(success) Messages.postMessage(OTHER|INFO|STDOUT, fullpath + " removed from database."); else Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem removing " + fullpath + " from database."); return success; } public boolean removeEntryFromDB (String objType, String fullpath, String dhost, DBCommunInfo info) { try { executeUpdate("DELETE FROM " + objType + " WHERE host_fullpath = \'" + dhost + ":" + fullpath + "\'"); info.numFilesRemoved++; return true; } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem removing " + fullpath + " from DB"); Messages.writeStackTrace(e,"Error caught in removeEntryFromDB"); } return false; } } public boolean removeEntryFromDB (String objType, String host_fullpath, DBCommunInfo info) { try { executeUpdate("DELETE FROM " + objType + " WHERE host_fullpath = \'" + host_fullpath + "\'"); info.numFilesRemoved++; return true; } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem removing " + host_fullpath + " from DB"); Messages.writeStackTrace(e,"Error caught in removeEntryFromDB"); } return false; } } public boolean removeEntryFromDB (String objType, String fullpath, String dhost) { DBCommunInfo info = new DBCommunInfo(); return removeEntryFromDB(objType, fullpath, dhost, info); } // Fill all of the tables using only this directory public void fillAllTables(String baseDir, String userName, boolean recur, DBCommunInfo info, long sleepMs) { String dir; dir=FileUtil.vnmrDir(baseDir,"SHIMS"); if(dir !=null) fillATable(Shuf.DB_SHIMS, dir, userName, recur, info); dir=FileUtil.vnmrDir(baseDir,"LAYOUT"); if(dir !=null){ fillATable(Shuf.DB_PANELSNCOMPONENTS, dir, userName, recur, info); } dir=FileUtil.vnmrDir(baseDir,"PANELITEMS"); if(dir !=null){ fillATable(Shuf.DB_PANELSNCOMPONENTS, dir, userName, recur, info); } // Get Protocol Files dir=FileUtil.vnmrDir(baseDir,"PROTOCOLS"); if(dir !=null) fillATable(Shuf.DB_PROTOCOL, dir, userName, recur, info); // Get Trash Files dir=FileUtil.vnmrDir(baseDir,"TRASH"); if(dir !=null) fillATable(Shuf.DB_TRASH, dir, userName, false, info, sleepMs); fillATable(Shuf.DB_VNMR_DATA, baseDir, userName, recur, info, sleepMs); fillATable(Shuf.DB_VNMR_PAR, baseDir, userName, recur, info, sleepMs); fillATable(Shuf.DB_STUDY, baseDir, userName, recur, info, sleepMs); fillATable(Shuf.DB_LCSTUDY, baseDir, userName, recur, info, sleepMs); fillATable(Shuf.DB_AUTODIR, baseDir, userName, recur, info, sleepMs); fillATable(Shuf.DB_IMAGE_DIR, baseDir, userName, recur, info, sleepMs); } public ArrayList fillATable(String objType, String dir, String user, boolean recursive, DBCommunInfo info, long sleepMs) { // Call fillATable with null for attrName and attrVal. return fillATable(objType, dir, user, recursive, info, sleepMs, null, null); } public ArrayList fillATable(String objType, String dir, String user, boolean recursive, DBCommunInfo info) { // Call fillATable with a sleepMs = 0 return fillATable(objType, dir, user, recursive, info, 0); } public ArrayList fillATable(String objType, String dir, String user, boolean recursive, DBCommunInfo info, long sleepMs, String attrName, String attrVal) { String suffix="", prefix=""; String fullpath=null; String hostFullpath; String filename; boolean success=false; ArrayList files = new ArrayList(); UNFile file; int filesAdded=0, totFiles=0; java.util.Date starttime=null; if (locatorOff()) return files; // Check DB version String result = checkDBversion(); if(result.equals("bad")) { // If there is a connection, then the bad version is probably valid. if(checkDBConnection() == true) Messages.postMessage(OTHER|ERROR|LOG|MBOX, "DataBase contents version is not correct. \n" + " Run 'dbsetup' to create a new version." ); else if (dbMessage == 1) Messages.postMessage(OTHER|ERROR|LOG|MBOX, "No DB connection, Locator will not function."); /* Avoid a lot of these messages */ dbMessage = 0; return null; } dbMessage = 1; if(DebugOutput.isSetFor("fillATable")) { Messages.postDebug("fillATable(): objType = " + objType +" dir = " + dir + " user = " + user + " sleepMs = " + sleepMs + "\nDBCommunInfo Class = " + info); } if(DebugOutput.isSetFor("fillATable") || DebugOutput.isSetFor("locTiming")) starttime = new java.util.Date(); // If dateLimitMS = FUTURE_DATE and this is not a system directory, // skip it if(objType.equals(Shuf.DB_VNMR_DATA) && dateLimitMS == FUTURE_DATE) { String sysdir = System.getProperty("sysdir"); if(sysdir != null) { UNFile sysfile = new UNFile(sysdir); if(sysfile != null) { // Need to compare the canonical path String csysdir = sysfile.getCanonicalPath(); if(!dir.startsWith(csysdir + "/")) { // Not varian file, just exit if(DebugOutput.isSetFor("fillATable")) Messages.postDebug("fillATable(): skipping " + dir); return null; } } } } // This try is to catch any unspecified exceptions encountered in the // code. Catch it here so we can print out information about what // we were trying to do instead of catching it later and having no // information about what we were doing. try { // Set up suffix and prefix for use in getting files to put // into DB if(objType.equals(Shuf.DB_VNMR_DATA)) suffix = Shuf.DB_FID_SUFFIX; else if(objType.equals(Shuf.DB_VNMR_PAR)) suffix = Shuf.DB_PAR_SUFFIX; else if(objType.equals(Shuf.DB_VNMR_RECORD)) suffix = Shuf.DB_REC_SUFFIX; else if(objType.equals(Shuf.DB_WORKSPACE)) prefix = Shuf.DB_WKS_PREFIX; else if(objType.equals(Shuf.DB_PANELSNCOMPONENTS)) suffix = Shuf.DB_PANELSNCOMPONENTS_SUFFIX; else if(objType.equals(Shuf.DB_SHIMS)) suffix = ""; else if(objType.equals(Shuf.DB_PROTOCOL)) suffix = Shuf.DB_PROTOCOL_SUFFIX; else if(objType.equals(Shuf.DB_STUDY)) suffix = Shuf.DB_STUDY_SUFFIX; else if(objType.equals(Shuf.DB_LCSTUDY)) suffix = Shuf.DB_LCSTUDY_SUFFIX; else if(objType.equals(Shuf.DB_IMAGE_DIR)) suffix = Shuf.DB_IMG_DIR_SUFFIX; else if(objType.equals(Shuf.DB_IMAGE_FILE)) suffix = Shuf.DB_IMG_FILE_SUFFIX; else if(objType.endsWith(Shuf.DB_MACRO)) { fillMacro(objType); return files; } // If not recursive, for studies and autodirs, just use this file if(!recursive && (objType.equals(Shuf.DB_STUDY) || objType.equals(Shuf.DB_LCSTUDY) || objType.equals(Shuf.DB_AUTODIR))) { // If dir ends with a /, remove it. if(dir.endsWith(File.separator)) files.add(new UNFile(dir.substring(0, dir.length() -1))); else files.add(new UNFile(dir)); } else { /* Get all the files of this type to be added */ getFileListing(files, prefix, suffix, dir, recursive, objType); /* if objType is DB_VNMR_RECORD, then we need to get the files with the lower case suffix also. calling getFileListing() will add to the list in files, so just call it again. */ if(objType.equals(Shuf.DB_VNMR_RECORD)) { suffix = Shuf.DB_REC_SUFFIX; suffix = suffix.toLowerCase(); getFileListing(files, prefix, suffix, dir, recursive, objType); } } if(DebugOutput.isSetFor("fillATable")) Messages.postDebug("fillATable Checking " + files.size() + " files"); java.util.Date starttime2 = new java.util.Date(); java.util.Date endtime2; long timems2; /* Now loop thur the files adding them to the DB. */ for(int i=0; i < files.size(); i++) { file = (UNFile) files.get(i); filename = file.getName(); // The CanonicalPath is the real absolute path NOT using // any symbolic links. It is the real path. try { fullpath = file.getCanonicalPath(); // If this fullpath is for a system file, // set the user to varian String sysdir = System.getProperty("sysdir"); if(sysdir != null) { UNFile sysfile = new UNFile(sysdir); if(sysfile != null) { // Need to compare the canonical path String csysdir = sysfile.getCanonicalPath(); if(fullpath.startsWith(csysdir + "/")) user = "agilent"; } } } catch (Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem getting cononical path for " + filename); Messages.writeStackTrace(e, "Error caught in fillATable"); return null; } try { // If workspace, be sure user is actual owner of the file. if(objType.equals(Shuf.DB_WORKSPACE)) { String owner = getUnixOwner(fullpath); if(!owner.equals(user)) { Messages.postDebug("Cannot add " + fullpath + "\n to DB. It is not owned by " + user); continue; } } // Add each of these to the DB. // success=false is okay, it may just mean that the entry // is already in the DB. if(objType.equals(Shuf.DB_VNMR_DATA) || objType.equals(Shuf.DB_WORKSPACE) || objType.equals(Shuf.DB_VNMR_PAR)) { success = addVnmrFileToDB(filename, fullpath, user, objType, sleepMs, attrName, attrVal, null); getStudyParentAndSet(objType, fullpath); // If we are in a thread and we want to cause mimimal // interruption, sleep between files. wait less if // not successful. That usually means the file already // exists and nothing is being done. if(sleepMs > 0 && !success) { try { Thread.sleep(sleepMs/2); } catch(Exception e) {} } else if(sleepMs > 0) { try { Thread.sleep(sleepMs); } catch(Exception e) {} } } else if(objType.equals(Shuf.DB_IMAGE_DIR) || objType.equals(Shuf.DB_COMPUTED_DIR)) { success = addImageDirToDB(filename, fullpath, user, objType, sleepMs); getStudyParentAndSet(objType, fullpath); } else if(objType.equals(Shuf.DB_VNMR_RECORD)) success = addRecordToDB(filename, fullpath, user, objType, sleepMs); else if(objType.equals(Shuf.DB_PANELSNCOMPONENTS)) { Object ret = addXmlFileToDB(filename, fullpath, user, objType); if(ret == null) success = false; else success = true; } else if(objType.equals(Shuf.DB_SHIMS)) success = addVnmrFileToDB(filename, fullpath, user, objType, sleepMs, null); else if(objType.equals(Shuf.DB_STUDY) || objType.equals(Shuf.DB_LCSTUDY)) { success = addStudyToDB(filename, fullpath, user, objType, sleepMs); } else if(objType.equals(Shuf.DB_AUTODIR)) success = addAutodirToDB(filename, fullpath, user, objType, sleepMs); else if(objType.equals(Shuf.DB_PROTOCOL)) { DBCommunInfo dbInfo = addXmlFileToDB(filename, fullpath, user, objType); if(dbInfo == null) success = false; else { // For Protocols, we have to get attr from .xml and procpar // The call to addXmlFileToDB started the process and the // partial information is in info. Send that to the call to // addVnmrFileToDB and let it finish creating the Insert command // for adding to the DB. // The fullpath and filename passed to addVnmrFile is the .xml //file and we need the procpar. // It looks like if .xml is "abc/templates/vnmrj/protocols/myprotocol.xml" // then the path we need is "abc/parlib/myprotocol.par" // Create the filename by stripping off the "xml" and adding "par" String parname = filename.substring(0, filename.length() -3); parname = parname + "par"; // Create the par full path by stripping off the // "templates/vnmrj/protocols/myprotocol.xml" and // adding "parlib/myprotocol.par" int index = fullpath.indexOf("templates/vnmrj"); if(index > -1) { String parpath = fullpath.substring(0, index); parpath = parpath + "parlib/" + parname; success = addVnmrFileToDB(parname, parpath, user, objType, 0, dbInfo); } else { // Just debug output while looking for a problem. It shouldn't happen Messages.postDebug("Problem trying to remove \"templates/vnmrj\" " + "from fullpath (" + fullpath + ") in fillATable() while adding protocols."); } } } else if(objType.equals(Shuf.DB_TRASH)) success = addTrashFileToDB(fullpath); if(success) { info.numFilesAdded++; if(info.numFilesAdded%20 == 0) System.out.print("."); if(info.numFilesAdded%500 == 0) { System.out.print("\n"); if(DebugOutput.isSetFor("locTiming")) { endtime2 = new java.util.Date(); timems2 = endtime2.getTime() - starttime2.getTime(); Messages.postDebug("Time for 500 " + objType + " additions " + "(ms): " + timems2); // Restart for next timing cycle starttime2 = new java.util.Date(); } } // Debug output showing each file added if(DebugOutput.isSetFor("fillATableV")) { Messages.postDebug("fillATable added\n " + fullpath); } // Future additions and tests to see if files are // already in the DB go faster if it is vacuumed // now and then. if(filesAdded%10000 == 0 || filesAdded == 50) vacuumDB(objType); filesAdded++; } else { // Output a , every so often for files checked. // This is to keep it from looking like nothing is // going on while it checks 1000's of files. if(totFiles > 0 && totFiles%100 == 0) System.out.print(","); if(totFiles > 0 && totFiles%1000 == 0) System.out.print("\n"); // Debug output showing each file not added if(DebugOutput.isSetFor("fillATableV")) { Messages.postDebug("fillATable: file apparently " + "already in DB:\n "+ fullpath); } } totFiles++; // Number of files tested } catch (Exception ex) { if(!ExitStatus.exiting()) { Messages.writeStackTrace(ex, "Problem in fillATable()"); // continue with the for loop of files if not exiting. } else // vnmrj is shutting down, just return. return files; } Vector mp = MountPaths.getCanonicalPathAndHost(fullpath); String dhost = (String) mp.get(Shuf.HOST); String dpath = (String) mp.get(Shuf.PATH); // Skip .gz files. They shouldn't be here anyway. if(dpath.endsWith(".gz")) continue; hostFullpath = dhost + ":" + dpath; // Is this file in the DB and are we being requested // to set anything? boolean unique = isDBKeyUnique(objType, hostFullpath); if(attrName != null && !unique) { // The problem is that if there are studies // within studies, they will be added in a recursive manner. // In doing so, we can end up setting the study attribute // to the higher level study, and we want it set to the // lowest level study (closest parent). Thus, we want to // set the attribute to the lowest level which will be // the longest path. String val = getAttributeValue(objType, fullpath, localHost, attrName); // If the new val is longer, set it if(val == null || (attrVal.length() > val.length())) { // If an attrName was passed in, set that attr to // attrVal. The attr must be allowed in isParamInList() setNonTagAttributeValue(objType, fullpath, localHost, attrName, "text", attrVal); } } } } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem with file\n \'" + fullpath + "\' \n while filling " +objType +" table in DB"); Messages.postMessage(OTHER|ERROR|LOG, "fillATable failed: objType = " + objType + " dir = " + dir + " user = " + user + " sleepMs = " + sleepMs + "\nfullpath = " + fullpath + " DBCommunInfo Class = " + info); Messages.writeStackTrace(e); } } if(DebugOutput.isSetFor("fillATable") || DebugOutput.isSetFor("locTiming")) { java.util.Date endtime = new java.util.Date(); long timems = endtime.getTime() - starttime.getTime(); Messages.postDebug("fillATable: Time(ms) adding " + filesAdded + " " + objType + " files and testing " + totFiles + " files = " + timems); } if(filesAdded > 0) { // Send notification that this table of the DB has been modified sendTableModifiedNotification(objType); } return files; } public void updateMacro(String objType) { long prevdate=0; long curdate=0; String filepath; ArrayList list; String inLine; BufferedReader in; String datepath; // This is just to determine if the list is empty or not. if(attrList == null) return; list= attrList.getAttrValueList("name", objType); if(objType.equals(Shuf.DB_COMMAND_MACRO)) { filepath = FileUtil.openPath("LOCATOR/commands.xml"); // Note: use savePath in case this file does not exist yet. // In that case, we will create it below. datepath = FileUtil.savePath("USER/.macro_date_stamp"); } else if(objType.equals(Shuf.DB_PPGM_MACRO)) { filepath = FileUtil.openPath("LOCATOR/pulse_sequence_macros.xml"); // Note: use savePath in case this file does not exist yet. // In that case, we will create it below. datepath = FileUtil.savePath("USER/.ppgm_macro_date_stamp"); } else return; if(list != null && list.size() != 0) { // If new date on xml file, do it. // Get the date stamp from the file UNFile f = new UNFile(filepath); curdate = f.lastModified(); prevdate = 0; if(datepath != null) { // Open the file. try { in = new BufferedReader(new FileReader(datepath)); try { // Read one line at a time. while ((inLine = in.readLine()) != null) { // Date is in sec since epoch prevdate = Long.valueOf(inLine).longValue(); } in.close(); } catch(Exception e) { } } catch(Exception e) { // Either file doesn't exit or cannot open it. // Either way, leave prevdate set to 0 and continue. } } // Write out the curdate to the file. try { FileWriter fw = new FileWriter(datepath); String str = String.valueOf(curdate); fw.write(str, 0, str.length()); fw.close(); // Change the mode to all write access String[] cmd = {UtilB.SHTOOLCMD, UtilB.SHTOOLOPTION, "chmod 666 " + datepath}; Runtime rt = Runtime.getRuntime(); Process prcs = null; try { prcs = rt.exec(cmd); } finally { // It is my understanding that these streams are left // open sometimes depending on the garbage collector. // So, close them. if(prcs != null) { OutputStream os = prcs.getOutputStream(); if(os != null) os.close(); InputStream is = prcs.getInputStream(); if(is != null) is.close(); is = prcs.getErrorStream(); if(is != null) is.close(); } } } catch(Exception e) { } } // Only refill if the date stamp changed or table is empty. if(list != null && (list.size() == 0 || prevdate != curdate)) { // Fill the DB fillMacro(objType); } } public void fillMacro(String objType) { ArrayList commandDefinitionList; CommandDefinition cd; String name; Hashtable attribList; int numAttr; String key; String filepath; int numCmds; boolean ok=true; DBCommunInfo info; if(objType.equals(Shuf.DB_COMMAND_MACRO)) filepath = FileUtil.openPath("LOCATOR/commands.xml"); else filepath = FileUtil.openPath("LOCATOR/pulse_sequence_macros.xml"); commandDefinitionList = new ArrayList(); // Parse the file try { CommandBuilder.build(commandDefinitionList, filepath); } catch (Exception e) {} // Clear out the current command_n_macro table clearOutTable(objType, "all"); numCmds = commandDefinitionList.size(); // Loop thru each command/macro and add one at a time // Create a single sql command for each one. for(int i=0; i < numCmds; i++) { cd = (CommandDefinition)commandDefinitionList.get(i); name = cd.getcommandName(); // Initialize a row adding sequence info = addRowToDBInit(objType, name, filepath); // add the "name" attribute. if(info != null) { ArrayList List = new ArrayList(); List.add(name); ok = addRowToDBSetAttr(objType, "name", "text", List, name, info); } else return; // Get attributes and values to set attribList = cd.getattrList(); numAttr = attribList.size(); Enumeration en = attribList.keys(); // put the names of the attributes in order that the values // will follow below. for(int k=0; k < numAttr; k++) { // Get the attribute name and add the name to the list. key = (String)en.nextElement(); if(ok) { // All Macro/command attributes are text type. // If this ever changes, we have to determine what // the type is. For example any attribute starting // with "time_" could be set to date. ArrayList List = new ArrayList(); List.add(attribList.get(key)); ok = addRowToDBSetAttr(objType, key, "text", List , name, info); } } addRowToDBExecute(objType, name, info); } } public DBCommunInfo addRowToDBInit(String objType, String host_fullpath, String fullpath) { long fileStatus; DBCommunInfo info = new DBCommunInfo(); /* We are going to create one very long string by appending each attribute. Then the string will be sent to the DB. */ // Be sure we do not duplicate entries. fileStatus = isDBKeyUniqueAndUpToDate(objType, host_fullpath, fullpath); // Do we need to update it? if(fileStatus == -1) { removeEntryFromDB(objType, host_fullpath, info); } // Is is unique? else if(fileStatus == 0) { // Key is not unique, But it is up to date, return null. return null; } // Front part of the command string. info.addCmd = new StringBuffer ("INSERT INTO " + objType + " ("); // End of cmd string with all of the values info.cmdValueList = new StringBuffer(") VALUES ("); // Save the host_fullpath to be sure we don't change tables // in mid stream. info.hostFullpath = host_fullpath; // Reset flags since we are starting a new command string info.firstAttr = true; info.keySet = false; return info; } public boolean addRowToDBSetAttr(String objType, String attr, String attrType, ArrayList values, String host_fullpath, DBCommunInfo info) { int index; String newValue; boolean foundit; if(info.hostFullpath == null) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem adding " + host_fullpath + " to DB"); Messages.postMessage(OTHER|ERROR|LOG, "addRowToDBInit() must be called before " + "calling addRowToDBSetAttr()" + "\n Problem occured in " + host_fullpath); return false; } // This Test fails when we are adding procpar attributes to a protocol // because info.hostFullpath is for the protocol.xml file // and host_fullpath is for parlib/protocol.par file. // I think this testing was done in the early stages of locator development // and is not necessary now, so just stop doing it. GRS 10/12/11 // if(!info.hostFullpath.equals(host_fullpath)) { // Messages.postMessage(OTHER|ERROR|LOG|MBOX, // "Problem adding " + host_fullpath + " to DB"); // Messages.postMessage(OTHER|ERROR|LOG, // "addRowToDBSetAttr: objType changed after " + // "call to addRowToDBInit()" + // "\n Problem occured in " + host_fullpath); // return false; // host_fullpath must be one of the attributes set. Update the // flag if it is taken care of. if(objType.endsWith(Shuf.DB_MACRO) && attr.equals("name")) info.keySet = true; else if(attr.equals("host_fullpath")) info.keySet = true; // Be sure we do not already have this attr in the command // else we get an error and fail to add the file at all. // If the attr already exist, let the first one win. // Do not give error if attr dup is owner. // Do not give output if image_file, because it normally has // dups between the .img parents procpar and the .fdf header if(info.attrList.contains(attr)) { // if(!attr.equals("owner") && !objType.equals(Shuf.DB_IMAGE_FILE)) { // Messages.postMessage(OTHER|WARN|LOG, // "addRowToDBSetAttr: Duplicate attr named " + // attr + " found when adding\n " + // host_fullpath + // "\n skipping the second entry."); // return with or without error return true; } /* See if this attribute exists in the db. If not, it will be added if possible. */ foundit = isAttributeInDB(objType, attr, attrType, host_fullpath); /* If unsucessful, error exit. */ if(!foundit) return false; // if attritute is a time and is nothing but whitespace, then // skip it. if(attr.startsWith("time_")) { if(((String)values.get(0)).trim().length() == 0) { return false; } } /* if the value has a single quote character in it, it screws up the SQL command. Trap them and skip them. */ try { for(int i=0; i < values.size(); i++) { index = 0; String value = (String)values.get(i); if(value != null) { while((index = value.indexOf('\'', index)) != -1) { // copy value to newValue, skipping each single quote newValue = value.substring(0, index); newValue = newValue.concat(value.substring(index+1, value.length())); values.remove(i); values.add(i, newValue); value = new String(newValue); } } } } catch(Exception e) { Messages.writeStackTrace(e); return false; } // If we are on the first one, do not put a leading comma if(!info.firstAttr) { info.cmdValueList.append(", "); info.addCmd.append(", "); } // Put quotes around the name so that posgres does not force the // attr name to lower case. info.addCmd.append("\"" + attr + "\""); info.attrList.add(attr); // If array type, need values within {}s if(attrType.endsWith("[]")) { info.cmdValueList.append("\'{"); for(int i=0; i < values.size(); i++) { if(i != 0) info.cmdValueList.append(", "); String value = (String)values.get(i); info.cmdValueList.append("\"").append(value).append("\""); } info.cmdValueList.append("}\'"); } // If not array, put single value in string. else { if(values.size() == 0) { info.cmdValueList.append("\'\'"); } else info.cmdValueList.append("\'").append(values.get(0)).append("\'"); } info.firstAttr = false; return true; } public boolean addRowToDBExecute(String objType, String host_fullpath, DBCommunInfo info) { boolean status=true; // Have things been set up? if(info.hostFullpath == null) return false; if(objType.endsWith(Shuf.DB_MACRO) && !info.keySet) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem adding " + host_fullpath + " to DB"); Messages.postMessage(OTHER|ERROR|LOG, "addRowToDBExecute: name MUST be one" + " of the attributes set to add a row." + "\n Problem occured in " + host_fullpath); } else if(!info.keySet){ Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem adding " + host_fullpath + " to DB"); Messages.postMessage(OTHER|ERROR|LOG, "addRowToDBExecute: host_fullpath MUST be one"+ " of the attributes set to add a row." + "\n Problem occured in " + host_fullpath); } // This Test fails when we are adding procpar attributes to a protocol // because info.hostFullpath is for the protocol.xml file // and host_fullpath is for parlib/protocol.par file. // I think this testing was done in the early stages of locator development // and is not necessary now, so just stop doing it. GRS 10/12/11 // if(!info.hostFullpath.equals(host_fullpath)) { // Messages.postMessage(OTHER|ERROR|LOG|MBOX, // "Problem adding " + host_fullpath + " to DB"); // Messages.postMessage(OTHER|ERROR|LOG, // "addRowToDB: objType changed between calls" + // "\n Problem occured in " + host_fullpath); // return false; // Close the attr values list. info.cmdValueList.append(")"); // Create the full command info.addCmd.append(info.cmdValueList); // If sql debug is specified, this will help know where the sql // command came from when it gets printed out in executeUpdate() if(DebugOutput.isSetFor("sqlCmd")) Messages.postDebug("addRowToDBExecute()"); try { executeUpdate(info.addCmd.toString()); } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem adding" + host_fullpath + " to DB"); Messages.writeStackTrace(e,"Error caught in addRowToDBExecute"); } status = false; } info.hostFullpath = ""; info.keySet = false; return status; } public boolean isAttributeInDB(String objType, String attr, String attrType, String fullpath) { boolean foundit=false; // These are not in the LocAttrList table, but they should // already be in the table from its creation. if(attr.startsWith("long_time")) return true; if(DebugOutput.isSetFor("isAttributeInDB")) { Messages.postDebug("isAttributeInDB called for " + attr + " of type " + attrType + " in objType " + objType); } foundit = isAttributeInDB(objType, attr); /* If this attr is not found, add it to the table. */ if(!foundit && attrType != null) { try { if(DebugOutput.isSetFor("isAttributeInDB")) { Messages.postDebug("isAttributeInDB attempting to add " + attr + " to " + objType + " table"); } /* Add the new column to the table. */ executeUpdate("ALTER table " + objType + " ADD \"" + attr + "\" " + attrType); // add to attrList ArrayList attrValues = new ArrayList(); // Add this attribute with an empty list of values. attrValues.add(""); attrList.updateValues(attr, attrValues, objType); } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postMessage(OTHER|ERROR|MBOX|LOG, "Problem adding " + fullpath + " to DB"); Messages.postMessage(OTHER|ERROR|LOG, "isAttributeInDB: Failed to add " + attr + " to DB"); Messages.writeStackTrace(e, "Error caught in isAttributeInDB"); } // If we failed at adding the row, return false return false; } // Now it is in the DB, so return true return true; } else { if(!foundit && attrType == null) return false; } return true; } public boolean isAttributeInDB(String objType, String attr) { ArrayList list; list = attrList.getAllAttributeNames (objType); /* Get each attribute name, one at a time and test it. */ for(int i=0; i < list.size(); i++) { if(attr.equals(list.get(i))) { return true; } } return false; } public boolean isDBKeyUnique(String objType, String key) { java.sql.ResultSet rs; String cmd; if(objType.equals("unknown") || objType.equals("directory") || objType.equals("file")) return true; if(objType.endsWith(Shuf.DB_MACRO)) cmd = new String("SELECT name from " + objType + " WHERE name = \'" + key + "\'"); else cmd = new String("SELECT host_fullpath from " + objType + " WHERE host_fullpath = \'" + key + "\'"); try { rs = executeQuery(cmd); if(rs == null) return false; if(rs.next()) { // Found a row, not unique. return false; } else { // No row found, must be unique. return true; } } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem with " + key + " in DB"); Messages.writeStackTrace(e, "Error caught in isDBKeyUnique"); } haveConnection=false; } return false; } public long isDBKeyUniqueAndUpToDate(String objType, String key, String fullpath) { java.sql.ResultSet rs; String cmd; long dbdate=0, filedate; UNFile file; int status; if(objType.equals("unknown") || objType.equals("directory") || objType.equals("file")) return 1; if(objType.endsWith(Shuf.DB_MACRO)) { // For macros, don't really look for up to date, it doesn't have it cmd = new String("SELECT name from " + objType + " WHERE name = \'" + key + "\'"); } else if(objType.equals(Shuf.DB_VNMR_RECORD) || objType.equals(Shuf.DB_VNMR_REC_DATA) || objType.equals(Shuf.DB_AUTODIR) || objType.equals(Shuf.DB_LCSTUDY) || objType.equals(Shuf.DB_STUDY)) { cmd = new String("SELECT host_fullpath, long_time_saved, " + "corrupt from " + objType + " WHERE host_fullpath = \'" + key + "\'"); } else { cmd = new String("SELECT host_fullpath, long_time_saved from " + objType + " WHERE host_fullpath = \'" + key + "\'"); } try { rs = executeQuery(cmd); if(rs == null) // Not found, is unique return 1; if(rs.next()) { // Found a row, not unique. if(objType.endsWith(Shuf.DB_MACRO)) return 0; // Here is the date as a long from the DB for this entry dbdate = rs.getLong(2); file = new UNFile(fullpath); // Here is the current date when this file was last modified. filedate = file.lastModified()/1000; if(dbdate != filedate) // Not unique, Not up to Date status = -1; else // Not unique, Up to Date status = 0; if(objType.equals(Shuf.DB_VNMR_RECORD) || objType.equals(Shuf.DB_VNMR_REC_DATA) || objType.equals(Shuf.DB_AUTODIR) || objType.equals(Shuf.DB_LCSTUDY) || objType.equals(Shuf.DB_STUDY)) { // We need to see if the checksum.flag file // existance matched the DB entry value. If not, then // tag as out of date. String value; value = rs.getString(3); file = new UNFile(fullpath + File.separator + "checksum.flag"); if(file.exists() && value.equals("corrupt") && status == 0) status = 0; else if(!file.exists() && value.equals("valid") && status == 0) status = 0; else status = -1; } } else { // No row found, must be unique. status = 1; } } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem with " + key + " in DB"); Messages.writeStackTrace(e, "Error caught in isDBKeyUniqueAndUpToDate"); } status = -1; haveConnection = false; } return status; } public boolean destroyDB() { Runtime rt; Process chkit=null; String upath=""; String cmd; // if(sql == null) // return false; // The persistence file for attrList will be out of date it the // DB is destroyed and rebuild, get rid of it. LocAttrList.removePersistenceFile(); try { closeDBConnection(); rt = Runtime.getRuntime(); String sysdir = FileUtil.sysdir(); // For Windows, the pg_ctl cmds require the -D option with // the path to the DB starting with /SFU in unix style. // Start with getting the sysdir in unix style. if(UtilB.OSNAME.startsWith("Windows")) { UNFile file = new UNFile(sysdir); upath = file.getCanonicalPath(); upath = upath + "/pgsql/data"; if(upath.startsWith(UtilB.SFUDIR_INTERIX)) { // Remove it, but then add the /SFU back on upath = upath.substring( UtilB.SFUDIR_INTERIX.length(),upath.length()); upath = "/SFU" + upath; } } // If any process is connected to the DB, it cannot be destroyed. // To force everyone to be disconnected, kill the daemon and // then restart the daemon. Then drop the DB. if(UtilB.OSNAME.startsWith("Windows")) cmd = sysdir + "/pgsql/bin/pg_ctl.exe stop -m fast -D " +upath; else { // See if the /vnmr/pgsql/bin/pg_ctl exists. // if so, use it, if not, call pg_ctl without a fullpath. // This is to allow us to run the system postgres by // just moving /vnmr/pgsql/bin to a saved name out of the way. UNFile file = new UNFile("/vnmr/pgsql/bin/pg_ctl"); if(file.canExecute()) { // Use our released one cmd = "/vnmr/pgsql/bin/pg_ctl stop -m fast"; } else { // Use the system one cmd = "pg_ctl stop -m fast"; } } if(DebugOutput.isSetFor("destroydb")) Messages.postDebug("destroyDB stopping daemon, cmd:" + cmd); String[] cmds = {UtilB.SHTOOLCMD, UtilB.SHTOOLOPTION, cmd}; try { chkit = rt.exec(cmds); // Wait here as long is the process is alive. chkit.waitFor(); } finally { // It is my understanding that these streams are left // open sometimes depending on the garbage collector. // So, close them. if(chkit != null) { OutputStream os = chkit.getOutputStream(); if(os != null) os.close(); InputStream is = chkit.getInputStream(); if(is != null) is.close(); is = chkit.getErrorStream(); if(is != null) is.close(); } } if(UtilB.OSNAME.startsWith("Windows")) cmd = sysdir + "/pgsql/bin/pg_ctl.exe start -l " + sysdir + File.separator + "pgsql/pgsql.log -o -i -D " + upath; else { // See if the /vnmr/pgsql/bin/pg_ctl exists. // if so, use it, if not, call pg_ctl without a fullpath. // This is to allow us to run the system postgres by // just moving /vnmr/pgsql/bin to a saved name out of the way. UNFile file = new UNFile("/vnmr/pgsql/bin/pg_ctl"); if(file.canExecute()) { // Use our released one cmd = "/vnmr/pgsql/bin/pg_ctl start -l " + sysdir + File.separator + "pgsql/pgsql.log"; } else { // Use the system one cmd = "pg_ctl start -l " + sysdir + File.separator + "pgsql/pgsql.log"; } } if(DebugOutput.isSetFor("destroydb")) Messages.postDebug("destroyDB re-starting daemon, cmd:" + cmd); String cmdss[] = {UtilB.SHTOOLCMD, UtilB.SHTOOLOPTION, cmd}; try { chkit = rt.exec(cmdss); // Wait here as long is the process is alive. chkit.waitFor(); } finally { // It is my understanding that these streams are left // open sometimes depending on the garbage collector. // So, close them. if(chkit != null) { OutputStream os = chkit.getOutputStream(); if(os != null) os.close(); InputStream is = chkit.getInputStream(); if(is != null) is.close(); is = chkit.getErrorStream(); if(is != null) is.close(); } } Thread.sleep(500); if(DebugOutput.isSetFor("destroydb")) Messages.postDebug("destroyDB executing 'dropdb vnmr'"); if(UtilB.OSNAME.startsWith("Windows")) cmd = sysdir + "/pgsql/bin/dropdb.exe " + dbName; else cmd = "dropdb " + dbName; try { chkit = rt.exec(cmd); // Wait here as long is the process is alive. chkit.waitFor(); } finally { // It is my understanding that these streams are left // open sometimes depending on the garbage collector. // So, close them. if(chkit != null) { OutputStream os = chkit.getOutputStream(); if(os != null) os.close(); InputStream is = chkit.getInputStream(); if(is != null) is.close(); is = chkit.getErrorStream(); if(is != null) is.close(); } } } catch (Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem destroying the DB. "); Messages.writeStackTrace(e, "Error caught in destroyDB"); return false; } if(DebugOutput.isSetFor("destroydb")) Messages.postDebug("DB Destroyed"); Messages.postMessage(OTHER|INFO|LOG, "DB Destroyed"); return true; } public boolean createEmptyDBandTables() { String cmd; ShufDataParam par; Runtime rt; Process chkit=null; boolean status; // The persistence file for attrList will be out of date it the // DB is destroyed and rebuild, get rid of it. LocAttrList.removePersistenceFile(); if (locatorOff() && !managedb) return false; /* Now create the database anew */ try { rt = Runtime.getRuntime(); String dir = System.getProperty("sysdir"); if(UtilB.OSNAME.startsWith("Windows")) // What do we for system installed postgresql // IF we go back to having Windows having a locator. ??? cmd = dir + "/pgsql/bin/createdb.exe " + dbName; else { // See if the /vnmr/pgsql/bin/createdb exists. // if so, use it, if not, call createdb without a fullpath. // This is to allow us to run the system postgres by // just moving /vnmr/pgsql/bin to a saved name out of the way. UNFile file = new UNFile("/vnmr/pgsql/bin/createdb"); if(file.canExecute()) { // Use our released one cmd = "/vnmr/pgsql/bin/createdb " + dbName; } else { // Use the system one cmd = "createdb " + dbName; } } String[] cmds = {UtilB.SHTOOLCMD, UtilB.SHTOOLOPTION, cmd}; try { chkit = rt.exec(cmds); // Wait here as long is the process is alive. chkit.waitFor(); } finally { // It is my understanding that these streams are left // open sometimes depending on the garbage collector. // So, close them. if(chkit != null) { OutputStream os = chkit.getOutputStream(); if(os != null) os.close(); InputStream is = chkit.getInputStream(); if(is != null) is.close(); is = chkit.getErrorStream(); if(is != null) is.close(); } } } catch (Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Tables"); Messages.writeStackTrace(e, "Error caught in createEmptyDBandTables"); return false; } // Connect to the new dB status = makeDBConnection(); if(status == false) return false; /* Fill the param_list with params to put into shuffler. */ shufDataParams = ReadParamListFile(Shuf.DB_VNMR_DATA, false); shufStudyParams = ReadParamListFile(Shuf.DB_STUDY, false); shufProtocolParams = ReadParamListFile(Shuf.DB_PROTOCOL, false); shufImageParams = ReadParamListFile(Shuf.DB_IMAGE_DIR, false); /* Now create the tables. */ /* DB_VNMR_DATA table */ /* We need to create it with all of the attributes in shufDataParams */ // DB_VNMR_DATA /* Create the start of the command. */ cmd = new String("create table " + Shuf.DB_VNMR_DATA + " ("); /* Now add in all of the attributes in shufDataParams. */ for(int i=0; i < shufDataParams.size(); i++) { par = (ShufDataParam)shufDataParams.get(i); // The param temp is not usable in postgres, so change the // string to "temperature". if(par.equals("temp")) par.setParam(par.getParam().concat("erature")); // Put quotes around the attr name, otherwise, postgres will // convert upper case to lower case. cmd = cmd.concat("\"" + par.getParam() + "\" " + par.getType()); if(i == shufDataParams.size() -1) /* End of command, primary key will not allow duplicates of this column. */ cmd = cmd.concat(", PRIMARY KEY(host_fullpath));"); else cmd = cmd.concat(","); } try { int istatus = executeUpdate(cmd); if(istatus == 0) { Messages.postError("Problem creating DB table on cmd: " + cmd); return false; } executeUpdate("GRANT ALL ON " + Shuf.DB_VNMR_DATA + " TO PUBLIC"); // Adding indices, add substancially to the time it takes to add fids // to the DB. It does not seem to help with the search time, so don't // bother doing it. // executeUpdate("CREATE INDEX fn_inx on vnmr_data (filename)"); // executeUpdate("CREATE INDEX ow_inx on vnmr_data (owner)"); // executeUpdate("CREATE INDEX fp_inx on vnmr_data (fullpath)"); // executeUpdate("CREATE INDEX seq_inx on vnmr_data (seqfil)"); } catch (Exception e) { haveConnection = false; if(!locatorOff()) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Tables"); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); } return false; } // DB_VNMR_PAR /* Create the start of the command. */ cmd = new String("create table " + Shuf.DB_VNMR_PAR + " ("); /* Now add in all of the attributes in shufDataParams. */ for(int i=0; i < shufDataParams.size(); i++) { par = (ShufDataParam)shufDataParams.get(i); // The param temp is not usable in postgres, so change the // string to "temperature". if(par.equals("temp")) par.setParam(par.getParam().concat("erature")); // Put quotes around the attr name, otherwise, postgres will // convert upper case to lower case. cmd = cmd.concat("\"" + par.getParam() + "\" " + par.getType()); if(i == shufDataParams.size() -1) /* End of command, primary key will not allow duplicates of this column. */ cmd = cmd.concat(", PRIMARY KEY(host_fullpath));"); else cmd = cmd.concat(","); } try { int istatus = executeUpdate(cmd); if(istatus == 0) { Messages.postError("Problem creating DB table on cmd: " + cmd); return false; } executeUpdate("GRANT ALL ON " + Shuf.DB_VNMR_PAR + " TO PUBLIC"); } catch (Exception e) { haveConnection = false; Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Tables"); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); return false; } // DB_IMAGE_DIR /* Create the start of the command. */ cmd = new String("create table " + Shuf.DB_IMAGE_DIR + " ("); /* Now add in all of the attributes in shufImageParams. */ for(int i=0; i < shufImageParams.size(); i++) { par = (ShufDataParam)shufImageParams.get(i); // The param temp is not usable in postgres, so change the // string to "temperature". if(par.equals("temp")) par.setParam(par.getParam().concat("erature")); // Put quotes around the attr name, otherwise, postgres will // convert upper case to lower case. cmd = cmd.concat("\"" + par.getParam() + "\" " + par.getType()); if(i == shufImageParams.size() -1) /* End of command, primary key will not allow duplicates of this column. */ cmd = cmd.concat(", PRIMARY KEY(host_fullpath));"); else cmd = cmd.concat(","); } try { int istatus = executeUpdate(cmd); if(istatus == 0) { Messages.postError("Problem creating DB table on cmd: " + cmd); return false; } executeUpdate("GRANT ALL ON " + Shuf.DB_IMAGE_DIR + " TO PUBLIC"); } catch (Exception e) { haveConnection = false; Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Tables"); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); return false; } // DB_VNMR_RECORD /* Create the start of the command. */ cmd = new String("create table " + Shuf.DB_VNMR_RECORD + " ("); /* Now add in all of the attributes in shufDataParams. */ for(int i=0; i < shufDataParams.size(); i++) { par = (ShufDataParam)shufDataParams.get(i); // The param temp is not usable in postgres, so change the // string to "temperature". if(par.equals("temp")) par.setParam(par.getParam().concat("erature")); cmd = cmd.concat("\"" + par.getParam() + "\" " + par.getType()); if(i == shufDataParams.size() -1) /* End of command, primary key will not allow duplicates of this column. */ cmd = cmd.concat(", PRIMARY KEY(host_fullpath));"); else cmd = cmd.concat(","); } try { int istatus = executeUpdate(cmd); if(istatus == 0) { Messages.postError("Problem creating DB table on cmd: " + cmd); return false; } executeUpdate("GRANT ALL ON " + Shuf.DB_VNMR_RECORD + " TO PUBLIC"); } catch (Exception e) { haveConnection = false; Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Tables"); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); return false; } // DB_VNMR_REC_DATA /* Create the start of the command. */ cmd = new String("create table " + Shuf.DB_VNMR_REC_DATA + " ("); /* Now add in all of the attributes in shufDataParams. */ for(int i=0; i < shufDataParams.size(); i++) { par = (ShufDataParam)shufDataParams.get(i); // The param temp is not usable in postgres, so change the // string to "temperature". if(par.equals("temp")) par.setParam(par.getParam().concat("erature")); cmd = cmd.concat("\"" + par.getParam() + "\" " + par.getType()); if(i == shufDataParams.size() -1) /* End of command, primary key will not allow duplicates of this column. */ cmd = cmd.concat(", PRIMARY KEY(host_fullpath));"); else cmd = cmd.concat(","); } try { int istatus = executeUpdate(cmd); if(istatus == 0) { Messages.postError("Problem creating DB table on cmd: " + cmd); return false; } executeUpdate("GRANT ALL ON " + Shuf.DB_VNMR_REC_DATA + " TO PUBLIC"); } catch (Exception e) { haveConnection = false; Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Tables"); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); return false; } /* DB_WORKSPACE table */ /* Create the start of the command. */ cmd = new String("create table " + Shuf.DB_WORKSPACE + " ("); /* Now add in all of the attributes in shufDataParams. */ for(int i=0; i < shufDataParams.size(); i++) { par = (ShufDataParam)shufDataParams.get(i); cmd = cmd.concat("\"" + par.getParam() + "\" " + par.getType()); if(i == shufDataParams.size() -1) /* End of command, primary key will not allow duplicates of this column. */ cmd = cmd.concat(", PRIMARY KEY(host_fullpath));"); else cmd = cmd.concat(","); } try { int istatus = executeUpdate(cmd); if(istatus == 0) { Messages.postError("Problem creating DB table on cmd: " + cmd); return false; } executeUpdate("GRANT ALL ON " + Shuf.DB_WORKSPACE + " TO PUBLIC"); } catch (Exception e) { haveConnection = false; Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Tables"); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); return false; } /* panelsNcomponents table */ cmd = new String( "create table " + Shuf.DB_PANELSNCOMPONENTS + " (host_fullpath text, " + "filename text, " + "fullpath text, " + "owner text, " + "hostname text, " + "hostdest text, " + "arch_lock int, " + "element_type text, " + "element text, " + "panel_type text, " + "type text, " + "comment text, " + "name text, " + "directory text, " + "language text, " + "long_time_saved" + " " + DB_ATTR_INTEGER + ", " + "tag0 text, " + Shuf.DB_TIME_SAVED + " " + DB_ATTR_DATE + ", " + "PRIMARY KEY(host_fullpath)" + ")"); try { executeUpdate(cmd); executeUpdate("GRANT ALL ON " + Shuf.DB_PANELSNCOMPONENTS + " TO PUBLIC"); } catch (Exception e) { haveConnection = false; Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Tables"); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); return false; } /* DB_SHIMS table */ cmd = new String( "create table " + Shuf.DB_SHIMS + " (host_fullpath text, " + "filename text, " + "fullpath text, " + "owner text, " + "investigator text, " + "hostname text, " + "hostdest text, " + "shims text, " + "probe text, " + "directory text, " + "arch_lock int, " + "long_time_saved" + " " + DB_ATTR_INTEGER + ", " + Shuf.DB_TIME_SAVED + " " + DB_ATTR_DATE + ", " + "solvent text, " + "tag0 text, " + "PRIMARY KEY(host_fullpath)" + ")"); try { executeUpdate(cmd); executeUpdate("GRANT ALL ON " + Shuf.DB_SHIMS + " TO PUBLIC"); } catch (Exception e) { haveConnection = false; Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Tables"); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); return false; } /* DB_COMMAND_MACRO table */ cmd = new String( "create table " + Shuf.DB_COMMAND_MACRO + " (name text, " + "tag0 text, " + "PRIMARY KEY(name)" + ")"); try { executeUpdate(cmd); executeUpdate("GRANT ALL ON " + Shuf.DB_COMMAND_MACRO + " TO PUBLIC"); } catch (Exception e) { haveConnection = false; Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Tables"); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); return false; } /* DB_PPGM_MACRO table */ cmd = new String( "create table " + Shuf.DB_PPGM_MACRO + " (name text, " + "label text, " + "tag0 text, " + "PRIMARY KEY(name)" + ")"); try { executeUpdate(cmd); executeUpdate("GRANT ALL ON " + Shuf.DB_PPGM_MACRO + " TO PUBLIC"); } catch (Exception e) { haveConnection = false; Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Tables"); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); return false; } /* DB_STUDY table */ /* Create the start of the command. */ cmd = new String("create table " + Shuf.DB_STUDY + " ("); /* Now add in all of the attributes in shufStudyParams. */ for(int i=0; i < shufStudyParams.size(); i++) { par = (ShufDataParam)shufStudyParams.get(i); // The param temp is not usable in postgres, so change the // string to "temp ". if(par.equals("temp")) par.setParam(par.getParam().concat("erature")); cmd = cmd.concat("\"" + par.getParam() + "\" " + par.getType()); if(i == shufStudyParams.size() -1) cmd = cmd.concat(");"); /* End of command */ else cmd = cmd.concat(","); } try { int istatus = executeUpdate(cmd); if(istatus == 0) { Messages.postError("Problem creating DB table on cmd: " + cmd); return false; } executeUpdate("GRANT ALL ON " + Shuf.DB_STUDY + " TO PUBLIC"); } catch (Exception e) { haveConnection = false; Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Tables"); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); return false; } /* DB_LCSTUDY table */ /* Create the start of the command. */ cmd = new String("create table " + Shuf.DB_LCSTUDY + " ("); /* Now add in all of the attributes in shufStudyParams. */ for(int i=0; i < shufStudyParams.size(); i++) { par = (ShufDataParam)shufStudyParams.get(i); // The param temp is not usable in postgres, so change the // string to "temp ". if(par.equals("temp")) par.setParam(par.getParam().concat("erature")); cmd = cmd.concat("\"" + par.getParam() + "\" " + par.getType()); if(i == shufStudyParams.size() -1) cmd = cmd.concat(");"); /* End of command */ else cmd = cmd.concat(","); } try { int istatus = executeUpdate(cmd); if(istatus == 0) { Messages.postError("Problem creating DB table on cmd: " + cmd); return false; } executeUpdate("GRANT ALL ON " + Shuf.DB_LCSTUDY + " TO PUBLIC"); } catch (Exception e) { haveConnection = false; Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Tables"); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); return false; } /* DB_AUTODIR table */ cmd = new String( "create table " + Shuf.DB_AUTODIR + " (host_fullpath text, " + "datatype text, " + "directory text, " + "fullpath text, " + "filename text, " + "owner text, " + "investigator text, " + "hostname text, " + "hostdest text, " + "subtype text, " + "corrupt text, " + "tag0 text, " + "arch_lock int, " + "long_time_saved" + " " + DB_ATTR_INTEGER + ", " + Shuf.DB_TIME_SAVED + " " + DB_ATTR_DATE + ", " + "PRIMARY KEY(host_fullpath)" + ")"); try { int istatus = executeUpdate(cmd); if(istatus == 0) { Messages.postError("Problem creating DB table on cmd: " + cmd); return false; } executeUpdate("GRANT ALL ON " + Shuf.DB_AUTODIR + " TO PUBLIC"); } catch (Exception e) { haveConnection = false; Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Tables"); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); return false; } /* DB_PROTOCOL table */ /* Create the start of the command. */ cmd = new String("create table " + Shuf.DB_PROTOCOL + " ("); /* Now add in all of the attributes in shufProtocolParams. */ for(int i=0; i < shufProtocolParams.size(); i++) { par = (ShufDataParam)shufProtocolParams.get(i); // The param temp is not usable in postgres, so change the // string to "temp ". if(par.equals("temp")) par.setParam(par.getParam().concat("erature")); cmd = cmd.concat("\"" + par.getParam() + "\" " + par.getType()); // If adding sfrq, then we need to create "field" also to // hold the Tesla field associated with the sfrq freq. // Actually, field should be in the protocol_param_list.img file // in which case, it will be added. If added here, we can // end up with it twice and get an error. // if(par.getParam().equals("sfrq")) { // cmd = cmd.concat(",field float"); if(i == shufProtocolParams.size() -1) cmd = cmd.concat(");"); /* End of command */ else cmd = cmd.concat(","); } try { int istatus = executeUpdate(cmd); if(istatus == 0) { Messages.postError("Problem creating DB table on cmd: " + cmd); return false; } executeUpdate("GRANT ALL ON " + Shuf.DB_PROTOCOL + " TO PUBLIC"); } catch (Exception e) { haveConnection = false; Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Tables"); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); return false; } /* DB_AVAIL_SUB_TYPES table */ // All objTypes that can be subtypes should be entered into // this table with the objType name as the key value in types. // There should then be an attribute name for each objType that // can have subtypes. The value for each of these will be yes or null // for each types. For example // types has values of study, vnmr_data, record, etc // for types = study, attr study = yes, attr record = null // attr vnmr_data = yes, attr shim = null etc. // This says that studies can have subtypes of study and vnmr_data. // filename, fullpath, hostname, owner and arch_lock are not used, but // must exist for the search to succeed. cmd = new String( "create table " + Shuf.DB_AVAIL_SUB_TYPES + " (types text, " + "blank1 text, " + "blank2 text, " + "filename text, " + "fullpath text, " + "hostname text, " + "hostdest text, " + "owner text, " + "arch_lock int, " + Shuf.DB_TIME_RUN + " " + DB_ATTR_DATE + ", " + "PRIMARY KEY(types)" + ")"); try { executeUpdate(cmd); executeUpdate("GRANT ALL ON " + Shuf.DB_AVAIL_SUB_TYPES + " TO PUBLIC"); } catch (Exception e) { haveConnection = false; Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Tables"); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); return false; } // /* DB_PRESCRIPTION table */ // cmd = new String( "create table " + Shuf.DB_PRESCRIPTION + // " (host_fullpath text, " + // "filename text, " + // "fullpath text, " + // "owner text, " + // "hostname text, " + // "tag0 text, " + // "arch_lock int, " + // "long_time_saved" + " " + DB_ATTR_INTEGER + ", " + // Shuf.DB_TIME_SAVED + " " + DB_ATTR_DATE + ", " + // "PRIMARY KEY(host_fullpath)" + // try { // executeUpdate(cmd); // executeUpdate("GRANT ALL ON " + Shuf.DB_PRESCRIPTION + // " TO PUBLIC"); // catch (Exception e) { // haveConnection = false; // Messages.postMessage(OTHER|ERROR|LOG|MBOX, // "Problem creating empty DB Tables"); // Messages.postMessage(OTHER|ERROR|LOG, // "Problem in createEmptyDBandTables " + // "with command: " + cmd); // Messages.writeStackTrace(e); // return false; // /* DB_GRADIENTS table */ // cmd = new String( "create table " + Shuf.DB_GRADIENTS + // " (host_fullpath text, " + // "filename text, " + // "fullpath text, " + // "owner text, " + // "hostname text, " + // "tag0 text, " + // "arch_lock int, " + // "long_time_saved" + " " + DB_ATTR_INTEGER + ", " + // Shuf.DB_TIME_SAVED + " " + DB_ATTR_DATE + ", " + // "PRIMARY KEY(host_fullpath)" + // try { // executeUpdate(cmd); // executeUpdate("GRANT ALL ON " + Shuf.DB_GRADIENTS + // " TO PUBLIC"); // catch (Exception e) { // haveConnection = false; // Messages.postMessage(OTHER|ERROR|LOG|MBOX, // "Problem creating empty DB Tables"); // Messages.postMessage(OTHER|ERROR|LOG, // "Problem in createEmptyDBandTables " + // "with command: " + cmd); // Messages.writeStackTrace(e); // return false; /* DB_TRASH table */ cmd = new String( "create table " + Shuf.DB_TRASH + " (host_fullpath text, " + "filename text, " + "fullpath text, " + "orig_fullpath text, " + "orig_host_fullpath text, " + "objtype text, " + "hostname text, " + "hostdest text, " + "owner text, " + "tag0 text, " + "datetrashed " + DB_ATTR_DATE + ", " + "arch_lock int, " + "long_time_saved" + " " + DB_ATTR_INTEGER + ", " + "PRIMARY KEY(host_fullpath)" + ")"); try { executeUpdate(cmd); executeUpdate("GRANT ALL ON " + Shuf.DB_TRASH + " TO PUBLIC"); } catch (Exception e) { haveConnection = false; Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Table, " + Shuf.DB_TRASH); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); return false; } /* DB_VERSION table */ cmd = new String( "create table " + Shuf.DB_VERSION + " (hostname text, " + "version text, " + "networkMode text, " + "vnmrjversion text" + ");"); try { executeUpdate(cmd); executeUpdate("GRANT ALL ON " + Shuf.DB_VERSION + " TO PUBLIC"); } catch (Exception e) { haveConnection = false; Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Table, " + Shuf.DB_VERSION); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); return false; } // Get value for networkMode String networkMode = determineNetworkMode(); String vnmrjversion = getVnmrjVersion(); String version = getPostgresVersion(); /* Add version to DB_VERSION */ cmd = new String("INSERT INTO " + Shuf.DB_VERSION + " VALUES (\'" + localHost + "\', \'" + version + "\', \'" + networkMode + "\', \'" + vnmrjversion + "\');"); try { executeUpdate(cmd); } catch (Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem adding" + Shuf.DB_VERSION + " to DB"); Messages.writeStackTrace(e); } /* NOTIFY table */ try { cmd = "create table notify (host text, PRIMARY KEY(host), "; // Now add a column for the name of each objType vnmr // plans to use this notification for. for(int i=0; i<Shuf.OBJTYPE_LIST.length; i++) { cmd = cmd.concat(Shuf.OBJTYPE_LIST[i] + " text "); // No trailing comma if(i != Shuf.OBJTYPE_LIST.length -1) cmd = cmd.concat(", "); else cmd = cmd.concat(")"); } executeUpdate(cmd); executeUpdate("GRANT ALL ON notify" + " TO PUBLIC"); // add a row to the DB for this host cmd = "INSERT INTO notify (host) VALUES (\'" + localHost + "\')"; executeUpdate(cmd); } catch(Exception e) { haveConnection = false; Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Table, " + Shuf.DB_LINK_MAP); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); return false; } /* DB_LINK_MAP table */ cmd = new String( "create table " + Shuf.DB_LINK_MAP + " (dhost_dpath text, " + " dhost text, " + " dpath text, " + " PRIMARY KEY(dhost_dpath));"); try { executeUpdate(cmd); executeUpdate("GRANT ALL ON " + Shuf.DB_LINK_MAP + " TO PUBLIC"); } catch (Exception e) { haveConnection = false; Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty DB Table, " + Shuf.DB_LINK_MAP); Messages.postMessage(OTHER|ERROR|LOG, "Problem in createEmptyDBandTables " + "with command: " + cmd); Messages.writeStackTrace(e); return false; } Messages.postMessage(OTHER|INFO|LOG, "Empty DB Created"); return true; } public String getVnmrjVersion() { String strPath = FileUtil.openPath(FileUtil.SYS_VNMR+"/vnmrrev"); BufferedReader reader; String strLine; StringTokenizer tok; String verNum="", revision=""; try { reader = new BufferedReader(new FileReader(strPath)); strLine = reader.readLine(); tok = new StringTokenizer(strLine); if(tok.countTokens() < 3) { } // Skip the first 2 tokens which should be Vnmrj and VERSION tok.nextToken(); tok.nextToken(); // The third one should be the version basic number verNum = tok.nextToken().trim(); // If there is a revision, there will be 2 more tokens if(tok.countTokens() > 1) { // Skip 'REVISION' string tok.nextToken(); // get the revision letter or string revision = tok.nextToken().trim(); // Only keep the first character revision = revision.substring(0, 1); } } catch(Exception ex) { // Something went wrong. Log to the log file and return // empty string Messages.postLog("getVnmrjVersion: Problem getting vnmrj version from /vnmr/vnmrrev"); } verNum = verNum + revision; return verNum; } // This is only to be called by createEmptyDBandTables which should // in turn only be called if PGHOST = the local host. In that case, // the only reason to have networkMode other than false, is if we // have been directed to do so by finding a file // /usr/varian/config/NMR_NETWORK_DB private String determineNetworkMode() { String usingNetServer; UNFile file; if(UtilB.OSNAME.startsWith("Windows")) file = new UNFile(UtilB.SFUDIR_WINDOWS + "/usr/varian/config/NMR_NETWORK_DB"); else file = new UNFile("/usr/varian/config/NMR_NETWORK_DB"); if(file.exists()) usingNetServer = "true"; else usingNetServer = "false"; return usingNetServer; } public HashArrayList ReadParamListFile(String objType, boolean limited) { String filepath; String filename; BufferedReader in; String param, type, inLine=null; StringTokenizer tok; ShufDataParam par; boolean dup; HashArrayList paramList; paramList = new HashArrayList(); /* Go ahead and add default params. */ paramList.put("host_fullpath", new ShufDataParam("host_fullpath", DB_ATTR_TEXT)); paramList.put("filename", new ShufDataParam("filename", DB_ATTR_TEXT)); paramList.put("fullpath", new ShufDataParam("fullpath", DB_ATTR_TEXT)); paramList.put("directory", new ShufDataParam("directory", DB_ATTR_TEXT)); paramList.put("owner", new ShufDataParam("owner", DB_ATTR_TEXT)); paramList.put("hostname", new ShufDataParam("hostname", DB_ATTR_TEXT )); paramList.put("hostdest", new ShufDataParam("hostdest", DB_ATTR_TEXT )); paramList.put("arch_lock", new ShufDataParam("arch_lock", DB_ATTR_INTEGER)); paramList.put("long_time_saved", new ShufDataParam("long_time_saved", DB_ATTR_INTEGER)); paramList.put("time_created", new ShufDataParam("time_created", DB_ATTR_DATE)); paramList.put(Shuf.DB_TIME_RUN, new ShufDataParam(Shuf.DB_TIME_RUN, DB_ATTR_DATE)); paramList.put(Shuf.DB_TIME_SAVED, new ShufDataParam(Shuf.DB_TIME_SAVED, DB_ATTR_DATE)); // Several objTypes use shufDataParams which is filled based on // the type DB_VNMR_DATA if(objType.equals(Shuf.DB_VNMR_DATA)) { paramList.put("pslabel", new ShufDataParam("pslabel", DB_ATTR_TEXT)); paramList.put("operator_", new ShufDataParam("operator_",DB_ATTR_TEXT )); paramList.put("operator", new ShufDataParam("operator", DB_ATTR_TEXT)); paramList.put("investigator", new ShufDataParam("investigator", DB_ATTR_TEXT)); paramList.put("dataid", new ShufDataParam("dataid", DB_ATTR_TEXT)); paramList.put(Shuf.DB_AUTODIR, new ShufDataParam(Shuf.DB_AUTODIR, DB_ATTR_TEXT)); paramList.put(Shuf.DB_STUDY, new ShufDataParam(Shuf.DB_STUDY, DB_ATTR_TEXT)); paramList.put(Shuf.DB_LCSTUDY, new ShufDataParam(Shuf.DB_LCSTUDY, DB_ATTR_TEXT)); paramList.put("corrupt", new ShufDataParam("corrupt", DB_ATTR_TEXT)); paramList.put("fda", new ShufDataParam("fda", DB_ATTR_TEXT)); paramList.put("record", new ShufDataParam("record", DB_ATTR_TEXT)); paramList.put("exp", new ShufDataParam("exp", DB_ATTR_INTEGER)); // This autodir is to hold the DB_AUTODIR information as the local // mounted path. paramList.put("autodir", new ShufDataParam("autodir", DB_ATTR_TEXT)); } if(objType.equals(Shuf.DB_STUDY) || objType.equals(Shuf.DB_LCSTUDY)) { paramList.put(Shuf.DB_AUTODIR, new ShufDataParam(Shuf.DB_AUTODIR, DB_ATTR_TEXT)); // This autodir is to hold the DB_AUTODIR information as the local // mounted path. paramList.put("autodir", new ShufDataParam("autodir", DB_ATTR_TEXT)); paramList.put(Shuf.DB_STUDY, new ShufDataParam(Shuf.DB_STUDY, DB_ATTR_TEXT)); paramList.put(Shuf.DB_LCSTUDY, new ShufDataParam(Shuf.DB_LCSTUDY, DB_ATTR_TEXT)); paramList.put("corrupt", new ShufDataParam("corrupt", DB_ATTR_TEXT)); } if(objType.equals(Shuf.DB_IMAGE_DIR)) { // Hold parent's path for DB_IMAGE_FILE paramList.put(Shuf.DB_IMAGE_DIR, new ShufDataParam(Shuf.DB_IMAGE_DIR, DB_ATTR_TEXT)); paramList.put(Shuf.DB_STUDY, new ShufDataParam(Shuf.DB_STUDY, DB_ATTR_TEXT)); } if(objType.equals(Shuf.DB_PROTOCOL)) { paramList.put("language", new ShufDataParam("language", DB_ATTR_TEXT)); paramList.put("operator_", new ShufDataParam("operator_",DB_ATTR_TEXT )); paramList.put("operator", new ShufDataParam("operator", DB_ATTR_TEXT)); paramList.put("investigator", new ShufDataParam("investigator", DB_ATTR_TEXT)); } /* Now add some tag columns. */ for(int k=0; k < NUM_TAGS; k++) { paramList.put("tag" + Integer.toString(k), new ShufDataParam("tag" + Integer.toString(k), DB_ATTR_TEXT)); } // There can be one xxx_param_list for each appmode. For adding files // to the DB, we must have the full list, so we need to accumulate the // params from all appmode lists. For the limited list, we just // use the xxx_param_list in LOCATOR/xxx_param_list. // Create a list of files to loop through, adding only one for the // limited list. Then the code below can just always loop in the // same manner. // Start with the beginning of the path ArrayList fileList = new ArrayList(); if(limited) { fileList.add("LOCATOR/"); } else { fileList.add("SYSTEM/LOCATOR/"); for(int i=0; i < appmodFileList.length; i++) fileList.add("SYSTEM/" + appmodFileList[i]); } // Now, depending on the objType, we need to add the actual filename // to all items in the fileList for(int i=0; i < fileList.size(); i++) { if(objType.equals(Shuf.DB_VNMR_DATA)) { filename = (String) fileList.get(i); filename = filename.concat("shuffler_param_list"); // Replace this position in the list with the full path needed fileList.remove(i); fileList.add(i, filename); } else if(objType.equals(Shuf.DB_STUDY)) { filename = (String) fileList.get(i); filename = filename.concat("study_param_list"); // Replace this position in the list with the full path needed fileList.remove(i); fileList.add(i, filename); } else if(objType.equals(Shuf.DB_PROTOCOL)) { filename = (String) fileList.get(i); filename = filename.concat("protocol_param_list"); // Replace this position in the list with the full path needed fileList.remove(i); fileList.add(i, filename); } else if(objType.equals(Shuf.DB_IMAGE_DIR) || objType.equals(Shuf.DB_COMPUTED_DIR)) { filename = (String) fileList.get(i); filename = filename.concat("image_param_list"); // Replace this position in the list with the full path needed fileList.remove(i); fileList.add(i, filename); } else { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Param list not supported for " + objType); return paramList; } } // Now loop through the paths in fileList for(int i=0; i < fileList.size(); i++) { // Get the absolute path from the utility filename = (String) fileList.get(i); filepath = FileUtil.openPath(filename); if(filepath == null) { continue; } try { UNFile file = new UNFile(filepath); FileReader fr = new FileReader(file); if(fr == null) { continue; } in = new BufferedReader(fr); } catch(Exception e) { continue; } try { // Read one line at a time. while ((inLine = in.readLine()) != null) { /* skip blank lines and comment lines. */ if (inLine.length() > 1 && !inLine.startsWith(" inLine.trim(); tok = new StringTokenizer(inLine); if(tok.countTokens() < 2) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Each non comment line in " + filepath + "\n Must contain two entries" + " where the first is the param name"+ "\n and the second is the data" + " type (text, int, float or date)"); in.close(); continue; } param = tok.nextToken().trim(); type = tok.nextToken().trim(); // Be sure date type is the correct one. if(type.equals("date")) type = DB_ATTR_DATE; // If float, make it float8 if(type.startsWith("float") && type.endsWith("[]")) type = DB_ATTR_FLOAT8_ARRAY; else if(type.startsWith("float")) type = DB_ATTR_FLOAT8; // Try making all integers, float8 also else if(type.startsWith("int") && type.endsWith("[]")) type = DB_ATTR_FLOAT8_ARRAY; else if(type.startsWith("int")) type = DB_ATTR_FLOAT8; dup = false; // Be sure this item is not already in the list for(int k=0; k < paramList.size(); k++) { par = (ShufDataParam)paramList.get(k); if(param.equals(par.getParam())) { dup = true; break; } } if(!dup) { // Not a duplicate, add the item. paramList.put(param,new ShufDataParam(param, type)); } } } } catch(Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem reading " + filename); Messages.postMessage(OTHER|ERROR|LOG, "ReadParamListFile failed on " + filepath + " on line: '" + inLine + "'"); Messages.writeStackTrace(e); } try { in.close(); } catch(Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem closing " + filename); Messages.writeStackTrace(e,"Error caught in ReadParamListFile"); } } if(DebugOutput.isSetFor("ReadParamListFile")) Messages.postDebug("ReadParamListFile Attributes: " + paramList.keySet()); return paramList; } public int isParamInList(String objType, String param, String type) { ShufDataParam par; int result; // For shims, disallow everything starting with x, y or z. if(objType.equals(Shuf.DB_SHIMS)) { if(param.startsWith("x") || param.startsWith("y") || param.startsWith("z")) return 0; else return 1; } // For Study else if(objType.equals(Shuf.DB_STUDY) || objType.equals(Shuf.DB_LCSTUDY)) { for(int i=0; i < shufStudyParams.size(); i++) { par = (ShufDataParam)shufStudyParams.get(i); result = par.equals(param, type); if(result > 0) return result; } } // For Protocol else if(objType.equals(Shuf.DB_PROTOCOL)) { for(int i=0; i < shufProtocolParams.size(); i++) { par = (ShufDataParam)shufProtocolParams.get(i); result = par.equals(param, type); if(result > 0) return result; } } // For DB_IMAGE_DIR and DB_IMAGE_FILE else if(objType.equals(Shuf.DB_IMAGE_DIR) || objType.equals(Shuf.DB_COMPUTED_DIR) || objType.equals(Shuf.DB_IMAGE_FILE)) { for(int i=0; i < shufImageParams.size(); i++) { par = (ShufDataParam)shufImageParams.get(i); result = par.equals(param, type); if(result > 0) return result; } } // For AutoDir allow everything else if(objType.equals(Shuf.DB_AUTODIR)) { return 1; } else { for(int i=0; i < shufDataParams.size(); i++) { par = (ShufDataParam)shufDataParams.get(i); result = par.equals(param, type); if(result > 0) return result; } } return 0; } static boolean inUse=false; static boolean haveConnection=false; public boolean checkDBConnection() { if(haveConnection) return true; else return makeDBConnection(); } // reduce the number of error messages when postgres_deamon is not running. static int errCnt=0; public boolean makeDBConnection() { String port=null; // If locator is turned off, just return true // if(locatorOff() && !managedb) if (locatorOff()) return false; if(inUse) { return false; } haveConnection = false; // Get the port number if(port == null) { port = System.getProperty("dbport"); if(port == null) port = "5432"; } try { if(newpostgres.equals("true")) Class.forName("org.postgresql.Driver"); else Class.forName("postgresql.Driver"); } catch (ClassNotFoundException e) { Messages.postDebug("PostgreSQL JDBC Driver Not Found!"); e.printStackTrace(); } // Create url with host, port and /dbname // For some reason Windows had a problem with an actual name // for dbhost, but using the string localhost works. String url; if(dbHost.equals(localHost)) url = new String("jdbc:postgresql://" + "localhost" + ":" + port + "/" + dbName); else url = new String("jdbc:postgresql://" + dbHost + ":" + port + "/" + dbName); // Get the current user name String user = System.getProperty("user.name"); String passwd = new String("jjj"); // String passwd = new String(""); // Connect to database try { if(DebugOutput.isSetFor("makeDBConnection")) Messages.postDebug("makeDBConnection url = " + url + " user = " + user + " passwd = " + passwd); db = DriverManager.getConnection(url, user, passwd); if(DebugOutput.isSetFor("makeDBConnection")) Messages.postDebug("DriverManager connection = " + db); sql = db.createStatement(); } catch (SQLException e) { /* Avoid a lot of these messages */ if (connectMessage == 1) { // If the postmaster.pid file does not exist, postgres // is off. String filepath = FileUtil.openPath(FileUtil.sysdir() + "/pgsql/data/postmaster.pid"); if(filepath==null) { locatoroff = true; } else { Messages.postError("makeDBConnection failed on " + dbHost + " port " + port + ",\n be sure database " + "exists and that " + user + " has access to it.\n Try having the " + "system administrator execute " + "the command 'createuser " + user + "'." + "\n Also check that if a special port number " + " is used for postgres,\n that this user " + "has the environment variable \'PGPORT\' set " + " correctly.\n Is it possible that a specific" + " error can be found in the log file:\n" + " /vnmr/pgsql/pgsql.log"); } } // Remove the locAttrList persistence file in case it // is screwed up connectMessage = 0; LocAttrList.removePersistenceFile(); return false; } connectMessage = 1; haveConnection=true; inUse=false; try { executeUpdate("SET DateStyle TO \'ISO\'"); } catch (Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem connecting to DB. The locator will" + " not function."); inUse=false; return false; } return true; } public void closeDBConnection() { if(DebugOutput.isSetFor("closeDBConnection")) System.out.println("**closeDBConnection**"); try { if(sql != null) sql.close(); if(db != null) db.close(); } catch (Exception e) {} } private DBCommunInfo addXmlFileToDB (String filename, String fullpath, String user, String objType) { String dhostFullpath; BufferedReader in; String inLine=null; String rootFilename; String string=null; int index; String attr; String value; boolean foundName=false; StringReader sr; StreamTokenizerQuotedNewlines tok; StringTokenizer tokstring; long timeSavedSec; UNFile file; int typeMatch; String directory; java.util.Date timeSavedDate; DBCommunInfo info=null; String dpath, dhost; String language; if(DebugOutput.isSetFor("addFileToDB")) { Messages.postDebug("addXmlFileToDB(): filename = " + filename + " fullpath = " + fullpath + "\nuser = " + user + " objType = " + objType); } try { Vector mp = MountPaths.getCanonicalPathAndHost(fullpath); dhost = (String) mp.get(Shuf.HOST); dpath = (String) mp.get(Shuf.PATH); } catch(Exception e) { Messages.postDebug("Problem getting cononical path for " + fullpath); Messages.writeStackTrace(e); dhost = localHost; dpath = fullpath; } dhostFullpath = new String(dhost + ":" + dpath); file = new UNFile(fullpath); // Open the file. try { in = new BufferedReader(FileUtil.getUTFReader(file)); } catch(Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem opening " + fullpath); return null; } timeSavedSec = file.lastModified(); // strip suffix off of the filename before adding to DB. index = filename.lastIndexOf('.'); rootFilename = filename.substring(0, index); // While we are at it, see if there is a language extension // such as filename.ja.xml language=FileUtil.langExt(rootFilename); if(language!=null){ //rootFilename=rootFilename.replace(language,""); language=language.replace(".",""); } else language="en"; // Strip off the filename and create a directory string. index = fullpath.lastIndexOf(File.separator); if(index > 0) directory = fullpath.substring(0, index); else directory = fullpath; // Now get just the last directory level name index = directory.lastIndexOf(File.separator); if(index > 0) directory = directory.substring(index+1); // Start the process of adding a row to the DB info = addRowToDBInit(objType, dhostFullpath, fullpath); // If failure, leave. if(info == null) { try { in.close(); } catch(Exception e) {} return null; } // Add some standard attributes. ArrayList List = new ArrayList(); List.add(dhostFullpath); addRowToDBSetAttr(objType, "host_fullpath", DB_ATTR_TEXT, List, dhostFullpath, info); List.clear(); List.add(rootFilename); addRowToDBSetAttr(objType, "filename", DB_ATTR_TEXT, List, dhostFullpath, info); List.clear(); List.add(dpath); addRowToDBSetAttr(objType, "fullpath", DB_ATTR_TEXT, List, dhostFullpath, info); List.clear(); List.add(user); addRowToDBSetAttr(objType, "owner", DB_ATTR_TEXT, List, dhostFullpath, info); List.clear(); List.add(localHost); addRowToDBSetAttr(objType, "hostname", DB_ATTR_TEXT, List, dhostFullpath, info); List.clear(); List.add(dhost); addRowToDBSetAttr(objType, "hostdest", DB_ATTR_TEXT, List, dhostFullpath, info); List.clear(); List.add(String.valueOf(timeSavedSec/1000)); addRowToDBSetAttr(objType, "long_time_saved", DB_ATTR_INTEGER, List, dhostFullpath, info); List.clear(); List.add(directory); addRowToDBSetAttr(objType, "directory", DB_ATTR_TEXT, List, dhostFullpath, info); List.clear(); List.add(language); addRowToDBSetAttr(objType, "language", DB_ATTR_TEXT, List, dhostFullpath, info); List.clear(); timeSavedDate = new java.util.Date(timeSavedSec); // Convert timeSavedDate to date string SimpleDateFormat formatter = new SimpleDateFormat ("MMM d, yyyy HH:mm:ss"); String str = formatter.format(timeSavedDate); List.add(str); addRowToDBSetAttr(objType, Shuf.DB_TIME_SAVED, DB_ATTR_DATE, List, dhostFullpath, info); // Get the line/s to parse from the first occurence of a '<' // followed by an alpha character and continuing to the next '>'. try { // Read one line at a time. while ((inLine = in.readLine()) != null) { inLine = inLine.trim(); if (string == null && inLine.length() > 1 && inLine.startsWith("<")) { // Is next char a letter? if(Character.isLetter(inLine.charAt(1))) { // We are at the start of our string, save it. string = new String(inLine); // If this line contains the closing '>', then // stop reading now. if ((index = inLine.indexOf('>')) != -1) { // Only take the string up to the '>' string = inLine.substring(0, index); break; } } } // concatonate to string until '>' is found. else if (string != null && inLine.indexOf('>') == -1) { string = string.concat(" " + inLine); } // Include the line up to the '>' else if (string != null && (index = inLine.indexOf('>')) != -1) { // Concatonate up to the '>' and include a space. string = string.concat(" " + inLine.substring(0, index)); break; } } in.close(); if(string == null) throw (new Exception("Badly formated xml file")); } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem reading " + fullpath); Messages.postMessage(OTHER|ERROR|LOG, "addXmlFileToDB failed on line: '" + inLine + "'"); Messages.writeStackTrace(e); } try { in.close(); } catch(Exception eio) {} return null; } // We should now have something like // <template panel_type="acquisition" element_type="panels" // Tokenize the string. // Use StreamTokenizer because we can keep the quoted string // as a single token. StringTokenizer does not allow that. // I had to create StreamTokenizerQuotedNewlines to allow quoted // string to contain newLines. The standard one ends the quote // at the end of a line. Sun had a bug reported about this // (4239144) and refused to add an option to allow multiple lines // in a quoted string. GRS sr = new StringReader(string); tok = new StreamTokenizerQuotedNewlines(sr); // Define the quote character tok.quoteChar('\"'); // Define additional char to be treated as normal letter. tok.wordChars('_', '_'); try { // Dump the first two tokens. They will be '<' and the // word following '<'. tok.nextToken(); tok.nextToken(); // Now we should have a sequence of TT_WORD, '=', quoted string // for each attribute being defined. while(tok.nextToken() != StreamTokenizerQuotedNewlines.TT_EOF) { if(tok.ttype != StreamTokenizerQuotedNewlines.TT_WORD) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem with syntax setting attributes" + " from the file:\n " + fullpath); Messages.postMessage(OTHER|ERROR|LOG, "addXmlFileToDB failed on line: '" + string + "'"); break; // Bail out } // Get the name of the attribute being set. attr = tok.sval; tok.nextToken(); if(tok.ttype != '=') { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem with syntax (=) setting attributes" + " from the file:\n" + fullpath); Messages.postMessage(OTHER|ERROR|LOG, "addXmlFileToDB failed on line: '" + string + "'"); break; // Bail out } tok.nextToken(); if(tok.ttype != '\"') { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem with syntax (\") setting attributes" + " from the file:\n" + fullpath); Messages.postMessage(OTHER|ERROR|LOG, "addXmlFileToDB failed on line: '" + string + "'"); break; // Bail out } // Get the value for this attribute. value = tok.sval; // We cannot add an empty string to the DB so if the value // is empty, make it a single space. if(value.length() == 0) value = " "; if(attr.equals("name")) foundName = true; List = new ArrayList(); List.add(value); /* For Protocols, see if we want to put this param in the db or not. Returns 0 for false, 1 for true and 2 for true except item in DB is array type. */ if(objType.equals(Shuf.DB_PROTOCOL)) { if(attr.startsWith("time_")) typeMatch = isParamInList(objType, attr, DB_ATTR_DATE); else if(attr.equals("field") || attr.equals("sfrq")) typeMatch = isParamInList(objType, attr, DB_ATTR_FLOAT8); else typeMatch = isParamInList(objType, attr, DB_ATTR_TEXT); } else typeMatch = 1; /* If == 1, the type matches and is not an array. */ if(typeMatch == 1) { if(attr.startsWith("time_")) addRowToDBSetAttr(objType, attr, DB_ATTR_DATE, List, dhostFullpath, info); else addRowToDBSetAttr(objType, attr, DB_ATTR_TEXT, List, dhostFullpath, info); } /* We have a param match and it is an array type. */ if(typeMatch == 2) { // We need to parse the string into individual values. // They should be comma separated all in one string. string = new String((String)List.get(0)); tokstring = new StringTokenizer(string, ","); // Make a new empty list to fill in List = new ArrayList(); while(tokstring.hasMoreTokens()) { List.add(tokstring.nextToken().trim()); } addRowToDBSetAttr(objType, attr, DB_ATTR_TEXT_ARRAY, List, dhostFullpath, info); } } } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem reading " + fullpath); Messages.postMessage(OTHER|ERROR|LOG, "addXmlFileToDB failed on line: '" + string + "'"); } return null; } // If 'name' was not given, use filename. if(!foundName) { List = new ArrayList(); List.add(rootFilename); addRowToDBSetAttr(objType, "name", DB_ATTR_TEXT, List, dhostFullpath, info); } // Complete the process of adding a row to the DB // For Protocol, don't call the execute. Instead, the caller // will pass the returned info to addVnmrFileToDB to get more attributes // from the Protocol procpar file. if(!objType.equals(Shuf.DB_PROTOCOL)) addRowToDBExecute(objType, dhostFullpath, info); // The returned "info", is only used for Protocols return info; } public boolean addTrashFileToDB(String fullpath) { DBCommunInfo info; boolean status=true; TrashInfo trashInfo; String tHostFullpath; String dhost, dpath; // We need to open and read the trashinfo file from fullpath // into a TrashInfo object. trashInfo = TrashInfo.readTrashInfoFile(fullpath); // null means file was not found if(trashInfo == null) return false; try { Vector mp = MountPaths.getCanonicalPathAndHost(fullpath); dhost = (String) mp.get(Shuf.HOST); dpath = (String) mp.get(Shuf.PATH); } catch(Exception e) { Messages.postDebug("Problem getting canonical path for " + fullpath); Messages.writeStackTrace(e); dhost = localHost; dpath = fullpath; } // The trashInfo.hostFullpath and trashInfo.fullpath are set to // the original values. We need to add this item with its // new path which is the arg fullpath. tHostFullpath = new String(dhost + ":" + dpath); // Start the process of adding a row to the DB info = addRowToDBInit(Shuf.DB_TRASH, tHostFullpath, trashInfo.fullpath); // If failure, leave. if(info == null) { return false; } // Values are passed as an ArrayList in case they are to be an array. // Note: the first arg of addRowToDBSetAttr() is the objType, but // in this case, that is DB_TRASH, not the objType of the // file that has been trashed. ArrayList List = new ArrayList(); List.add(tHostFullpath); addRowToDBSetAttr(Shuf.DB_TRASH, "host_fullpath", DB_ATTR_TEXT, List, tHostFullpath, info); List.clear(); List.add(trashInfo.filename); addRowToDBSetAttr(Shuf.DB_TRASH, "filename", DB_ATTR_TEXT, List, tHostFullpath, info); List.clear(); List.add(trashInfo.fullpath); addRowToDBSetAttr(Shuf.DB_TRASH, "fullpath", DB_ATTR_TEXT, List, tHostFullpath, info); List.clear(); List.add(trashInfo.origFullpath); addRowToDBSetAttr(Shuf.DB_TRASH, "orig_fullpath", DB_ATTR_TEXT, List, tHostFullpath, info); List.clear(); List.add(trashInfo.origHostFullpath); addRowToDBSetAttr(Shuf.DB_TRASH, "orig_host_fullpath", DB_ATTR_TEXT, List, tHostFullpath, info); List.clear(); List.add(trashInfo.owner); addRowToDBSetAttr(Shuf.DB_TRASH, "owner", DB_ATTR_TEXT, List, tHostFullpath, info); List.clear(); List.add(trashInfo.objType); addRowToDBSetAttr(Shuf.DB_TRASH, "objtype", DB_ATTR_TEXT, List, tHostFullpath, info); List.clear(); List.add(localHost); addRowToDBSetAttr(Shuf.DB_TRASH, "hostname", DB_ATTR_TEXT, List, tHostFullpath, info); List.clear(); List.add(trashInfo.dhost); addRowToDBSetAttr(Shuf.DB_TRASH, "hostdest", DB_ATTR_TEXT, List, tHostFullpath, info); List.clear(); SimpleDateFormat formatter = new SimpleDateFormat ("MMM d, yyyy HH:mm:ss"); String str = formatter.format(trashInfo.dateTrashed); List.add(str); addRowToDBSetAttr(Shuf.DB_TRASH, "datetrashed", DB_ATTR_DATE, List, tHostFullpath, info); UNFile dir = new UNFile(fullpath); long timeSavedSec = dir.lastModified(); // The division by 1000 is to get seconds instead of milliseconds. // milliseconds over flows the int. List.clear(); List.add(String.valueOf(timeSavedSec/1000)); addRowToDBSetAttr(Shuf.DB_TRASH, "long_time_saved", DB_ATTR_INTEGER, List, tHostFullpath, info); status = addRowToDBExecute(Shuf.DB_TRASH,tHostFullpath, info); return status; } public boolean addRecordToDB(String filename, String fullpath, String owner, String objType, long sleepMs){ boolean success=false; File[] files; UNFile file; String name, path=null; // Add the record itself which will get params from // *.REC/acqfil/procpar try { // Be sure fullpath is the Canonical path UNFile recDir = new UNFile(fullpath); path = recDir.getCanonicalPath(); success = addVnmrFileToDB(filename, path, owner, Shuf.DB_VNMR_RECORD, sleepMs, null); if(DebugOutput.isSetFor("addRecordToDB")) { if(success) Messages.postDebug("Added Record " + path); else Messages.postDebug("Failed to Add Record " + path); } // Now, add all of the subdirectories under the .REC/.rec directory // including acqfil. This means that basically, acqfil is in the // DB twice, once as the params for the record and once as the // acqfil file itself. files = recDir.listFiles(); if(files == null) return false; /* Now loop thur the files adding them to the DB. */ for(int i=0; i < files.length; i++) { file = (UNFile)files[i]; name = file.getName(); // The CanonicalPath is the real absolute path NOT using // any symbolic links. It is the real path. path = file.getCanonicalPath(); success = addVnmrFileToDB(name, path, owner, Shuf.DB_VNMR_REC_DATA, sleepMs, null); if(DebugOutput.isSetFor("addRecordToDB")) { if(success) Messages.postDebug("Added Record Data " + path); else Messages.postDebug("Failed to Add Record Data " + path); } } } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postError("Problem adding " + path + " to DB"); Messages.writeStackTrace(e); } } return success; } public boolean addAutodirToDB(String filename, String fullpath, String owner, String objType, long sleepMs){ boolean success=false; String subType=null; File[] files; UNFile file; String name, path=null; String autoHostFullpath; ArrayList fileList = new ArrayList(); String dhost, dpath; // Add the automation itself try { // Be sure fullpath is the Canonical path UNFile autoDir = new UNFile(fullpath); path = autoDir.getCanonicalPath(); // Create the hostFullpath for this automation to use as the // attribute value for automation for the items under this directory. Vector mp = MountPaths.getCanonicalPathAndHost(fullpath); dhost = (String) mp.get(Shuf.HOST); dpath = (String) mp.get(Shuf.PATH); autoHostFullpath = new String(dhost + ":" + dpath); success = addVnmrFileToDB(filename, path, owner, Shuf.DB_AUTODIR, sleepMs, null); if(!success) { // If failure if because the automation exists and is up to date // then we need to proceed with looking at the files // within this automation. First see if is is indeed an // automation run. String autopar = fullpath + File.separator + "autopar"; UNFile sfile = new UNFile(autopar); if(!sfile.exists()) { autopar = fullpath + File.separator + "doneQ"; sfile = new UNFile(autopar); if(!sfile.isFile()) { return false; } } long status = isDBKeyUniqueAndUpToDate(objType, autoHostFullpath, fullpath); if(status != 0) return false; } if(DebugOutput.isSetFor("addAutodirToDB")) { if(success) Messages.postDebug("Added Autodir " + path); else Messages.postDebug("Failed to Add Autodir " + path); } // Now determine whether this automation contains studies or // vnmr_data files. It should not contain both, just one or the // other. This must not be a recursive search, else I will // indeed find the .fids inside of studies. Do recursive below. files = autoDir.listFiles(); if(files == null) return false; // Now loop thur the list and see if any studies or .fids are there for(int i=0; i < files.length; i++) { file = (UNFile)files[i]; String fpath = file.getCanonicalPath(); String type = getType(fpath); // If there is a study, use that type even if there are // also vnmr_data files, therefore break if one is found if(type.equals(Shuf.DB_STUDY)) { subType = Shuf.DB_STUDY; break; } // If there is a lcstudy, use that type even if there are // also vnmr_data files, therefore break if one is found if(type.equals(Shuf.DB_LCSTUDY)) { subType = Shuf.DB_LCSTUDY; break; } if(type.equals(Shuf.DB_VNMR_DATA)) { // If a vnmr_data file if found, set the subType. // Keep cycling to see if a study is found, because // if a study is found, it takes precedent subType = Shuf.DB_VNMR_DATA; } } // If nothing was found, default to study if(subType == null) subType = Shuf.DB_STUDY; // Set attribute 'subtype' for this automation showing what type // of data is under it. setNonTagAttributeValue(Shuf.DB_AUTODIR, path, localHost, "subtype", "text", subType); /* Now we need the recursive file list of files. If subtype is STUDY, then we do not want to include all of the .fids in the studies. They will be taken care of when the studies are added. */ // Get the recursive list. if(subType.equals(Shuf.DB_STUDY) || subType.equals(Shuf.DB_LCSTUDY)) { // Get the recursive list for studies getFileListing(fileList, "", "", fullpath, true, subType); } else { // Get the recursive list for fids getFileListing(fileList, "", Shuf.DB_FID_SUFFIX, fullpath, true, Shuf.DB_VNMR_DATA); } // Check to see if an autostudies file exist. If so we want to // be sure we include all of the files listed in it. We also // want to eliminate duplicates with the list already obtained. // The autotsudies file should contain a list of all studies in // this automation. Note that the studies do not have to reside in // this automation directory itself, but can be anyplace. boolean dup; UNFile newfile; String inLine; String aspath = fullpath + File.separator + "autostudies"; file = new UNFile(aspath); if(file.isFile()) { BufferedReader in = new BufferedReader(new FileReader(file)); try { // Read one line at a time. while ((inLine = in.readLine()) != null) { name = inLine.trim(); if(!name.startsWith("/") && name.indexOf(":") < 1) { // Not a root path, we need to prepend fullpath name = fullpath.concat(File.separator + name); } newfile = new UNFile(name); dup = false; for(int i=0; i < fileList.size(); i++) { file = (UNFile) fileList.get(i); if(file.compareTo(newfile) == 0) { dup = true; break; } } if(!dup) { // Was not a duplicate, add it to the list. fileList.add(newfile); } } in.close(); } catch(Exception e) { Messages.postDebug("Problem Reading " + aspath); Messages.writeStackTrace(e); // Now just continue with the list we have already. } } /* Now loop thur the files adding them to the DB. */ for(int i=0; i < fileList.size(); i++) { file = (UNFile) fileList.get(i); // If subtype is study, only proceed if file is a study if(subType.equals(Shuf.DB_STUDY)) { // Only proceed if this files is really a study. String studypar = file.getPath() + File.separator + "studypar"; UNFile sfile = new UNFile(studypar); if(!sfile.exists()) { continue; } } if(subType.equals(Shuf.DB_LCSTUDY)) { // Only proceed if this files is really a study. String studypar = file.getPath() + File.separator + "lcpar"; UNFile sfile = new UNFile(studypar); if(!sfile.exists()) { continue; } } name = file.getName(); // The CanonicalPath is the real absolute path NOT using // any symbolic links. It is the real path. path = file.getCanonicalPath(); if(subType.equals(Shuf.DB_VNMR_DATA)) success = addVnmrFileToDB(name, path, owner, subType, sleepMs, null); else success = addStudyToDB(name, path, owner, subType, sleepMs); // Make the hostFullpath for this item. mp = MountPaths.getCanonicalPathAndHost(path); dhost = (String) mp.get(Shuf.HOST); dpath = (String) mp.get(Shuf.PATH); String hFullpath = dhost + ":" + dpath; // If the file was successfully added, we need to set the // 'automation' attribute showing the parent of this item. // If the file is already in the DB, we need to be sure // this attribute is set. The file may have gotten added // during an update of the item type itself. // success will show false if the path was not the right // type as well as if the item is already in the DB. // Check the DB itself. if(isDBKeyUniqueAndUpToDate(subType, hFullpath, path) < 1) { setNonTagAttributeValue(subType, path, localHost, Shuf.DB_AUTODIR, "text", autoHostFullpath); setNonTagAttributeValue(subType, path, localHost, "autodir", "text", fullpath); } if(DebugOutput.isSetFor("addAutodirToDB")) { if(success) Messages.postDebug("Added Autodir Data " + path); else Messages.postDebug("Failed to Add Autodir Data " +path); } // Output a , every so often for files checked. // This is to keep it from looking like nothing is // going on while it checks 1000's of files. if(i > 0 && i%100 == 0) System.out.print(","); if(i > 0 && i%1000 == 0) System.out.print("\n"); } } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postError("Problem adding " + path + " to DB"); Messages.writeStackTrace(e); } } return success; } public boolean addStudyToDB(String filename, String fullpath, String owner, String objType, long sleepMs){ boolean success=false; UNFile file; String studyHostFullpath; String parent=""; DBCommunInfo info = new DBCommunInfo(); String dhost, dpath; // Add the study or lcstudy itself try { // Create the hostFullpath for this study to use as the // attribute value for study for the items under this directory. try { Vector mp = MountPaths.getCanonicalPathAndHost(fullpath); dhost = (String) mp.get(Shuf.HOST); dpath = (String) mp.get(Shuf.PATH); } catch (Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem getting cononical path for\n " + fullpath); Messages.writeStackTrace(e); return false; } studyHostFullpath = new String(dhost + ":" + dpath); success = addVnmrFileToDB(filename, fullpath, owner, objType, sleepMs, null); if(!success){ // If failure if because the study exists and is up to date // then we need to proceed with looking at the files // within this study long status = isDBKeyUniqueAndUpToDate(objType, studyHostFullpath, fullpath); if(status != 0) return false; } // Check to see if this study is in an automation directory. // If so, then set the automation attr. If we are in here because // the automation itself is being added, then this will be // duplicated. That will be a waste of time, but will not // hurt anything. // Get the parent path for this study. // Strip off the filename and create a directory string. int index = fullpath.lastIndexOf(File.separator); if(index > 0) parent = fullpath.substring(0, index); // Is this parent an automation? Having to look to see if the parent // is an automation should only be necessary if this is a new dir // and we are actively putting studies into it. Thus, only look // for the file autopar. String parPath = new String(parent + File.separator + "autopar"); file = new UNFile(parPath); if(file.isFile()) { // The parent is an automation, set the automation and autodir // attributes for this study. Vector mp = MountPaths.getCanonicalPathAndHost(parent); dhost = (String) mp.get(Shuf.HOST); dpath = (String) mp.get(Shuf.PATH); String parentHostFullpath = dhost + ":" + dpath; setNonTagAttributeValue(objType, fullpath, localHost, Shuf.DB_AUTODIR, "text", parentHostFullpath); setNonTagAttributeValue(objType, fullpath, localHost, "autodir", "text", parent); } if(DebugOutput.isSetFor("addStudyToDB")) { if(success) Messages.postDebug("Added Study " + fullpath); else Messages.postDebug("Failed to Add Study " + fullpath); } // recursively add any vnmr_data or studies below this. // Add anything that is supposed to be in study_data here. // Set the 'study' attribute to studyHostFullpath even if the // files are already in the DB. fillATable(Shuf.DB_VNMR_DATA, fullpath, owner, true, info, sleepMs, objType, studyHostFullpath); fillATable(Shuf.DB_STUDY, fullpath, owner, true, info, sleepMs, objType, studyHostFullpath); fillATable(Shuf.DB_LCSTUDY, fullpath, owner, true, info, sleepMs, objType, studyHostFullpath); } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postError("Problem adding " + fullpath + " to DB"); Messages.writeStackTrace(e); } } return success; } public boolean addImageDirToDB(String filename, String fullpath, String owner, String objType, long sleepMs) { boolean success=false; UNFile file; UNFile procparFile; String name, path=null; String imageHostFullpath; ArrayList fileList = new ArrayList(); String dhost, dpath; // Add the image dir itself try { // Be sure fullpath is the Canonical path UNFile imageDir = new UNFile(fullpath); path = imageDir.getCanonicalPath(); // Create the hostFullpath for this image dir to use as the // attribute value for image_dir for the items under this directory. Vector mp = MountPaths.getCanonicalPathAndHost(fullpath); dhost = (String) mp.get(Shuf.HOST); dpath = (String) mp.get(Shuf.PATH); imageHostFullpath = new String(dhost + ":" + dpath); success = addVnmrFileToDB(filename, path, owner, objType, sleepMs, null); if(!success) { // If failure if because the image_dir exists and is up to date // then we need to proceed with looking at the files // within this image_dir. First see if there is an procpar. String procpar = fullpath + File.separator + "procpar"; procparFile = new UNFile(procpar); if(!procparFile.exists()) { // No procpar file, bail out return false; } long status = isDBKeyUniqueAndUpToDate(objType, imageHostFullpath, fullpath); if(status != 0) return false; } if(DebugOutput.isSetFor("addImagedirToDB")) { if(success) Messages.postDebug("Added " + objType + " " + path); else Messages.postDebug("Failed to Add " + objType + " " + path); } } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postError("Problem adding " + path + " to DB"); Messages.writeStackTrace(e); } } return success; } public boolean addVnmrFileToDB(String filename, String fullpath, String owner, String objType, long sleepMs, DBCommunInfo dbInfo){ return addVnmrFileToDB(filename, fullpath, owner, objType, sleepMs, null,null,dbInfo); } public boolean addVnmrFileToDB(String filename, String fullpath, String owner, String objType, long sleepMs, String attrName, String attrVal, DBCommunInfo dbInfo){ String dhostFullpath; BufferedReader in=null; String rootFilename; String parPath; ArrayList valuesAsString=new ArrayList(); String dataType; String param=""; String directory; int numVals, index; String basicType, subType; StreamTokenizerQuotedNewlines tok; boolean investigatorFound=false; boolean time_savedFound=false; int typeMatch; char ch; UNFile file; UNFile dir; long timeSavedSec; java.util.Date timeSavedDate; DBCommunInfo info; String expNum=""; String dhost, dpath; if(DebugOutput.isSetFor("addFileToDB")) { Messages.postDebug("addVnmrFileToDB(): filename = " + filename + " fullpath = " + fullpath + "\nowner = " + owner + " objType = " + objType + " sleepMs = " + sleepMs); } /* if we have a workspace, then be sure the char following the prefix is numeric and the last char is numeric. Get the numeric part and keep it for later. */ if(objType.equals(Shuf.DB_WORKSPACE)) { // Is the name at least long enough to contain a suffix numeral if(filename.length() < Shuf.DB_WKS_PREFIX.length() +1) return false; /* Go on to next file */ ch = filename.charAt(Shuf.DB_WKS_PREFIX.length()); if(!Character.isDigit(ch)) return false; /* Go on to next file */ /* Be sure the last char is a numeric */ ch = filename.charAt(filename.length() -1); if(!Character.isDigit(ch)) return false; /* Go on to next file */ // Get the numeric part following Shuf.DB_WKS_PREFIX expNum = filename.substring(Shuf.DB_WKS_PREFIX.length(), filename.length()); } if(objType.equals(Shuf.DB_SHIMS)) { // If shims, be sure path is a shim directory if(fullpath.indexOf("shims/") == -1) return false; /* Go on to next file */ } try { Vector mp = MountPaths.getCanonicalPathAndHost(fullpath); dhost = (String) mp.get(Shuf.HOST); dpath = (String) mp.get(Shuf.PATH); } catch(Exception e) { Messages.postDebug("Problem getting cononical path for " + fullpath); Messages.writeStackTrace(e); dhost = localHost; dpath = fullpath; } dhostFullpath = new String(dhost + ":" + dpath); /* AUTODIR can be detected by the presence of any of 3 files. Look for all three. */ if(objType.equals(Shuf.DB_AUTODIR)) { parPath = new String(fullpath + File.separator + "autopar"); file = new UNFile(parPath); if(!file.isFile()) { // No autopar, try doneQ String qFile = new String(fullpath + File.separator + "doneQ"); file = new UNFile(qFile); if(!file.isFile()) { // No doneQ, try enterQ qFile = new String(fullpath + File.separator + "enterQ"); file = new UNFile(qFile); if(!file.isFile()) { // No autopar, doneQ nor enterQ, thus, not an automation return false; } } // We must have found doneQ or enterQ, but not autopar // Create an empty BufferedReader try { in = new BufferedReader(new StringReader(new String(""))); } catch(Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem creating empty Reader"); Messages.writeStackTrace(e); return false; } } else { // It is DB_AUTODIR and it has a autopar file. // Open the file. try { file = new UNFile(parPath); in = new BufferedReader(new FileReader(file)); } catch(Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem opening " + parPath); Messages.writeStackTrace(e, "Error caught in " + "addVnmrFileToDB"); return false; } } } else { /* For workspace, use curpar, for vnmr_data files use procpar, for shims, use fullpath, for records, use procpar for record_data use curpar. */ if(objType.equals(Shuf.DB_WORKSPACE) || objType.equals(Shuf.DB_VNMR_REC_DATA) ) parPath = new String(fullpath + File.separator + "curpar"); else if(objType.equals(Shuf.DB_SHIMS)) parPath = fullpath; else if(objType.equals(Shuf.DB_STUDY)) { parPath = new String(fullpath + File.separator + "studypar"); } else if(objType.equals(Shuf.DB_LCSTUDY)) { parPath = new String(fullpath + File.separator + "lcpar"); } else if(objType.equals(Shuf.DB_VNMR_RECORD)) parPath = new String(fullpath + File.separator + "acqfil" + File.separator + "curpar"); // for DB_IMAGE_FILE, we need to use the procpar of the DB_IMAGE_DIR // or DB_COMPUTED_DIR above it. Then after this, we will get // params from the .fdf file header else if(objType.equals(Shuf.DB_IMAGE_FILE)) { // Does parent end in .img or .cmp? file = new UNFile(fullpath); String parent = file.getParent(); if(parent.endsWith(Shuf.DB_IMG_DIR_SUFFIX)) { // We have the proper type parent, add procpar to the path parPath = new String(parent + File.separator + "procpar"); } else { // Oops, the .fdf is not in an .img nor .cmp directory. // Error out, until we know what to do about this. Messages.postError("Failed while trying to add\n " + fullpath + "\n which is not in a " + Shuf.DB_IMG_DIR_SUFFIX + " directory."); return false; } } else if(objType.equals(Shuf.DB_PROTOCOL)) { // If protocol, the filename and fullpath may still have ".xml" on it. // Create the filename by stripping off the "xml" and adding "par" String parname; if(filename.endsWith(Shuf.DB_PROTOCOL_SUFFIX)) { parname = filename.substring(0, filename.length() -3); parname = parname + "par"; } else parname = filename; // Create the par full path by stripping off the // "templates/vnmrj/protocols/myprotocol.xml" and // adding "parlib/myprotocol.par" int ind = fullpath.indexOf("templates/vnmrj"); if(ind > -1) { parPath = fullpath.substring(0, ind); parPath = parPath + "parlib" + File.separator + parname + File.separator + "procpar"; } else parPath = new String(fullpath + File.separator + "procpar"); } else parPath = new String(fullpath + File.separator + "procpar"); // Test for the file first. file = new UNFile(parPath); if(!file.isFile()) { // If Protocol but the fullpath for the .par passed in does not exist, // then just fill the Db with what arrived in dbInfo from the .xml file // This will be the case for a composite protocol if(objType.equals(Shuf.DB_PROTOCOL)) { // Send the cmd to the DB to add all the stuff in dbInfo addRowToDBExecute(objType, dhostFullpath, dbInfo); // Now get out of here, there is no .par file to parse return true; } return false; } // check to see if limits are in effect and if this file is too old if(objType.equals(Shuf.DB_VNMR_DATA) || objType.equals(Shuf.DB_IMAGE_FILE)) { long fileModified = file.lastModified(); if(fileModified < dateLimitMS) { // date is too old, but keep varian files anyway String sysdir = System.getProperty("sysdir"); if(sysdir != null) { UNFile sysfile = new UNFile(sysdir); if(sysfile != null) { // Need to compare the canonical path String csysdir = sysfile.getCanonicalPath(); if(!fullpath.startsWith(csysdir + "/")) // Not varian file, just exit return false; } } } } // Open the file. try { in = new BufferedReader(new FileReader(file)); } catch(Exception e) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem opening " + parPath); Messages.writeStackTrace(e, "Error caught in addVnmrFileToDB"); return false; } } /* The DB takes backslashes as excape characters. The directory * paths on Windows use backslashes. For these to work in the DB, we * need to use \\ so the backslashes are kept as part of the string. * Unix paths are uneffected because they will not have any backslashes. */ dhostFullpath = UtilB.escapeBackSlashes(dhostFullpath); dpath = UtilB.escapeBackSlashes(dpath); // Start the process of adding a row to the DB if(dbInfo != null) { // Protocols need to add xml and procpar info, so we pass in info. info = dbInfo; } else info = addRowToDBInit(objType, dhostFullpath, fullpath); if(info == null) { // File may already be in DB and be up to date is most common // reason to bail out here. try { in.close(); } catch(Exception eio) {} return false; } dir = new UNFile(fullpath); timeSavedSec = dir.lastModified(); timeSavedDate = new java.util.Date(timeSavedSec); // strip suffix off of the filename before adding to DB. // Not for automation nor study if(objType.equals(Shuf.DB_AUTODIR) || objType.equals(Shuf.DB_STUDY) || objType.equals(Shuf.DB_LCSTUDY)) { rootFilename = filename; } else { index = filename.lastIndexOf('.'); if(index > 0) rootFilename = filename.substring(0, index); else rootFilename = filename; } // Strip off the filename and create a directory string. // If ends with File.separator, just strip it off. index = fullpath.lastIndexOf(File.separator); if(index == fullpath.length() -1) fullpath = fullpath.substring(0,fullpath.length() -1); // In case we stripped off a slash, get the index again index = fullpath.lastIndexOf(File.separator); if(index > 0) directory = fullpath.substring(0, index); else directory = fullpath; // Now get just the last directory level name index = directory.lastIndexOf(File.separator); if(index > 0) directory = directory.substring(index+1); // Add some standard attributes that will not be in the file. ArrayList List = new ArrayList(); List.add(dhostFullpath); addRowToDBSetAttr(objType, "host_fullpath", DB_ATTR_TEXT, List, dhostFullpath, info); List.clear(); List.add(rootFilename); addRowToDBSetAttr(objType, "filename", DB_ATTR_TEXT, List, dhostFullpath, info); List.clear(); List.add(dpath); addRowToDBSetAttr(objType, "fullpath", DB_ATTR_TEXT, List, dhostFullpath, info); List.clear(); List.add(owner); addRowToDBSetAttr(objType, "owner", DB_ATTR_TEXT, List, dhostFullpath, info); List.clear(); List.add(localHost); addRowToDBSetAttr(objType, "hostname", DB_ATTR_TEXT, List, dhostFullpath, info); List.clear(); List.add(dhost); addRowToDBSetAttr(objType, "hostdest", DB_ATTR_TEXT, List, dhostFullpath, info); List.clear(); List.add(directory); addRowToDBSetAttr(objType, "directory", DB_ATTR_TEXT, List, dhostFullpath, info); // The division by 1000 is to get seconds instead of milliseconds. // milliseconds over flows the int. List.clear(); List.add(String.valueOf(timeSavedSec/1000)); addRowToDBSetAttr(objType, "long_time_saved", DB_ATTR_INTEGER, List, dhostFullpath, info); if(objType.equals(Shuf.DB_WORKSPACE)) { List.clear(); List.add(expNum); addRowToDBSetAttr(objType, "exp", DB_ATTR_INTEGER, List, dhostFullpath, info); } if(objType.equals(Shuf.DB_VNMR_RECORD) || objType.equals(Shuf.DB_VNMR_REC_DATA) || objType.equals(Shuf.DB_AUTODIR) || objType.equals(Shuf.DB_LCSTUDY) || objType.equals(Shuf.DB_STUDY)) { List.clear(); // Is this data corrupt? If so, there should be a file // named 'checksum.flag' file = new UNFile(fullpath + File.separator + "checksum.flag"); String corrupt; if(file.exists()) corrupt = new String("corrupt"); else corrupt = new String("valid"); List.add(corrupt); addRowToDBSetAttr(objType, "corrupt", DB_ATTR_TEXT, List, dhostFullpath, info); if(objType.equals(Shuf.DB_VNMR_RECORD) || objType.equals(Shuf.DB_VNMR_REC_DATA)) { List.clear(); // Is this data FDA (.REC) or Non-FDA (.rec)? if(fullpath.indexOf(Shuf.DB_REC_SUFFIX) > -1) { List.add("fda"); } else List.add("nonfda"); addRowToDBSetAttr(objType, "fda", DB_ATTR_TEXT, List, dhostFullpath, info); } } if(objType.equals(Shuf.DB_VNMR_REC_DATA)) { // We need the parent record name and path that this data belongs // to. That should be the name which ends with .rec or .REC in // the fullpath of this rec_data file. Thus, we want the string // before .rec or .REC. index = dhostFullpath.indexOf(Shuf.DB_REC_SUFFIX); if(index == -1) index = dhostFullpath.indexOf(Shuf.DB_REC_SUFFIX.toLowerCase()); if(index == -1) { Messages.postError("Cannot find record name for " + dhostFullpath); } else { String record = dhostFullpath.substring(0, index); List.clear(); List.add(record); addRowToDBSetAttr(objType, "record", DB_ATTR_TEXT, List, dhostFullpath, info); } } // If attrName is set, then add that to the list if(attrName != null) { List.clear(); List.add(attrVal); addRowToDBSetAttr(objType, attrName, DB_ATTR_TEXT, List, dhostFullpath, info); } // Use StreamTokenizer because we can keep the quoted string // as a single token. StringTokenizer does not allow that. // I had to create StreamTokenizerQuotedNewlines to allow quoted // string to contain newLines. The standard one ends the quote // at the end of a line. Sun had a bug reported about this // (4239144) and refused to add an option to allow multiple lines // in a quoted string. GRS tok = new StreamTokenizerQuotedNewlines(in); // Define the quote character tok.quoteChar('\"'); // Define additional chars to be treated as normal letters. // Most things within a comment, sample name etc will be within // double quotes and do not need to be listed here. We need things // here that can be in parameter names. tok.wordChars('_', '_'); // I incountered 2 Java bugs in using StreamTokenizer. // One is that is does not handle 1e18 format of numbers. // I am not worried about it not turning 1e18 format into numbers // because I don't need the numeric value anyway. I would just // turn it into a string and send it to the DB. // Two is that tok.parseNumbers() is called by its constructor // and thus is always on, and tok.parseNumbers() does not allow // you to turn it off. // To turn off the numeric thing by hand, first call ordinaryChars, // then specify numbers to be normal word characters. // Then when we encounter 1.3e-13 we get it as one string token. // tok.nval will never contain anything, because ALL letters // and numbers will be turned into 'String' tokens. tok.ordinaryChars('+', '.'); // + comma - and period (Turn off numeric) tok.wordChars('+', '.'); // + comma - and period (Set as normal letters) tok.ordinaryChars('0', '9'); // all numbers (Turn off numeric) tok.wordChars('0', '9'); // all numbers (Set as normal letters) tok.wordChars('$', '$'); // all numbers (Set as normal letters) try { // Parse the vnmr file. while(tok.nextToken() != StreamTokenizerQuotedNewlines.TT_EOF) { // There should be 11 tokens on the first line and we // only want the first 3. The first is a string and // the 2nd and 3rd are integers param = tok.sval; tok.nextToken(); subType = tok.sval; // If null or negative, this is a bad format file // If not an integer, an exception will be thrown. try { if(subType == null || Integer.parseInt(subType) < 0) { if(in != null) in.close(); return false; } } catch (Exception e) { try { in.close(); } catch(Exception eio) {} return false; } tok.nextToken(); basicType = tok.sval; // This would mean a bad format, so skip this file if(basicType == null || (!basicType.equals("1") && !basicType.equals("2"))) { try { in.close(); } catch(Exception eio) {} return false; } // Dump the next 8 tok.nextToken(); tok.nextToken(); tok.nextToken(); tok.nextToken(); tok.nextToken(); tok.nextToken(); tok.nextToken(); tok.nextToken(); tok.nextToken(); numVals = Integer.parseInt(tok.sval); if(basicType.equals(T_REAL)) { // Try forcing all reals to float8 // if(subType.equals(ST_INTEGER)) { // dataType = DB_ATTR_INTEGER; // else { dataType = DB_ATTR_FLOAT8; /* See if we want to put this param in the db or not. We wait to check until now, because we have to read everything out of the procpar file anyway. Returns 0 for false, 1 for true and 2 for true except item in DB is array type. */ typeMatch = isParamInList(objType, param, dataType); // The param temp is not usable in postgres, so change the // string to "temperature". if(param.equals("temp")) param = "temperature"; /* If == 1, the type matches and is not an array. Loop thru in case the procpar had an array. If == 0, no match, so just loop thru to dump them. */ if(typeMatch < 2) { for (int i=0; i < numVals; i++) { tok.nextToken(); // Only take first value and // only if param is wanted. if(i == 0 && typeMatch == 1) { // We only want the first value. valuesAsString.add(tok.sval); /* Just put the first value into the db. */ addRowToDBSetAttr(objType, param, dataType, valuesAsString, dhostFullpath, info); valuesAsString.clear(); // If protocol AND param is sfrq, then we // want to calc a field in Tesla and add it if(objType.equals(Shuf.DB_PROTOCOL) && param.equals("sfrq")) { double field = convertFreqToTesla(tok.sval); valuesAsString.add(Double.toString(field)); addRowToDBSetAttr(objType, "field", dataType, valuesAsString, dhostFullpath, info); valuesAsString.clear(); } } // else, not the first, just let them be dumped. } } /* We have a param match and it is an array type. Even if procpar only has one value, we still have to send sql command to set an array. */ if(typeMatch == 2) { for (int i=0; i < numVals; i++) { tok.nextToken(); valuesAsString.add(tok.sval); } // attr Type sent as arg must be type including // the []. Since we know this is an array type, // add the [] to dataType. addRowToDBSetAttr(objType, param, dataType + "[]", valuesAsString, dhostFullpath, info); valuesAsString.clear(); } /* Read the enumeration values and ignore */ tok.nextToken(); numVals = Integer.parseInt(tok.sval); for (int i=0; i < numVals; i++) tok.nextToken(); } else if(basicType.equals(T_STRING)) { if(param.startsWith("time")) dataType = DB_ATTR_DATE; else dataType = DB_ATTR_TEXT; /* We need to know if investigator is set, so check and if so, set the flag. */ if(param.equals("investigator")) investigatorFound = true; /* Do we want this parameter? Returns 0 for false, 1 for true and 2 for true except item in DB is array type. */ typeMatch = isParamInList(objType, param, dataType); /* If == 1, the type matches and is not an array. Loop thru in case the procpar had an array. If == 0, no match, so just loop thru to dump them. */ if(typeMatch < 2) { for (int i=0; i < numVals; i++) { tok.nextToken(); // We only want the first value and // only if param is wanted if(i == 0 && typeMatch == 1) { String value = tok.sval; /* If the name starts with 'time', we may need to convert a trailing 'Z' to 'UTC'. ISO 8601 specifies 'Z' but Postgres accepts 'UTC'. Actually it accepts 'UT' also. */ if(param.startsWith("time")) { if(value.endsWith("Z")) { value = value.substring( 0,value.length()-1); value = value.concat("UT"); } // If we found TIME_SAVED and it has a // value then set the flag. if(param.equals(Shuf.DB_TIME_SAVED) && value.trim().length() != 0) time_savedFound = true; } // Limit string value length. Too many causes // an sql error if(value.length() > MAX_ARRAY_STR_LEN) { value = value.substring(0, MAX_ARRAY_STR_LEN); } // If empty string, don't use it // if(!value.equals("")) valuesAsString.add(value); /* Do we want this parameter? Returns 0 for false, 1 for true and 2 for true except item in DB is array type. */ /* Just put the first value into the db. */ addRowToDBSetAttr(objType, param, dataType, valuesAsString, dhostFullpath, info); valuesAsString.clear(); } } // else, not the first, just let them be dumped. } /* We have a param match and it is an array type. Even if procpar only has one value, we still have to send sql command to set an array. */ if(typeMatch == 2) { for (int i=0; i < numVals; i++) { tok.nextToken(); String value = tok.sval; // Limit string value length. Too many causes // an sql error if(value.length() > MAX_ARRAY_STR_LEN) { value = value.substring(0, MAX_ARRAY_STR_LEN); } valuesAsString.add(value); } // attr Type sent as arg must be type including // the []. Since we know this is an array type, // add the [] to dataType. addRowToDBSetAttr(objType, param, dataType + "[]", valuesAsString, dhostFullpath, info); valuesAsString.clear(); } /* Read the enumeration values and ignore */ tok.nextToken(); numVals = Integer.parseInt(tok.sval); for (int i=0; i < numVals; i++) tok.nextToken(); } } in.close(); } catch (Exception e) { // Only output error if not running update in background. // This will be given as any time we are called with sleepMs == 0 if(sleepMs == 0) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem adding " + filename + " to database near param = " + param); Messages.writeStackTrace(e, "Error caught in addVnmrFileToDB"); } try { in.close(); } catch(Exception eio) {} return false; } /* If investigator is not set for this entry, then set it to the owner. */ if(!investigatorFound) { List = new ArrayList(); List.add(owner); addRowToDBSetAttr(objType, "investigator", DB_ATTR_TEXT, List, dhostFullpath, info); } if(!time_savedFound) { // If the parameter time_saved is not in procpar, then // just use the unix date stamp and set time_saved. // Convert timeSavedDate to date string SimpleDateFormat formatter = new SimpleDateFormat ("MMM d, yyyy HH:mm:ss"); String str = formatter.format(timeSavedDate); List = new ArrayList(); List.add(str); addRowToDBSetAttr(objType, Shuf.DB_TIME_SAVED, DB_ATTR_DATE, List, dhostFullpath, info); } // Send the cmd to the DB to add all the stuff from above. addRowToDBExecute(objType, dhostFullpath, info); try { in.close(); } catch(Exception e) { } return true; } public boolean clearOutTable(String objType, String user) { try { if(user.equals("all") ) executeUpdate("DELETE FROM " + objType); else executeUpdate("DELETE FROM " + objType + " WHERE owner = \'" + user + "\'"); return true; } catch (Exception e) { haveConnection = false; if(!ExitStatus.exiting()) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem removing all items from" + objType + " DB table for owner = " + user); Messages.writeStackTrace(e, "Error caught in clearOutTable"); } return false; } } public void getFileListing(ArrayList fileList, String prefix, String suffix, String directory, boolean recursive, String objType) { int entryCounter = 0; java.util.Date starttime = new java.util.Date(); java.util.Date endtime; long timems; // if (locatorOff() && !managedb) if (locatorOff()) return; // Skip the updateSymLinks if not recursive and if Interix if(recursive) { // Start a thread to check for symbolic links. UpdateSymLinks updateSymLinks; updateSymLinks = new UpdateSymLinks(directory, symLinkMap); updateSymLinks.start(); } getFileListingRecursive(fileList, prefix, suffix, directory, recursive, objType, entryCounter); if(DebugOutput.isSetFor("getFileListing")) { endtime = new java.util.Date(); timems = endtime.getTime() - starttime.getTime(); Messages.postDebug("**Time for getFileListing " + objType + ": " + timems + "\n Dir: " + directory + "\n " + "entryCount: " + entryCounter + " fileCount: " + fileList.size()); } } private void getFileListingRecursive(ArrayList fileList, String prefix, String suffix, String directory, boolean recursive, String objType, int entryCounter) { DirFilter filterMatch, filterNonMatch; UNFile dir; UNFile file; File[] files; String[] MatchSuffixList; String[] NonMatchSuffixList; if(entryCounter > 200) { Messages.postError("Problem getting file listing of " + directory + "\n There may be a cyclic reference" + " someplace in this persons directory."); return; } // accept() is set up to only work with one matching suffix, MatchSuffixList = new String[1]; NonMatchSuffixList = new String[6]; MatchSuffixList[0] = suffix; NonMatchSuffixList[0] = Shuf.DB_FID_SUFFIX; NonMatchSuffixList[1] = Shuf.DB_PAR_SUFFIX; NonMatchSuffixList[2] = Shuf.DB_SPC_SUFFIX; NonMatchSuffixList[3] = Shuf.DB_PANELSNCOMPONENTS_SUFFIX; NonMatchSuffixList[4] = Shuf.DB_REC_SUFFIX; NonMatchSuffixList[5] = new String(Shuf.DB_REC_SUFFIX.toLowerCase()); filterMatch = new DirFilter(prefix, MatchSuffixList, true, objType); filterNonMatch = new DirFilter("", NonMatchSuffixList, false); dir = new UNFile(directory); if(dir == null) return; // Did we receive a single file or single data directory? // See if it is a file, or if 'directory' has prefix or suffix. // If so, just return a list of this one item. if(dir.isFile() || (suffix.length() > 0 && directory.endsWith(suffix)) || (suffix.length() > 0 && directory.endsWith(suffix + "/"))) { fileList.add(dir); return; } // Traverse down the directory tree. try { if(recursive) { // Get the desired files from this directory files = dir.listFiles(filterMatch); // Transfser the files found to the output list if(files != null) { for(int i=0; i < files.length; i++) { fileList.add(files[i]); } } // Now Get any sub directories within this directory, but // do not include .par nor .fid entries. // Get the directory listing excluding files/dir with suffix files = dir.listFiles(filterNonMatch); if(files != null) { for(int i=0; i < files.length; i++) { file = (UNFile)files[i]; // Try to catch cyclic links and tell the user // what and where the problem is, then skip the dir if(file.getParent().startsWith( file.getCanonicalPath())) { Messages.postError("Problem getting directory list." + " The directory\n " + file.getAbsolutePath() + "\n Appears to link back to " + file.getCanonicalPath() + "\n Skipping this directory."); } // Skip the directory if it appears to be cyclic. else { if(file.isDirectory()) { getFileListingRecursive(fileList, prefix, suffix, file.getCanonicalPath(), recursive, objType, entryCounter+1); } } } } } // Only this directory else { filterNonMatch = new DirFilter("", NonMatchSuffixList, false); files = dir.listFiles(filterMatch); if(files != null) { // Transfser the files found to the output list for(int i=0; i < files.length; i++) fileList.add(files[i]); } } } catch (Exception e) { if(!ExitStatus.exiting()) Messages.writeStackTrace(e, "Error caught in getFileListingRecursive"); } if(DebugOutput.isSetFor("filelist")) { // The size given in the output from this will grow as it recursively // goes down the tree. Messages.postDebug("Size of filelist being accumulated " + directory + " is " + fileList.size()); } return; } public void cleanupDBList(DBCommunInfo info) { // If no arg, pass 0 for sleepMs cleanupDBList(0, info); } public void cleanupDBList(long sleepMs, DBCommunInfo info) { info.numFilesRemoved=0; cleanupDBListThisType(Shuf.DB_VNMR_DATA, sleepMs, info); cleanupDBListThisType(Shuf.DB_VNMR_PAR, sleepMs, info); cleanupDBListThisType(Shuf.DB_VNMR_RECORD, sleepMs, info); cleanupDBListThisType(Shuf.DB_VNMR_REC_DATA, sleepMs, info); cleanupDBListThisType(Shuf.DB_PROTOCOL, sleepMs, info); cleanupDBListThisType(Shuf.DB_STUDY, sleepMs, info); cleanupDBListThisType(Shuf.DB_LCSTUDY, sleepMs, info); cleanupDBListThisType(Shuf.DB_AUTODIR, sleepMs, info); cleanupDBListThisType(Shuf.DB_IMAGE_DIR, sleepMs, info); cleanupDBListThisType(Shuf.DB_WORKSPACE, info); cleanupDBListThisType(Shuf.DB_TRASH, info); cleanupDBListThisType(Shuf.DB_PANELSNCOMPONENTS, info); cleanupDBListThisType(Shuf.DB_SHIMS, info); } public boolean cleanupDBListThisType(String objType, DBCommunInfo info) { // If no second arg, pass 0 for sleepMs return cleanupDBListThisType(objType, 0, info); } public boolean cleanupDBListThisType(String objType, long sleepMs, DBCommunInfo info) { java.sql.ResultSet rs; String host, dhost; String fullpath; String mpath; UNFile file; if(DebugOutput.isSetFor("cleanupDBListThisType")) Messages.postDebug("cleanupDBListThisType on " + objType); // Get the dateLimit for keeping vnmr_data in the locator // dataLimitDays = 0 means nothing is kept except varian data // dataLimitDays = -1 means everything is kept // dataLimitDays greater than 0 means keep this many weeks of data // dataLimitDays is set with -Ddatelimit=# in the java startup cmd line Calendar dateLimit = Calendar.getInstance(); java.util.Date dateToday = new java.util.Date(); Calendar calToday = Calendar.getInstance(); calToday.setTime(dateToday); // Get ALL entries for this table. try { rs = executeQuery("SELECT hostname, fullpath, hostdest FROM " + objType); if(rs == null) { return false; } while(rs.next()) { host = rs.getString(1); // If there is no host, something is wrong with the // entry. We do not even have the information to get // rid of the entry so just skip it. if(host == null) continue; // If not put into the DB from this host, go on to the next one. if(!host.equals(localHost)) continue; fullpath = rs.getString(2); dhost = rs.getString(3); // fullpath here will be the direct path on the machine // where it actually exists. We need to get the mounted // path so that we can access the actual file. mpath = MountPaths.getMountPath(dhost, fullpath); // If Windows, we need a windows path for File if(UtilB.OSNAME.startsWith("Windows")) mpath = UtilB.unixPathToWindows(mpath); file = new UNFile(mpath); // Does this fullpath still exist? if(!file.exists()) { // No, then remove it from the DB. removeEntryFromDB (objType, fullpath, dhost, info); } // If the file is older than the date specified as the // limit, then remove it. long fileModified = file.lastModified(); if((objType.equals(Shuf.DB_VNMR_DATA) || objType.equals(Shuf.DB_IMAGE_FILE)) && fileModified < dateLimitMS) { // date is too old, but keep varian files anyway String sysdir = System.getProperty("sysdir"); if(sysdir != null) { UNFile sysfile = new UNFile(sysdir); if(sysfile != null) { // Need to compare the canonical path String csysdir = sysfile.getCanonicalPath(); if(!fullpath.startsWith(csysdir + "/")) // Not varian file, remove it removeEntryFromDB (objType, fullpath, dhost, info); } } } try { Thread.sleep(sleepMs); } catch (Exception e) {} } } catch (Exception e) { // If sleepMs > 0, we must be in a bkg thread, no error output if(sleepMs == 0) { Messages.postDebug("Problem clearing out " + objType + " table in DB"); Messages.writeStackTrace(e, "Error caught in cleanupDBListThisType"); } } return true; } public void updateDB(Hashtable users, long sleepMs) throws InterruptedException { // Default to filling of workspace as true. boolean workspace = true; updateDB(users, sleepMs, workspace); } public void updateDB(Hashtable users, long sleepMs, boolean workspace) throws InterruptedException { // Default to filling of appdirOnly as false. boolean appdirOnly = false; updateDB(users, sleepMs, workspace, appdirOnly); } public void updateDB(Hashtable users, long sleepMs, boolean workspace, boolean appdirOnly) throws InterruptedException { User user; String dir; String userName; ArrayList dataDirs; java.util.Date endtime; long timems; java.util.Date starttime = new java.util.Date(); DBCommunInfo info = new DBCommunInfo(); ArrayList dirChecked = new ArrayList(); if(attrList == null) return; // workspace = false, means don't update workspaces from the disk // files. The DB may have been updated on the fly as params change. // The thread crawler needs to skip the workspace update. try { // If no connection, this will output one error, then we can quit. if(checkDBConnection() == false) return; // Vacuum the DB before updating for better access during update. vacuumDB(); // Update the macros and commands if necessary. updateMacro(Shuf.DB_COMMAND_MACRO); if(DebugOutput.isSetFor("updatedb")) Messages.postDebug("Updating Command Macros"); updateMacro(Shuf.DB_PPGM_MACRO); if(DebugOutput.isSetFor("updatedb")) Messages.postDebug("Updating PPGM Macros"); // appdirOnly means we are only updating the apdir directories // and are probably trying to use a previous DB and and wanting // to go as quickly as possible. Cleanup can take a long time // when there are a lot of files in the DB if(!appdirOnly) { // Remove any entries which are no longer on the disk if(DebugOutput.isSetFor("updatedb")) Messages.postDebug("updateDB calling cleanupDBList"); cleanupDBList(sleepMs, info); // Clean up the SymLinkList. symLinkMap.cleanDirChecked(); } // Get the system DB_PANELSNCOMPONENTS files. //dir = FileUtil.vnmrDir("SYSTEM/PANELITEMS"); // Force user for these to vnmrj. //fillATable(Shuf.DB_PANELSNCOMPONENTS, null, dir, // "vnmrj", recursive); // Get the system shim files // Force Owner to vnmrj //dir = FileUtil.vnmrDir("SYSTEM/SHIMS"); //fillATable(Shuf.DB_SHIMS, null, dir, "vnmrj", recursive); // Go thru the users if(DebugOutput.isSetFor("updatedb")) Messages.postDebug("Going through the users to be updated"); for(Enumeration en = users.elements(); en.hasMoreElements(); ) { user = (User) en.nextElement(); userName = user.getAccountName(); // Skip the datadirs if appdir Only if(!appdirOnly) { dataDirs = user.getDataDirectories(); // Do not search in directories or children of directories // already searched. Get a clone so we can change the list. ArrayList cDataDirs; String dirCked; int index; cDataDirs = (ArrayList)dataDirs.clone(); for(int k=0; k < dirChecked.size(); k++) { dirCked = (String) dirChecked.get(k); // First Dups if((index=cDataDirs.indexOf(dirCked)) > -1) { // Found dup, remove it from list to check cDataDirs.remove(index); continue; } // Look for children in cDataDirs of parents in dirChecked for(int j=0; j < cDataDirs.size(); j++) { String dir1 = (String) cDataDirs.get(j); String dir2 = (String) dirChecked.get(k); if(dir1.startsWith(dir2)) { // We found that cDataDirs(j) is a child of // dirChecked(k). Remove the child. cDataDirs.remove(j); j } } } // Add cDataDirs to dirChecked for future checks for(int j=0; j < cDataDirs.size(); j++) { dirChecked.add(cDataDirs.get(j)); } // Check this users list of directories in SavedDirList // These are directories where the user has saved files // to. It actually comes from addFileToDB(). Add the // unique ones to cDataDirs for use below. // Get a clone of the list. ArrayList cSavedDirList; cSavedDirList = savedDirList.getSavedDirList(); for(int k=0; k < dirChecked.size(); k++) { dirCked = (String) dirChecked.get(k); // First Dups if((index=cSavedDirList.indexOf(dirCked)) > -1) { // Found dup, remove it from list to check cSavedDirList.remove(index); continue; } // Look for children in cSavedDirList of parents // in dirChecked for(int j=0; j < cSavedDirList.size(); j++) { String dir1 = (String) cSavedDirList.get(j); String dir2 = (String) dirChecked.get(k); if(dir1.startsWith(dir2)) { // We found that cSavedDirList(j) is a child of // dirChecked(k). Remove the child. cSavedDirList.remove(j); j } } } // Now add any directories found in cSavedDirList to // cDataDirs and dirChecked for(int j=0; j < cSavedDirList.size(); j++) { cDataDirs.add(cSavedDirList.get(j)); dirChecked.add(cSavedDirList.get(j)); } if(DebugOutput.isSetFor("updatedb")) Messages.postDebug("Updating for user, " + userName + "\n Data Dir List: " + cDataDirs); // Now loop thru all of this users data directories as // specified in userList. for(int i=0; i < cDataDirs.size(); i++) { dir = (String)cDataDirs.get(i); if(DebugOutput.isSetFor("updatedb")) Messages.postDebug(" Updating vnmr_data in " +dir); // Fill DB with files in this directory and below. fillATable(Shuf.DB_VNMR_DATA, dir, userName, true, info, sleepMs); if(DebugOutput.isSetFor("updatedb")) Messages.postDebug(" Updating vnmr_par in " +dir); fillATable(Shuf.DB_VNMR_PAR, dir, userName, true, info, sleepMs); if(DebugOutput.isSetFor("updatedb")) Messages.postDebug(" Updating study in " +dir); fillATable(Shuf.DB_STUDY, dir, userName, true, info, sleepMs); if(DebugOutput.isSetFor("updatedb")) Messages.postDebug(" Updating lcstudy in " +dir); fillATable(Shuf.DB_LCSTUDY, dir, userName, true, info, sleepMs); if(DebugOutput.isSetFor("updatedb")) Messages.postDebug(" Updating " + Shuf.DB_AUTODIR + " in " +dir); fillATable(Shuf.DB_AUTODIR, dir, userName, true, info, sleepMs); if(DebugOutput.isSetFor("updatedb")) Messages.postDebug(" Updating " + Shuf.DB_IMAGE_DIR + " in " +dir); fillATable(Shuf.DB_IMAGE_DIR, dir, userName, true, info, sleepMs); // Get Protocol Files // If dir ends with "data", remove it and use the // base path ahead of "data" String baseDir=dir; if(dir.endsWith(File.separator + "data")) { baseDir = dir.substring(0, dir.length() -5); } String pdir=FileUtil.vnmrDir(baseDir,"PROTOCOLS"); if(pdir !=null) { if(DebugOutput.isSetFor("updatedb")) Messages.postDebug(" Updating protocol in " +pdir); fillATable(Shuf.DB_PROTOCOL, pdir, userName, true, info, sleepMs); } // Non-FDA records should be in the cDataDirs list of // directories. if(DebugOutput.isSetFor("updatedb")) Messages.postDebug(" Updating record in " +dir); fillATable(Shuf.DB_VNMR_RECORD, dir, userName, true, info, sleepMs); } // Get directories to use for FDA records (.REC) // Fill records and the record data within the record dataDirs = user.getP11Directories(); for(int i=0; i < dataDirs.size(); i++) { dir = (String)dataDirs.get(i); if(DebugOutput.isSetFor("updatedb")) Messages.postDebug(" Updating P11 dir, " + dir); // Fill DB with files in this directory and below. fillATable(Shuf.DB_VNMR_RECORD, dir, userName, true, info, sleepMs); } } // Get this users shim directory and fill from it. ArrayList appDirs=user.getAppDirectories(); for(int i=0; i < appDirs.size(); i++) { String base=(String)appDirs.get(i); if(DebugOutput.isSetFor("updatedb")) Messages.postDebug(" Updating appDir base dir, " + base); dir=FileUtil.vnmrDir(base,"SHIMS"); if(dir !=null) fillATable(Shuf.DB_SHIMS, dir, userName, true, info); // Get this users xml directory and fill from it. dir=FileUtil.vnmrDir(base,"LAYOUT"); if(dir !=null){ fillATable(Shuf.DB_PANELSNCOMPONENTS, dir, userName, true, info); } dir=FileUtil.vnmrDir(base,"PANELITEMS"); if(dir !=null){ fillATable(Shuf.DB_PANELSNCOMPONENTS, dir, userName, true, info); } // Get Protocol Files dir=FileUtil.vnmrDir(base,"PROTOCOLS"); if(dir !=null) fillATable(Shuf.DB_PROTOCOL, dir, userName, true, info); // Get Trash Files dir=FileUtil.vnmrDir(base,"TRASH"); if(dir !=null) fillATable(Shuf.DB_TRASH, dir, userName, false, info, sleepMs); } if(!appdirOnly) { // Fill this users Workspaces if requested. The thread crawler // does not want to do this, since workspace attributes can be // updated on the fly and thus the disk file is out of date. if(workspace) { String path = user.getVnmrsysDir(); if(DebugOutput.isSetFor("updatedb")) Messages.postDebug(" Updating workspaces from " + path); fillATable(Shuf.DB_WORKSPACE, path, userName, false, info, sleepMs); } // Get the imported directories/files ArrayList list = readImportedDirs(user); // Loop thru the list of files/dir and add them // non recursively. for(int k=0; k < list.size(); k++) { String path = (String) list.get(k); String type = getType(path); // Do not allow the user's home directory in this list. // Too many customers have ended up with their home directory // in the list and it takes a long time to search all of // the extraneous directories. String userdir = user.getHomeDir(); if(path.equals(userdir)) continue; fillATable(type, path, userName, false, info, sleepMs); } } } if(info.numFilesAdded > 0) Messages.postMessage(OTHER|INFO|LOG, "Number of Files added/updated = " + info.numFilesAdded); info.numFilesAdded = 0; // Update the LocAttrList. Pass sleepMs on along. // If this is set, the update will sleep this long between // attributes. We need to call this after adding all the files, // to get the values into the table. if(DebugOutput.isSetFor("updatedb")) Messages.postDebug("updateDB starting fillAllListsFromDB"); attrList.fillAllListsFromDB(sleepMs * 4); } catch (InterruptedException ie) { // This normally means that we are closing vnmrj and // we need to forward this information up the line. throw new InterruptedException(); } catch (Exception e) { if(!ExitStatus.exiting()) Messages.writeStackTrace(e); } // Vacuum after updating for better user access vacuumDB(); if(DebugOutput.isSetFor("updatedb")) { endtime = new java.util.Date(); timems = endtime.getTime() - starttime.getTime(); Messages.postDebug("**Time for updatedb: " + timems); } } public ArrayList getAllAttributeNamesFromDB(String objType) throws Exception { java.sql.ResultSet rs; ResultSetMetaData md; int numCols; ArrayList output; String attr; java.util.Date starttime=null; if(DebugOutput.isSetFor("getAllAttributeNamesFromDB") || DebugOutput.isSetFor("locTiming")) starttime = new java.util.Date(); output = new ArrayList(); // Get a list of all attributes for this objType try { rs = executeQuery("SELECT * FROM " + objType + " WHERE \'false\'::bool"); if(rs == null) return output; // What we have now is all the columns, with no rows. // Get the column information. md = rs.getMetaData(); numCols = md.getColumnCount(); /* Get each attribute name, one at a time and test it. */ for(int i=1; i <= numCols; i++) { // Get the column name attr = md.getColumnName(i); // Cull out the long_time_saved entries and tags. // The tag names here will have the number attached, // just add the attr 'tag' below. if(!attr.equals("long_time_saved") && !attr.startsWith("tag")) output.add(attr); } // add in a tag attr output.add("tag"); } catch (Exception e) { haveConnection = false; throw e; } // Put into alphabetical or numeric order Collections.sort(output, new NumericStringComparator()); if(DebugOutput.isSetFor("getAllAttributeNamesFromDB")) Messages.postDebug("Attribute name list: " + output); if(DebugOutput.isSetFor("getAllAttributeNamesFromDB") || DebugOutput.isSetFor("locTiming")) { java.util.Date endtime = new java.util.Date(); long timems = endtime.getTime() - starttime.getTime(); Messages.postDebug("getAllAttributeNamesFromDB: Time(ms) " + timems + " for " + objType); } return output; } public int numTagColumns(String objType) throws SQLException { String colName; int numTags=0; long numCols; java.sql.ResultSet rs; ResultSetMetaData md; try { rs = executeQuery("SELECT * FROM " + objType + " WHERE \'false\'::bool"); if(rs == null) return 0; // What we have now is all the columns, with no rows. // Get the column information. md = rs.getMetaData(); numCols = md.getColumnCount(); /* Get each attribute name, one at a time and test it. Look for tag columns and get number following tag. */ for(int i=1; i <= numCols; i++) { colName = md.getColumnName(i); if(colName.startsWith("tag")) { if(Character.isDigit(colName.charAt(3))) { numTags++; } } } } catch (SQLException pe) { throw pe; } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postMessage(OTHER|ERROR|LOG|MBOX, "Problem getting information from DB"); Messages.postMessage(OTHER|ERROR|LOG, "numTagColumns failed while getting info" + " for " + objType); Messages.writeStackTrace(e); } return 0; } return numTags; } public ArrayList getAttrValueListFromDB(String attr, String objType, long sleepTimeMs) throws Exception { ArrayList output; java.sql.ResultSet rs; int numTagCol; String value; java.util.Date starttime=null; if(DebugOutput.isSetFor("getAttrValueListFromDB") || DebugOutput.isSetFor("locTiming")) starttime = new java.util.Date(); output = new ArrayList(); if(attr.startsWith("tag")) { /* I have not found a way to get SQL to give DISTINCT results across several columns. Thus we have to get the tag values for each tag column and weed out duplicated for ourselves. */ /* Get the number of tag columns. */ try { numTagCol = numTagColumns(objType); } catch (SQLException pe) { throw pe; } String user = System.getProperty("user.name"); for(int i=0; i < numTagCol; i++) { try { // Initially I used DISTINCT here, but some of the // items took 10-30 sec. Taking out the DISTINCT // gives us back all of the rows and they get // weeded out below. rs = executeQuery("SELECT \"tag" + i + "\" FROM " + objType); if(rs == null) return output; while(rs.next()) { // There is only one column of results, thus, col 1 value = rs.getString(1); // Trap out null and user:null // Also trap for only the current user if(value != null && !value.equals("null") && !value.equals(user + ":" + "null") && value.startsWith(user + ":")) { int index = value.indexOf(':'); if(index >= 0) value = value.substring(index +1); value = value.trim(); // Only add it if we do not already have it. if(!output.contains(value)) { // Be sure it is not whitespace if(value.length() > 0) { output.add(value); } } } } if(sleepTimeMs > 0) { try { Thread.sleep(sleepTimeMs); } catch(InterruptedException ie) { // This normally means that we are closing // vnmrj and we need to forward this // information up the line. throw ie; } catch(Exception e) { if(!ExitStatus.exiting()) Messages.writeStackTrace(e); throw e; } } } catch (InterruptedIOException ioe) { // This typically happens during shutdown. We do not // want the error printed out in that case, so // throw it. throw ioe; } catch (SocketException se) { // This typically happens during shutdown. We do not // want the error printed out in that case, so // throw it. throw se; } catch (Exception e) { if(!ExitStatus.exiting()) Messages.writeStackTrace(e); throw e; } } } // Is this attr for this objType an 'array' type? else { int isArray = isParamArrayType(objType, attr); if(isArray == -1) { // Stop this error temporarily during the transition of // removing these two items from the DB. if(!objType.equals(Shuf.DB_COMPUTED_DIR) && !objType.equals(Shuf.DB_IMAGE_FILE) && !attr.equals(Shuf.DB_COMPUTED_DIR)) { Messages.postDebug(attr + " is not in xxx_param_list.\n" + " It must be in the list to be used in " + "a statement for " + objType + "."); } return output; } if(isArray == 0) { // Not an array try { // Limit the results else we could get a million items // here and that causes problems. As long as the results // are used for menus, thousands does not make sense anyway. // Note: the menus are created of type EPopButton which // has colLength defined statically and thus // partially controls how many items end up in the menu. rs = executeQuery("SELECT DISTINCT \"" + attr + "\" FROM " + objType + " LIMIT 390"); if(rs == null) return output; while(rs.next()) { // There is only one column of results, therefore, col 1 value = rs.getString(1); if(value != null) { // Be sure it is not whitespace value = value.trim(); if(value.length() > 0) output.add(value); } } } catch (InterruptedIOException ioe) { // This typically happens during shutdown. We do not // want the error printed out in that case, so // throw it. throw ioe; } catch (Exception e) { if(!ExitStatus.exiting()) Messages.writeStackTrace(e); } } // Array type attribute else { /* There is not a way to use DISTINCT on an array type. Thus we have to get all values for all rows and weed out duplicated for ourselves. */ try { // Initially I used DISTINCT here, but some of the // items took 10-30 sec. Taking out the DISTINCT // gives us back all of the rows and they get // weeded out below. rs = executeQuery("SELECT \"" + attr + "\" FROM " + objType); if(rs == null) return output; while(rs.next()) { // Loop through the rows. // Loop through each value of each row. I can only // figure out how to get a string of all values // from an array type column. So, I have to // parse it myself. The string looks like // '{120,123,130}' or '{"str1", "str2"}' value = rs.getString(1); if(value != null && !value.equals("null")) { StringTokenizer tok; if(value.indexOf('\"') != -1) // This will leave commas alone, however, // commas between items will end up as lone // commas and we need to skip them below. tok = new StringTokenizer(value, "{}\""); else tok = new StringTokenizer(value, "{},"); while(tok.hasMoreTokens()) { // Loop through each value for this row. String string = tok.nextToken(); // Add only if not already in the list and // does not begin with a comma. if(!output.contains(string) && !string.startsWith(",")) { // Be sure it is not whitespace if(string.length() > 0) { output.add(string); } } } } } } catch (InterruptedIOException ioe) { // This typically happens during shutdown. We do not // want the error printed out in that case, so // throw it. throw ioe; } catch (Exception e) { if(!ExitStatus.exiting()) Messages.writeStackTrace(e); } } } // Alphabetize or numeric order Collections.sort(output, new NumericStringComparator()); if(DebugOutput.isSetFor("getAttrValueListFromDB")) { java.util.Date endtime = new java.util.Date(); long timems = endtime.getTime() - starttime.getTime(); Messages.postDebug("getAttrValueListFromDB: Time(ms) " + timems + " for " + objType + ":" + attr); } return output; } // Execute sql commands which return search results (rs) public java.sql.ResultSet executeQuery(String cmd) throws Exception { java.sql.ResultSet rs=null; // if(locatorOff() && !managedb) if(locatorOff()) return null; checkDBConnection(); if(sql == null || !haveConnection) { return null; } if(DebugOutput.isSetFor("sqlCmd")) Messages.postDebug("executeQuery SQL Command: " + cmd); rs = sql.executeQuery(cmd); return rs; } // Determine the number of rows which will result from executing // the given sql command and return that count. // Unfortunately, the newest postgresql.jar drivers do not give // a ResultSet that is scrollable. That means that I can no // longer just execute rs.last() and look at the row // I tried using the "count" sql command, but it does not like // my long and complicated sql commands. // I have run out of ideas, so now I just do the full search // twice. Here I do it once and count the rows. Then the // code will caall executeQuery() which will do the search again. // Yes, Yes, it has now been slowed down by a factor of 2. // The only saving grace is that the newer postgresql drivers // can search and sort about twice as fast, so it will probably // be the same speed at it used to be. (GRS 8/11/11) public int executeQueryCount(String cmd) throws Exception { java.sql.ResultSet rs=null; int count=0; String countCmd, end; // if(locatorOff() && !managedb) if (locatorOff()) return count; checkDBConnection(); if(sql == null || !haveConnection) { return count; } if(DebugOutput.isSetFor("sqlCmd")) Messages.postDebug("executeQueryCount SQL Command: " + cmd); try { rs = sql.executeQuery(cmd); while (rs.next()) { count++; } } catch (SQLException se) { throw se; } return count; } // Execute sql commands not returning search results public int executeUpdate(String cmd) throws SQLException { int status=0; // if(locatorOff() && !managedb) if (locatorOff()) return 0; checkDBConnection(); if(sql == null || !haveConnection) { return 0; } if(DebugOutput.isSetFor("sqlCmd")) Messages.postDebug("executeUpdate SQL Command: " + cmd); try { status = sql.executeUpdate(cmd); } catch (SQLException se) { // Trap for errors about duplicate rows or columns and do // not throw them up. These are okay. if(se != null && se.getMessage() != null) { if(se.getMessage().indexOf("already exists") != -1 && se.getMessage().indexOf("duplicate key") != -1) { throw se; } else return 0; } else { if(!ExitStatus.exiting()) { Messages.writeStackTrace(se, "executeUpdate: " + cmd); } else throw se; return 0; } } // Catch other exceptions like nullpointer and just exit catch (Exception e) { if(!ExitStatus.exiting()) { Messages.writeStackTrace(e, "executeUpdate: "); } return 0; } // If failure, output debug. // When tags are being cleared, there are normal failures since // every tag is not set. Trap these and do not output them. // if(status == 0 && cmd.indexOf("SET tag") == -1) { // if(!ExitStatus.exiting()) // Messages.postDebug("executeUpdate failed on command:\n " // + cmd); // return status; return 1; } // Get the postgres version number from the pg_ctl command public String getPostgresVersion() { String cmd; Runtime rt = Runtime.getRuntime(); // See if the /vnmr/pgsql/bin/pg_ctl exists. // if so, use it, if not, call pg_ctl without a fullpath. // This is to allow us to run the system postgres by // just moving /vnmr/pgsql/bin to a saved name out of the way. UNFile file = new UNFile("/vnmr/pgsql/bin/pg_ctl"); if(file.canExecute()) { // Use our released one cmd = "/vnmr/pgsql/bin/pg_ctl --version"; } else { // Use the system one cmd = "pg_ctl --version"; } String[] cmds = {UtilB.SHTOOLCMD, UtilB.SHTOOLOPTION, cmd}; Process prcs = null; String version=""; try { prcs = rt.exec(cmds); BufferedReader str = (new BufferedReader (new InputStreamReader (prcs.getInputStream()))); version = str.readLine(); str.close(); } catch (Exception ex) { } finally { // It is my understanding that these streams are left // open sometimes depending on the garbage collector. // So, close them. try { if(prcs != null) { OutputStream os = prcs.getOutputStream(); if(os != null) os.close(); InputStream is = prcs.getInputStream(); if(is != null) is.close(); is = prcs.getErrorStream(); if(is != null) is.close(); } } catch (Exception ex) {} } return version; } // Utility to tell if the locator is turned off. Include when run as adm tool. public static boolean locatorOff() { return locatoroff; } // Set variable determining if locator is active or not public void setLocatorOff(boolean setting) { locatoroff = setting; // Write out the new value to the persistence file writeLocatorOff(setting); // Cause another shuffle. SessionShare sshare = ResultTable.getSshare(); StatementHistory history = sshare.statementHistory(); history.updateWithoutNewHistory(); String persona = System.getProperty("persona"); if (persona != null && persona.equalsIgnoreCase("adm")) locatoroff = true; } // Convienent method to accept value as String static public void setDateLimitMsFromDays(String limitDays) { int limit; try { limit = Integer.parseInt(limitDays); } catch (Exception e) { // No error output limit = -1; } setDateLimitMsFromDays(limit); } // Get the dateLimit for keeping vnmr_data in the locator // dataLimitDays = 0 means nothing is kept except varian data // dataLimitDays = -1 means everything is kept // dataLimitDays greater than 0 means keep this many weeks of data // dataLimitDays is set with -Ddatelimit=# in the java startup cmd line static public void setDateLimitMsFromDays(int dataLimitDays) { Calendar dateLimit = Calendar.getInstance(); java.util.Date dateToday = new java.util.Date(); if(dataLimitDays < 0) { // a neg number means keep data forever, thus a limit of 0 dateLimit.setTime(new java.util.Date(0)); } else if(dataLimitDays == 0) { // 0 days means nothing is kept, just use a future date here dateLimit.setTimeInMillis(FUTURE_DATE); } else { // must have a positive number of days specified // Subtract that amount from today for the limit dateLimit.setTime(dateToday); dateLimit.add(Calendar.DAY_OF_MONTH, -dataLimitDays); } // Save this dateLimitMS = dateLimit.getTimeInMillis(); // Write out the value in days to the persistence file writeDateLimit(dataLimitDays); } static protected void writeDateLimit(int limit) { String filepath; FileWriter fw; PrintWriter os; filepath = FileUtil.savePath(FileUtil.sysdir() + "/pgsql/persistence/AgeLimit"); try { fw = new FileWriter(filepath); os = new PrintWriter(fw); os.println("DateLimit " + limit); os.close(); // Change the mode to all write access String[] cmd = {UtilB.SHTOOLCMD, UtilB.SHTOOLOPTION, "chmod 666 " + filepath}; Runtime rt = Runtime.getRuntime(); Process prcs = null; try { prcs = rt.exec(cmd); } finally { // It is my understanding that these streams are left // open sometimes depending on the garbage collector. // So, close them. if(prcs != null) { OutputStream ost = prcs.getOutputStream(); if(ost != null) ost.close(); InputStream is = prcs.getInputStream(); if(is != null) is.close(); is = prcs.getErrorStream(); if(is != null) is.close(); } } } catch (Exception e) { Messages.postError("Problem writing " + filepath); Messages.writeStackTrace(e); } } static public String getLocatorOffFile() { return FileUtil.savePath(FileUtil.sysdir() + "/pgsql/persistence/LocatorOff"); } static public void writeLocatorOff(boolean setting) { String filepath; FileWriter fw; PrintWriter os; // filepath = FileUtil.savePath(FileUtil.sysdir() // + "/pgsql/persistence/LocatorOff"); filepath = getLocatorOffFile(); Process prcs = null; try { fw = new FileWriter(filepath); os = new PrintWriter(fw); if(setting) os.println("locatorOff true"); else os.println("locatorOff false"); os.close(); // Change the mode to all write access String[] cmd = {UtilB.SHTOOLCMD, UtilB.SHTOOLOPTION, "chmod 666 " + filepath}; Runtime rt = Runtime.getRuntime(); prcs = rt.exec(cmd); } catch (Exception e) { Messages.postError("Problem writing " + filepath); Messages.writeStackTrace(e); } finally { // It is my understanding that these streams are left // open sometimes depending on the garbage collector. // So, close them. try { if(prcs != null) { OutputStream ost = prcs.getOutputStream(); if(ost != null) ost.close(); InputStream is = prcs.getInputStream(); if(is != null) is.close(); is = prcs.getErrorStream(); if(is != null) is.close(); } } catch (Exception ex) { Messages.writeStackTrace(ex); } } } static public boolean readLocatorOff(boolean usePersona) { BufferedReader in; String line; String value; StringTokenizer tok; String usedb = System.getProperty("usedb"); if (usedb != null) { if (usedb.equalsIgnoreCase("false")||usedb.equalsIgnoreCase("no")) { locatoroff = true; return locatoroff; } } if (usePersona) { String persona = System.getProperty("persona"); if (persona != null && persona.equalsIgnoreCase("adm")) { locatoroff = true; return locatoroff; } } String filepath = FileUtil.openPath(FileUtil.sysdir() + "/pgsql/persistence/LocatorOff"); // Temporarily try the users file in case they had set this in // a previous version. if(filepath==null) { filepath = FileUtil.openPath("USER/PERSISTENCE/LocatorOff"); if(filepath==null) { locatoroff = false; return locatoroff; } } try { in = new BufferedReader(new FileReader(filepath)); line = in.readLine(); if(!line.startsWith("locatorOff")) { in.close(); File file = new File(filepath); // Remove the corrupted file. file.delete(); value = "false"; } else { tok = new StringTokenizer(line, " \t\n"); value = tok.nextToken(); if (tok.hasMoreTokens()) { value = tok.nextToken(); } else value = "false"; in.close(); } } catch (Exception e) { // No error output here. value = "false"; } if(value.startsWith("t")) locatoroff = true; else locatoroff = false; return locatoroff; } static public String readDateLimit() { String filepath; BufferedReader in; String line; String value; StringTokenizer tok; int newValue; filepath = FileUtil.openPath(FileUtil.sysdir() + "/pgsql/persistence/AgeLimit"); if(filepath==null) { // Temporarily try the users file in case they had set this in // a previous version. filepath = FileUtil.openPath("USER/PERSISTENCE/DateLimit"); if(filepath==null) return "-1"; } try { in = new BufferedReader(new FileReader(filepath)); line = in.readLine(); if(!line.startsWith("DateLimit")) { in.close(); File file = new File(filepath); // Remove the corrupted file. file.delete(); // -1 means keep everything value = "-1"; } else { tok = new StringTokenizer(line, " \t\n"); value = tok.nextToken(); if (tok.hasMoreTokens()) { value = tok.nextToken(); in.close(); } else { in.close(); File file = new File(filepath); // Remove the corrupted file. file.delete(); // -1 means keep everything value = "-1"; } } } catch (Exception e) { // No error output here. value = "-1"; } try { newValue = Integer.parseInt(value); } catch (Exception e) { // No error output newValue = -1; File file = new File(filepath); // Remove the corrupted file. file.delete(); } setDateLimitMsFromDays(newValue); // return the time in days return value; } // We need 3 possible return values // 0 = false // 1 = true // -1 = param not found // I found a way to find out if an attribute in the DB is an // array type (starting with "_"). I ended up not using it but wanted to // note it here for future reference // Get the sql datatype. Those starting with "_" are arrays // datatype = md.getColumnTypeName(i); public int isParamArrayType(String objType, String param) { ShufDataParam sdp; if(objType.equals(Shuf.DB_VNMR_DATA) || objType.equals(Shuf.DB_VNMR_PAR) || objType.equals(Shuf.DB_WORKSPACE) || objType.equals(Shuf.DB_VNMR_REC_DATA) || objType.equals(Shuf.DB_VNMR_RECORD)) { sdp = (ShufDataParam)shufDataParams.get(param); // If the param does not exist in the list, return null to // notify the caller of this. if(sdp == null) return -1; if(sdp != null) { if(sdp.getType().endsWith("[]")) return 1; else return 0; } else return 0; } else if(objType.equals(Shuf.DB_STUDY) || objType.equals(Shuf.DB_LCSTUDY)) { sdp = (ShufDataParam)shufStudyParams.get(param); // If the param does not exist in the list, return null to // notify the caller of this. if(sdp == null) return -1; if(sdp != null && sdp.getType().endsWith("[]")) return 1; else return 0; } else if(objType.equals(Shuf.DB_PROTOCOL)) { sdp = (ShufDataParam)shufProtocolParams.get(param); // If the param does not exist in the list, return null to // notify the caller of this. if(sdp == null) return -1; if(sdp != null && sdp.getType().endsWith("[]")) return 1; else return 0; } else if(objType.equals(Shuf.DB_IMAGE_DIR) || objType.equals(Shuf.DB_IMAGE_FILE) || objType.equals(Shuf.DB_COMPUTED_DIR)) { sdp = (ShufDataParam)shufImageParams.get(param); // If the param does not exist in the list, return -1 to // notify the caller of this. if(sdp == null) return -1; if(sdp != null && sdp.getType().endsWith("[]")) return 1; else return 0; } else return 0; } static public ArrayList readImportedDirs(User user) { ArrayList list; UNFile file; // Stop Using this file and use the Vnmrj adm Data Directories instead 7/13 list = new ArrayList(); return list; // String filepath = FileUtil.userDir(user, "PERSISTENCE") + // File.separator + "ImportedDirs"; // list = new ArrayList(); // if(filepath != null) { // BufferedReader in; // String line; // String path; // StringTokenizer tok; // try { // file = new UNFile(filepath); // in = new BufferedReader(new FileReader(file)); // // File must start with 'Imported Directories' // if((line = in.readLine()) != null) { // if(!line.startsWith("Imported Directories")) { // Messages.postWarning("The " + filepath + " file is " + // "corrupted and being removed"); // // Remove the corrupted file. // file.delete(); // return list; // while ((line = in.readLine()) != null) { // if(!line.startsWith("#")) {// skip comments. // tok = new StringTokenizer(line, " :,\t\n"); // path = tok.nextToken(); // if(path.indexOf(File.separator) >= 0) { // // See if the file/dir still exists. Otherwise, // // files which disappear will stay in this list // // forever. // file = new UNFile(path); // if(file.exists()) { // // It exists, add it // list.add(path); // in.close(); // catch (Exception ioe) { } // return list; } static public String getType(String path) { UNFile file = new UNFile(path); String name = file.getName(); return getType(path, name); } static public String getType(String path, String name) { String type = "?"; // If path contains a colon, it means we have been passed the // hostfullpath. We need to remove the try { String dirName = path; UNFile pathFile = new UNFile(path); UNFile studyfile = new UNFile(path + File.separator + "studypar"); UNFile curparfile = new UNFile(path + File.separator + "curpar"); UNFile lcfile = new UNFile(path + File.separator + "lcpar"); UNFile autofile = new UNFile(path + File.separator + "autopar"); int last = path.lastIndexOf(File.separator, path.length()-1); int second = path.lastIndexOf(File.separator, last-1); if(last != -1 && second != -1 && last > second+1) dirName = path.substring(second+1, last); if(name.endsWith(Shuf.DB_FID_SUFFIX)) type = Shuf.DB_VNMR_DATA; else if(name.endsWith(Shuf.DB_PAR_SUFFIX)) type = Shuf.DB_VNMR_PAR; else if(name.endsWith(Shuf.DB_REC_SUFFIX)) type = Shuf.DB_VNMR_RECORD; else if(name.endsWith(Shuf.DB_REC_SUFFIX.toLowerCase())) type = Shuf.DB_VNMR_RECORD; // If file is within .rec or .REC, it must be rec_data else if(dirName.endsWith(Shuf.DB_REC_SUFFIX) || dirName.endsWith(Shuf.DB_REC_SUFFIX.toLowerCase())) type = Shuf.DB_VNMR_REC_DATA; else if(name.endsWith(Shuf.DB_IMG_DIR_SUFFIX)) type = Shuf.DB_IMAGE_DIR; // Even though we are not adding .fdf, .vfs and .crft files // to the DB, keep this type for D&D perposes else if(name.endsWith(Shuf.DB_IMG_FILE_SUFFIX)) type = Shuf.DB_IMAGE_FILE; else if(name.endsWith(Shuf.DB_VFS_SUFFIX)) type = Shuf.DB_VFS; else if(name.endsWith(Shuf.DB_CRFT_SUFFIX)) type = Shuf.DB_CRFT; else if(dirName.equals(Shuf.DB_SHIMS)) type = Shuf.DB_SHIMS; else if(dirName.equals("maclib")) type = Shuf.DB_COMMAND_MACRO; else if(dirName.equals("protocols")) type = Shuf.DB_PROTOCOL; // Allow icons to be in the icons directory here, OR if nothing // else catches the type, try at the end to see if it is an // image file type else if(dirName.equals("icons")) type = Shuf.DB_ICON; // There can be sub-directories under mollib, do not tag them // as molecule types. else if(dirName.equals("mollib")) { if(!pathFile.isDirectory()) type = Shuf.DB_MOLECULE; } // They want any arbitrary subdirectories under mollib // (except icons) to be molecule type. If we have here a file // (not a directory) and it was not caught by the "icons" test // above, then see if mollib is anyplace in the path. If it // is, set to molecule type. else if(!pathFile.isDirectory() && path.indexOf("mollib") != -1) { type = Shuf.DB_MOLECULE; } // See if the directory contains a studypar file else if(studyfile.exists()) type = Shuf.DB_STUDY; // See if the directory contains an lcpar file else if(lcfile.exists()) type = Shuf.DB_LCSTUDY; // See if the directory contains an autopar file else if(autofile.exists()) type = Shuf.DB_AUTODIR; // Check for .xml which could be protocol or panelNcomponent else if(name.endsWith(Shuf.DB_PROTOCOL_SUFFIX)) { // See if it is a protocol by looking into the file BufferedReader in; String line; in = new BufferedReader(new FileReader(pathFile)); while ((line = in.readLine()) != null) { if(line.indexOf("protocol title") != -1) { type = Shuf.DB_PROTOCOL; break; } } in.close(); // If it was not a protocol, then tag it as panelNcomp if(type.equals("?")) type = Shuf.DB_PANELSNCOMPONENTS; } else if(name.startsWith(Shuf.DB_WKS_PREFIX)) { // Is probably a workspace, but check for a curpar if(curparfile.exists()) { type = Shuf.DB_WORKSPACE; } } else if(dirName.equals("studies")) type = Shuf.DB_STUDY; else { // Okay, if we got here, it has not been identified at all. // Check to see if it is an image type file readable by the // "imagefile" vnmr command. This ends up using the system // command /usr/bin/convert to convert to .gif format // It should work for anything "convert" supports, what ever // that list is. // Right now the .tif and .tiff don't seem to work, but I believe // that is "convert". if(path.endsWith(".gif") || path.endsWith(".jpg") || path.endsWith(".jpeg") || path.endsWith(".png") || path.endsWith(".bmp") || path.endsWith(".tif") || path.endsWith(".tiff")) { type = Shuf.DB_ICON; } // Now they want .mol in any directory also. If it is in mollib // then it was caught above. Else, see if the file is .mol if(path.endsWith(".mol")) type = Shuf.DB_MOLECULE; } } catch (Exception e) { if(!ExitStatus.exiting()) Messages.writeStackTrace(e,"Caught in FillDBManager.getType()"); } return type; } protected String checkDBversion() { String cmd; java.sql.ResultSet rs; String version=""; String vnmrjversion=""; return "okay"; // if(locatorOff() && !managedb) // return "okay"; // // Get host string from DB // /* Create SQL command */ // cmd = new String("SELECT hostname FROM " + Shuf.DB_VERSION); // try { // rs = executeQuery(cmd); // if(rs == null) // return "bad"; // catch (Exception e) { // if(!ExitStatus.exiting()) // Messages.postMessage(OTHER|LOG, // "Problem getting hostname from version DB table"); // return "bad"; // // Get version string from the version table in the DB // /* Create SQL command */ // cmd = new String("SELECT version FROM " + Shuf.DB_VERSION); // try { // rs = executeQuery(cmd); // if(rs == null) // return "bad"; // if(rs.next()) { // // getString() gives the string representation even if // // the column type is int or float or date // version = rs.getString(1); // catch (Exception e) { // if(!ExitStatus.exiting()) // Messages.postMessage(OTHER|LOG, // "Problem getting version from version DB table"); // return "bad"; // // Compare version retrieved to current version in DBVERSION // if(!version.equals(DBVERSION)) { // // If we got here, the versions don't match. // return "bad"; // // vnmrj/managedb. If not, have it rebuilt. This is to avoid // // having to rebuild multiple times for those of us who install // // multiple times. This is only for managedb, not vnmrj // if (managedb) { // // Get vnmrjversion string from the version table in the DB // /* Create SQL command */ // cmd = new String("SELECT vnmrjversion FROM " + Shuf.DB_VERSION); // try { // rs = executeQuery(cmd); // // If this field does not exist yet, then cause a rebuild // if (rs == null) // return "bad"; // if (rs.next()) { // vnmrjversion = rs.getString(1); // catch (Exception e) { // if (!ExitStatus.exiting()) // // Do not post an error, just return bad // Messages.postMessage(OTHER|LOG, // "Problem getting vnmrjversion from the version table"); // return "bad"; // // Get the current vnmrj version // String curVer = getVnmrjVersion(); // // Compare vnmrjversion retrieved to current version // if (!vnmrjversion.equals(curVer)) { // // We need to rebuild // return "bad"; // return "okay"; } public static String getUnixOwner(String fullpath) { Process proc=null; String owner=""; try { Runtime rt = Runtime.getRuntime(); String dir = System.getProperty("sysdir"); // If a file or directory does not exist, fileowner will // return an owner of 'root' String cmd; // Windows needs double quotes around the filename in case // there are any spaces. Unix fileowner did not like the quotes. if(UtilB.OSNAME.startsWith("Windows")) cmd = dir +"/bin/fileowner \"" + fullpath + "\""; else cmd = dir +"/bin/fileowner " + fullpath ; proc = rt.exec(cmd); BufferedReader str = (new BufferedReader (new InputStreamReader (proc.getInputStream()))); owner = str.readLine(); } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postDebug("Problem getting owner of " + fullpath); Messages.writeStackTrace(e); } } finally { // It is my understanding that these streams are left // open sometimes depending on the garbage collector. // So, close them. try { if(proc != null) { OutputStream os = proc.getOutputStream(); if(os != null) os.close(); InputStream is = proc.getInputStream(); if(is != null) is.close(); is = proc.getErrorStream(); if(is != null) is.close(); } } catch (Exception ex) { Messages.writeStackTrace(ex); } } return owner; } public void dbStatus() { java.sql.ResultSet rs; int numRows; String cmd; String version="empty"; String networkmode="unknown"; try { infoIfManagedbLogIfVnmrj("** Start DataBase Contents Report **"); cmd = new String("SELECT version, networkmode FROM " + Shuf.DB_VERSION); rs = executeQuery(cmd); if(rs != null && rs.next()) { // getString() gives the string representation even if // the column type is int or float or date version = rs.getString(1); networkmode = rs.getString(2); } infoIfManagedbLogIfVnmrj("DB version: " + version + " DB Host: " + dbHost + "\n Local Host: " + localHost + " Network Mode: " + networkmode); numRows = 0; rs = executeQuery("SELECT filename FROM " + Shuf.DB_VNMR_DATA); if(rs != null) while(rs.next()) numRows++; infoIfManagedbLogIfVnmrj("Number of " + Shuf.DB_VNMR_DATA + " items in DB = " + numRows); numRows = 0; rs = executeQuery("SELECT filename FROM " + Shuf.DB_VNMR_PAR); if(rs != null) while(rs.next()) numRows++; infoIfManagedbLogIfVnmrj("Number of " + Shuf.DB_VNMR_PAR + " items in DB = " + numRows); numRows = 0; rs = executeQuery("SELECT filename FROM " + Shuf.DB_VNMR_RECORD); if(rs != null) while(rs.next()) numRows++; infoIfManagedbLogIfVnmrj("Number of " + Shuf.DB_VNMR_RECORD + " items in DB = " + numRows); numRows = 0; rs = executeQuery("SELECT filename FROM " + Shuf.DB_VNMR_REC_DATA); if(rs != null) while(rs.next()) numRows++; infoIfManagedbLogIfVnmrj("Number of " + Shuf.DB_VNMR_REC_DATA + " items in DB = " + numRows); numRows = 0; rs = executeQuery("SELECT fullpath FROM " + Shuf.DB_AUTODIR); if(rs != null) while(rs.next()) numRows++; infoIfManagedbLogIfVnmrj("Number of " + Shuf.DB_AUTODIR + " items in DB = " + numRows); numRows = 0; rs = executeQuery("SELECT filename FROM " + Shuf.DB_WORKSPACE); if(rs != null) while(rs.next()) numRows++; infoIfManagedbLogIfVnmrj("Number of " + Shuf.DB_WORKSPACE + " items in DB = " + numRows); numRows = 0; rs = executeQuery("SELECT filename FROM " + Shuf.DB_PANELSNCOMPONENTS); if(rs != null) while(rs.next()) numRows++; infoIfManagedbLogIfVnmrj("Number of " + Shuf.DB_PANELSNCOMPONENTS + " items in DB = " + numRows); numRows = 0; rs = executeQuery("SELECT filename FROM " + Shuf.DB_SHIMS); if(rs != null) while(rs.next()) numRows++; infoIfManagedbLogIfVnmrj("Number of " + Shuf.DB_SHIMS + " items in DB = " + numRows); numRows = 0; rs = executeQuery("SELECT name FROM " + Shuf.DB_COMMAND_MACRO); if(rs != null) while(rs.next()) numRows++; infoIfManagedbLogIfVnmrj("Number of " + Shuf.DB_COMMAND_MACRO + " items in DB = " + numRows); numRows = 0; rs = executeQuery("SELECT name FROM " + Shuf.DB_PPGM_MACRO); if(rs != null) while(rs.next()) numRows++; infoIfManagedbLogIfVnmrj("Number of " + Shuf.DB_PPGM_MACRO + " items in DB = " + numRows); numRows = 0; rs = executeQuery("SELECT filename FROM " + Shuf.DB_PROTOCOL); if(rs != null) while(rs.next()) numRows++; infoIfManagedbLogIfVnmrj("Number of " + Shuf.DB_PROTOCOL + " items in DB = " + numRows); numRows = 0; rs = executeQuery("SELECT filename FROM " + Shuf.DB_STUDY); if(rs != null) while(rs.next()) numRows++; infoIfManagedbLogIfVnmrj("Number of " + Shuf.DB_STUDY + " items in DB = " + numRows); numRows = 0; rs = executeQuery("SELECT filename FROM " + Shuf.DB_LCSTUDY); if(rs != null) while(rs.next()) numRows++; infoIfManagedbLogIfVnmrj("Number of " + Shuf.DB_LCSTUDY + " items in DB = " + numRows); numRows = 0; rs = executeQuery("SELECT filename FROM " + Shuf.DB_IMAGE_DIR); if(rs != null) while(rs.next()) numRows++; infoIfManagedbLogIfVnmrj("Number of " + Shuf.DB_IMAGE_DIR + " items in DB = " + numRows); numRows = 0; rs = executeQuery("SELECT filename FROM " + Shuf.DB_TRASH); if(rs != null) while(rs.next()) numRows++; infoIfManagedbLogIfVnmrj("Number of " + Shuf.DB_TRASH + " items in DB = " + numRows); infoIfManagedbLogIfVnmrj("Total Number of " + Shuf.DB_VNMR_DATA + " attributes = " + shufDataParams.size()); infoIfManagedbLogIfVnmrj("Total Number of " + Shuf.DB_STUDY + " attributes = " + shufStudyParams.size()); infoIfManagedbLogIfVnmrj("Total Number of " + Shuf.DB_PROTOCOL + " attributes = " + shufProtocolParams.size()); infoIfManagedbLogIfVnmrj("Total Number of " + Shuf.DB_IMAGE_DIR + " attributes = " + shufImageParams.size()); infoIfManagedbLogIfVnmrj("** End DataBase Contents Report **"); } catch (Exception e) { if(!ExitStatus.exiting()) Messages.writeStackTrace(e); } } // Test to see whether we are in managedb or vnmrj. If we are in // managedb, write the output via postDebug so that it goes into the // log file and to stdout. If Vnmrj, write out to postLog static public void infoIfManagedbLogIfVnmrj(String msg) { if(managedb) Messages.postDebug(msg); else Messages.postLog(msg); } public int getNumFidsInDB() { java.sql.ResultSet rs; int numRows=0; try { rs = executeQuery("SELECT filename FROM " + Shuf.DB_VNMR_DATA); if(rs != null) while(rs.next()) numRows++; } catch (Exception e) { Messages.writeStackTrace(e); return 0; } return numRows; } public void updateThisTable (String objType) { User user; String userName; String dir; ArrayList dataDirs; DBCommunInfo info = new DBCommunInfo(); boolean foundit=false; // If no connection, this will output one error, then we can quit. if(checkDBConnection() == false) return; if(DebugOutput.isSetFor("updateThisTable")) Messages.postDebug("updateThisTable Updating " + objType + " table."); if(objType.equals("all")) { try { LoginService loginService = LoginService.getDefault(); Hashtable users = loginService.getuserHash(); // Just call the normal updateDB routine and let it go updateDB(users, 0); } catch (InterruptedException e) {} if(DebugOutput.isSetFor("updateThisTable")) Messages.postDebug("updateThisTable finished updating."); return; } // Both macro types are taken care of here. They are not related // to users. if(objType.endsWith("macro")) { updateMacro(Shuf.DB_COMMAND_MACRO); updateMacro(Shuf.DB_PPGM_MACRO); if(DebugOutput.isSetFor("updateThisTable")) Messages.postDebug("updateThisTable finished updating."); // Update the LocAttrList. try { attrList.fillAllListsFromDB(0); } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postError("Problem updating LocattrList"); Messages.writeStackTrace(e); } return; } return; } // Check to see that this is a valid table type for(int i=0; i<Shuf.OBJTYPE_LIST.length; i++) { if(objType.equals(Shuf.OBJTYPE_LIST[i])) foundit = true; } if(!foundit) { Messages.postError(objType + " not a valid DB table."); return; } // Update the LocAttrList DB table. // try { // attrList.fillAllListsFromDB(0); // catch (Exception e) { // if(!ExitStatus.exiting()) { // Messages.postError("Problem updating LocattrList"); // Messages.writeStackTrace(e); // else // return; cleanupDBListThisType(objType, info); // Clean up the SymLinkList. if(symLinkMap != null) symLinkMap.cleanDirChecked(); LoginService loginService = LoginService.getDefault(); Hashtable users = loginService.getuserHash(); // Go thru the users for(Enumeration en = users.elements(); en.hasMoreElements(); ) { user = (User) en.nextElement(); userName = user.getAccountName(); if(DebugOutput.isSetFor("updateThisTable")) Messages.postDebug("updateThisTable Updating for user, " + userName); // Now loop thru all of this users data directories as // specified in userList. dataDirs = user.getDataDirectories(); for(int i=0; i < dataDirs.size(); i++) { dir = (String)dataDirs.get(i); if(DebugOutput.isSetFor("updateThisTable")) Messages.postDebug(" Updating dir, " + dir + " for objType " + objType); if(objType.startsWith("vnmr_") || objType.equals(Shuf.DB_AUTODIR) || objType.equals(Shuf.DB_STUDY) || objType.equals(Shuf.DB_LCSTUDY) || objType.equals(Shuf.DB_IMAGE_DIR) || objType.equals(Shuf.DB_COMPUTED_DIR)) // Fill DB with files in this directory and below. fillATable(objType, dir, userName, true, info, 0); } // Get directories to use for FDA records (.REC) // Fill records and the record data within the record if(objType.equals(Shuf.DB_VNMR_RECORD)) { dataDirs = user.getP11Directories(); for(int i=0; i < dataDirs.size(); i++) { dir = (String)dataDirs.get(i); if(DebugOutput.isSetFor("updatedb")) Messages.postDebug(" Updating P11 dir, " + dir); // Fill DB with files in this directory and below. fillATable(Shuf.DB_VNMR_RECORD, dir, userName, true, info, 0); } } ArrayList appDirs=user.getAppDirectories(); for(int i=0; i < appDirs.size(); i++) { String base=(String)appDirs.get(i); if(DebugOutput.isSetFor("updatedb")) Messages.postDebug(" Updating appDir base dir, " + base); if(objType.equals(Shuf.DB_SHIMS)) { dir=FileUtil.vnmrDir(base,"SHIMS"); if(dir !=null) fillATable(Shuf.DB_SHIMS, dir, userName, true, info); if(DebugOutput.isSetFor("updateThisTable")) Messages.postDebug("updateThisTable finished."); } // Get this users xml directory and fill from it. else if(objType.equals(Shuf.DB_PANELSNCOMPONENTS)) { dir=FileUtil.vnmrDir(base,"LAYOUT"); if(dir !=null){ fillATable(Shuf.DB_PANELSNCOMPONENTS, dir, userName, true, info); } dir=FileUtil.vnmrDir(base,"PANELITEMS"); if(dir !=null){ fillATable(Shuf.DB_PANELSNCOMPONENTS, dir, userName, true, info); } if(DebugOutput.isSetFor("updateThisTable")) Messages.postDebug("updateThisTable finished."); } // Get Protocol Files else if(objType.equals(Shuf.DB_PROTOCOL)) { dir=FileUtil.vnmrDir(base,"PROTOCOLS"); if(dir !=null) fillATable(Shuf.DB_PROTOCOL, dir, userName, true, info); if(DebugOutput.isSetFor("updateThisTable")) Messages.postDebug("updateThisTable finished."); } // Get Trash Files else if(objType.equals(Shuf.DB_TRASH)) { dir=FileUtil.vnmrDir(base,"TRASH"); if(dir !=null) fillATable(Shuf.DB_TRASH, dir, userName, false, info, 0); if(DebugOutput.isSetFor("updateThisTable")) Messages.postDebug("updateThisTable finished."); } } // Fill this users Workspaces if(objType.equals(Shuf.DB_WORKSPACE)) { String path = user.getVnmrsysDir(); if(DebugOutput.isSetFor("updatedb")) Messages.postDebug(" Updating workspaces from " + path); fillATable(Shuf.DB_WORKSPACE, path, userName, false, info, 0); if(DebugOutput.isSetFor("updateThisTable")) Messages.postDebug("updateThisTable finished."); } } if(info.numFilesAdded > 0) Messages.postMessage(OTHER|INFO|LOG, "Number of Files added/updated = " + info.numFilesAdded); info.numFilesAdded = 0; // Update the LocAttrList. try { attrList.fillAllListsFromDB(0); } catch (Exception e) { if(!ExitStatus.exiting()) { Messages.postError("Problem updating LocattrList"); Messages.writeStackTrace(e); } } if(DebugOutput.isSetFor("updateThisTable")) Messages.postDebug("updateThisTable finished with update."); } public boolean setNonTagAttributeValue(String objType, String fullpath, String host, String attr, String attrType, String attrVal) { StringBuffer cmd; String dpath, dhost; UNFile file; // if (locatorOff() && !managedb) if (locatorOff()) return false; if(DebugOutput.isSetFor("setAttributeValue")) { Messages.postDebug("setNonTagAttributeValue: objType = " + objType + " attr = " + attr + " attrVal = " + attrVal + "\nfullpath = " + fullpath); } try { file = new UNFile(fullpath); // If the file does not exist, bail out if(!file.exists()) { return false; } Vector mp = MountPaths.getCanonicalPathAndHost(fullpath); dhost = (String) mp.get(Shuf.HOST); dpath = (String) mp.get(Shuf.PATH); } catch (Exception e) { Messages.postError("Problem updating attribute value for\n " + fullpath); Messages.writeStackTrace(e); return false; } // See if this attribute exists. If not, it will be added. if(isAttributeInDB(objType, attr, attrType, dpath)) { if(objType.endsWith(Shuf.DB_MACRO)) { cmd = new StringBuffer("UPDATE "); cmd.append(objType).append(" SET \"").append(attr); cmd.append("\" = \'").append(attrVal); cmd.append("\' WHERE name = \'").append(dpath); cmd.append("\'"); } else { cmd = new StringBuffer("UPDATE "); cmd.append(objType).append(" SET \"").append(attr); cmd.append("\" = \'").append(attrVal); cmd.append("\' WHERE host_fullpath = \'"); cmd.append(dhost).append(":").append(dpath); cmd.append("\'"); } try { executeUpdate(cmd.toString()); return true; } catch (Exception e) { Messages.postError("Problem setting value for \n " + attr + " in " + dpath); Messages.writeStackTrace(e,"setNonTagAttributeValue: objType = " + objType + "\fullpath = " + dpath + "\nattr = " + attr + " attrType = " + attrType + " attrVal = " + attrVal); return false; } } return true; } public void setAvailSubTypes(ArrayList typeList) { String cmd; // First empty the table clearOutTable(Shuf.DB_AVAIL_SUB_TYPES, "all"); // if (locatorOff() && !managedb) if (locatorOff()) return; // Now loop through the list and insert the types into the table. for(int i=0; i < typeList.size(); i++) { String type = (String) typeList.get(i); cmd = "INSERT INTO " + Shuf.DB_AVAIL_SUB_TYPES + " (types, filename, fullpath) VALUES (\'" + type + "\', \'" + type + "\', \'" + type + "\')"; try { executeUpdate(cmd); } catch(Exception e) { Messages.postError("Problem filling " +Shuf.DB_AVAIL_SUB_TYPES); Messages.writeStackTrace(e); } } } public ArrayList getAvailSubTypeList(String objType, String hostFullpath) { ArrayList subTypeList = new ArrayList(); String cmd; java.sql.ResultSet rs; // Loop through all DB types for(int i=0; i < Shuf.OBJTYPE_LIST.length; i++) { // Search to see if any items of objType have this // attribute set to hostFullpath. cmd = "SELECT filename FROM " + Shuf.OBJTYPE_LIST[i] + " WHERE " + objType + " = \'" + hostFullpath + "\'"; try { rs = executeQuery(cmd); if(rs != null) { if(rs.next()) subTypeList.add(Shuf.OBJTYPE_LIST[i]); } } // Don't do anything with errors, just keep going. catch(Exception e) { } } if(DebugOutput.isSetFor("subTypeList")) Messages.postDebug("subTypeList for " + objType + " and " + hostFullpath + " is:\n" + subTypeList); return subTypeList; } void vacuumDB() { vacuumDB(""); } void vacuumDB(String objTypeInput) { String filepath; PrintWriter out; java.util.Date starttime=null; java.util.Date endtime; long timems; String objType; objType = new String(objTypeInput); // If the objType is a container type (study, automation, image_dir, // lcstudyor record) then we will just vacuum all of the DB, else if we // don't vac a table that is within the container, the DB slows // down while being filled. if(objType.equals(Shuf.DB_STUDY) || objType.equals(Shuf.DB_IMAGE_DIR) || objType.equals(Shuf.DB_COMPUTED_DIR) || objType.equals(Shuf.DB_AUTODIR) || objType.equals(Shuf.DB_VNMR_RECORD) || objType.equals(Shuf.DB_LCSTUDY)) { objType = ""; // Force full vacuum } // Vacuum the DB try { if(DebugOutput.isSetFor("vacuumDB")) { starttime = new java.util.Date(); } String cmd = "VACUUM ANALYZE "+ objType; executeUpdate(cmd); if(DebugOutput.isSetFor("vacuumDB")) { endtime = new java.util.Date(); timems = endtime.getTime() - starttime.getTime(); if(objType.equals("")) Messages.postDebug("Time for Vacuum of All (ms): " + timems); else Messages.postDebug("Time for Vacuum of " + objType + " (ms): " + timems); } } catch(Exception e) { // Put error in log Messages.postDebug("Problem Vaccuming the DB. This will not cause " + "any problem with the system."); Messages.writeStackTrace(e); } // Save the date/time that Vacuum was last run java.util.Date date = new java.util.Date(); long longTime = date.getTime(); // This is time in ms from 1970. Convert to hours longTime /= 3600000; try { // If dir does not exist or is not writable, just exit. UNFile dir = new UNFile(FileUtil.sysdir() + "/pgsql/persistence"); if(!dir.canWrite()) { if(DebugOutput.isSetFor("vacuumDB")) { Messages.postDebug(FileUtil.sysdir() + "/pgsql/persistence\n" + "does not exist or is not writable." + "\nSkipping writing of vacuumDate."); return; } } filepath = FileUtil.savePath(FileUtil.sysdir() + "/pgsql/persistence/vacuumDate"); // savePath returns path on Windows in Windows format, change it // to unix. filepath = UtilB.windowsPathToUnix(filepath); } catch (Exception e) { Messages.postError(" Problem writing " + FileUtil.sysdir() + "/pgsql/persistence/vacuumDate\n" + " Skipping writing of vacuumDate."); Messages.writeStackTrace(e); return; } if(filepath == null) { Messages.postDebug(" Problem opening " + FileUtil.sysdir() + "/pgsql/persistence\n" + " Skipping writing of vacuumDate."); return; } try { // Write out the file in plain text UNFile file = new UNFile(filepath); out = new PrintWriter(new FileWriter(file)); // Write out a header line out.println("Last VacuumDB time in hours since 1970"); out.println(longTime); out.close(); } catch (Exception e) { Messages.writeStackTrace(e); } // savePath returns path on Windows in Windows format, change it // to unix if necessary. filepath = UtilB.windowsPathToUnix(filepath); // The file should now exist, be sure it has world write access // so that future users can access it. String[] cmd = {UtilB.SHTOOLCMD, UtilB.SHTOOLOPTION, "chmod 666 " + filepath}; Process prcs = null; try { Runtime rt = Runtime.getRuntime(); prcs = rt.exec(cmd); // Be sure this completes before continuing. prcs.waitFor(); } catch (Exception e) { Messages.postDebug(" Problem with cmd: " + cmd[0] + cmd[1] + cmd[2] + "\nSkipping writing of vacuumDate."); Messages.writeStackTrace(e); return; } finally { // It is my understanding that these streams are left // open sometimes depending on the garbage collector. // So, close them. if(prcs != null) { try { OutputStream os = prcs.getOutputStream(); if(os != null) os.close(); InputStream is = prcs.getInputStream(); if(is != null) is.close(); is = prcs.getErrorStream(); if(is != null) is.close(); } catch (Exception ex) { Messages.writeStackTrace(ex); } } } } public boolean vacuumOverdue() { String filepath; BufferedReader in; String line; int prevTime=0; filepath=FileUtil.openPath(FileUtil.sysdir() + "/pgsql/persistence/vacuumDate"); // If the file does not exist, report that update is needed // It should have been created during an installation in dbsetup if(filepath==null) return true; try { UNFile file = new UNFile(filepath); in = new BufferedReader(new FileReader(file)); // The file must start with "Last VacuumDB" or ignore the rest. line = in.readLine(); if(line != null && line.indexOf("VacuumDB") > 0) { // The second line should be the number of hours since 1970 line = in.readLine(); if(line != null) { // Convert to int prevTime = Integer.parseInt(line); } } in.close(); } catch (IOException e) { // No error output here. } catch (Exception e) { Messages.writeStackTrace(e); } // Now prevTime will either be 0, or the value from the file. // Get the current time in hr from 1970 java.util.Date date = new java.util.Date(); long curTime = date.getTime(); // This is time in ms from 1970. Convert to hours curTime /= 3600000; // Compare the hours if(curTime - prevTime > 1) // 1 means every 1 hours return true; // Needs update else return false; // Does not need update } private static boolean errSent=false; public boolean getNetworkModeFromDB() { String cmd, mode; boolean networkmode = false; java.sql.ResultSet rs; // If no locator don't try to do this stuff if(locatorOff()) { return false; } try { cmd = new String("SELECT networkmode FROM " + Shuf.DB_VERSION); rs = executeQuery(cmd); if(rs != null && rs.next()) { // getString() gives the string representation even if // the column type is int or float or date mode = rs.getString(1); if(mode.equals("true")) { networkmode = true; } } } catch (Exception e) { Messages.postDebug("Problem getting network mode from DB"); Messages.writeStackTrace(e); return false; } // If networkmode = false, then check to be sure dbhost is // the local host. If not, give error and try local host if(!errSent) { if(networkmode == false && !dbHost.equals(localHost)) { Messages.postError("The database being specified on " + dbHost + "\n is set up for non-network mode." + " Either specify PGHOST on " + localHost + "\n as \'" + localHost + "\' or rebuild the database on " + dbHost + " as a network \n mode database." + " Trying to switch to local host as " + "database server."); // Only do the test and error output once. errSent = true; // We cannot allow this machine to access the remote DB if it // has networkmode set to false. So, reset dbHost to be // the local host, then disconnect and reconnect to the DB. dbHost = localHost; closeDBConnection(); makeDBConnection(); } } // The result should be true or false. return networkmode; } public String getDefaultPath(String objType, String fname) { String fpath; if(fname.startsWith(File.separator) || fname.indexOf(":") == 1 ) { // arg contains a full path fpath = new String(fname); } else { // Not a full path, get default full path for this objType. if(objType.equals(Shuf.DB_VNMR_DATA)) fpath = FileUtil.openPath("USER" + File.separator + "DATA" + File.separator + fname); else if(objType.equals(Shuf.DB_VNMR_PAR)) fpath = FileUtil.openPath("USER" + File.separator + "DATA" + File.separator + fname); else if(objType.equals(Shuf.DB_PANELSNCOMPONENTS)) fpath = FileUtil.openPath("USER" + File.separator +"PANELITEMS"+ File.separator + fname); else if(objType.equals(Shuf.DB_SHIMS)) fpath = FileUtil.openPath("USER" + File.separator + "SHIMS" + File.separator + fname); else if(objType.equals(Shuf.DB_STUDY)) fpath = FileUtil.openPath("USER" + File.separator + "STUDIES" + File.separator + fname); else if(objType.equals(Shuf.DB_LCSTUDY)) fpath = FileUtil.openPath("USER" + File.separator + "LCSTUDIES"+ File.separator + fname); else if(objType.equals(Shuf.DB_AUTODIR)) fpath = FileUtil.openPath("USER" + File.separator + "AUTODIR" + File.separator + fname); else if(objType.equals(Shuf.DB_PROTOCOL)) fpath = FileUtil.openPath("USER" + File.separator +"PROTOCOLS" + File.separator + fname); else if(objType.equals(Shuf.DB_IMAGE_DIR)) fpath = FileUtil.openPath("USER" + File.separator + "IMAGES" + File.separator + fname); else if(objType.equals(Shuf.DB_COMPUTED_DIR)) fpath = FileUtil.openPath("USER" + File.separator + "IMAGES" + File.separator + fname); else if(objType.equals(Shuf.DB_IMAGE_FILE)) fpath = FileUtil.openPath("USER" + File.separator + "IMAGES" + File.separator + fname); else { Messages.postError("DB type " + objType + " Not available."); return null; } } return fpath; } // Set the table notify as modified for this objType for all hosts // in the table, except for this localHost. That is, notify everyone // else, but no need to notify ourselves. public void sendTableModifiedNotification(String objType) { String cmd; java.sql.ResultSet rs; ArrayList hostList = new ArrayList(); String host, value; // First get the list of hosts who have registered to be notified // excluding this host. try { rs = executeQuery("SELECT DISTINCT host FROM notify"); if(rs == null) return; while(rs.next()) { // There is only one column of results, therefore, col 1 value = rs.getString(1); if(value != null) { // Be sure it is not whitespace value = value.trim(); if(value.length() > 0) { // Eliminate this host from the list unless we are // in managedb, then go ahead with localhost to // trigger vnmrj. if(!value.equals(localHost) || managedb == true) { hostList.add(value); } } } } } catch (Exception e) { // If managedb, do not output any errors here. It is possible // for the notify table to not exist yet at this point if // vnmrj has not been executed yet. if(!managedb) Messages.writeStackTrace(e); } // Set the table for each host in the list for(int i=0; i < hostList.size(); i++) { host = (String) hostList.get(i); cmd = "UPDATE notify SET " + objType + " = \'modified\' WHERE " + "host = \'" + host + "\'"; try { executeUpdate(cmd); } catch (Exception e) { } } } // Take a string value then call the acqual calculation public static Double convertFreqToTesla(String h1freq) { if(h1freq == null) h1freq = "0"; Double field = new Double(h1freq); return convertFreqToTesla(field.doubleValue()); } // Calculate the Tesla field for this proton frequency. // Round to one decimal place. If the result is near one of the // standard fields, then force it to that value public static Double convertFreqToTesla(double h1freq) { double field = h1freq / 42.58; // Round to one decimal place long tmp = Math.round(field * 10.0); field = (double)tmp/10.0; if(field > 4.5 && field < 4.9) field = 4.7; else if(field > 6.8 && field < 7.2) field = 7.0; else if(field > 9.2 && field < 9.6) field = 9.4; else if(field > 11.4 && field < 12.0) field = 11.7; else if(field > 13.8 && field < 14.4) field = 14.1; else if(field > 16.1 && field < 16.7) field = 16.4; else if(field > 18.5 && field < 19.1) field = 18.8; return field; } } // class FillDBManager class DBCommunInfo { public StringBuffer addCmd; public StringBuffer cmdValueList; public String hostFullpath; public boolean firstAttr; public boolean keySet; public int numFilesAdded; public int numFilesRemoved; public ArrayList attrList; DBCommunInfo() { numFilesAdded = 0; numFilesRemoved = 0; attrList = new ArrayList(); } public String toString() { String str = "addCmd = " + addCmd + " cmdValueList = " + cmdValueList + " hostFullpath = " + hostFullpath + " firstAttr = " + firstAttr + "\nkeySet = " + keySet + " numFilesAdded = " + numFilesAdded + " numFilesRemoved = " + numFilesRemoved + "\nattrList = " + attrList; return str; } } class UpdateSymLinks extends Thread { String dirToSearch; SymLinkMap symLinkMapLocal; public UpdateSymLinks(String directory, SymLinkMap symLinkMap) { dirToSearch = directory; symLinkMapLocal = symLinkMap; setPriority(Thread.MIN_PRIORITY); } public void run() { // Bail out if Windows if(UtilB.OSNAME.startsWith("Windows")) return; symLinkMapLocal.checkForSymLinks(dirToSearch); } }
package tlc2.tool.distributed; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.URI; import java.net.UnknownHostException; import java.rmi.ConnectException; import java.rmi.Naming; import java.rmi.NoSuchObjectException; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.Date; import java.util.Timer; import tlc2.TLCGlobals; import tlc2.output.EC; import tlc2.output.MP; import tlc2.tool.TLCState; import tlc2.tool.TLCStateVec; import tlc2.tool.WorkerException; import tlc2.tool.distributed.fp.IFPSetManager; import tlc2.util.BitVector; import tlc2.util.FP64; import tlc2.util.LongVec; import util.ToolIO; import util.UniqueString; /** * @version $Id$ */ @SuppressWarnings("serial") public class TLCWorker extends UnicastRemoteObject implements TLCWorkerRMI { private static Timer keepAliveTimer; private static RMIFilenameToStreamResolver fts; private static TLCWorkerRunnable[] runnables = new TLCWorkerRunnable[0]; private DistApp work; private IFPSetManager fpSetManager; private final URI uri; private long lastInvocation; private final long mask; public TLCWorker(DistApp work, IFPSetManager fpSetManager, String aHostname) throws RemoteException { this.work = work; this.fpSetManager = fpSetManager; this.mask = fpSetManager.getMask(); uri = URI.create("rmi://" + aHostname + ":" + getPort()); } /* (non-Javadoc) * @see tlc2.tool.distributed.TLCWorkerRMI#getNextStates(tlc2.tool.TLCState[]) */ public synchronized Object[] getNextStates(final TLCState[] states) throws WorkerException, RemoteException { // statistics lastInvocation = System.currentTimeMillis(); // create containers for each fingerprint _server_ TLCState state1 = null, state2 = null; int fpServerCnt = this.fpSetManager.numOfServers(); // previous state TLCStateVec[] pvv = new TLCStateVec[fpServerCnt]; // container for all succ states TLCStateVec[] nvv = new TLCStateVec[fpServerCnt]; // container for all succ state fingerprints final LongVec[] fpvv = new LongVec[fpServerCnt]; for (int i = 0; i < fpServerCnt; i++) { pvv[i] = new TLCStateVec(); nvv[i] = new TLCStateVec(); fpvv[i] = new LongVec(); } try { // Compute all of the next states of this block of states. for (int i = 0; i < states.length; i++) { state1 = states[i]; TLCState[] nstates = this.work.getNextStates(state1); // add all succ states/fps to the array designated for the corresponding fp server for (int j = 0; j < nstates.length; j++) { long fp = nstates[j].fingerPrint(); int fpIndex = (int) ((fp & mask) % fpServerCnt); pvv[fpIndex].addElement(state1); nvv[fpIndex].addElement(nstates[j]); fpvv[fpIndex].addElement(fp); } } BitVector[] visited = this.fpSetManager.containsBlock(fpvv); // Remove the states that have already been seen, check if the // remaining new states are valid and inModel. TLCStateVec[] newStates = new TLCStateVec[fpServerCnt]; LongVec[] newFps = new LongVec[fpServerCnt]; for (int i = 0; i < fpServerCnt; i++) { newStates[i] = new TLCStateVec(); newFps[i] = new LongVec(); } for (int i = 0; i < fpServerCnt; i++) { BitVector.Iter iter = new BitVector.Iter(visited[i]); int index; while ((index = iter.next()) != -1) { state1 = pvv[i].elementAt(index); state2 = nvv[i].elementAt(index); this.work.checkState(state1, state2); if (this.work.isInModel(state2) && this.work.isInActions(state1, state2)) { state2.uid = state1.uid; newStates[i].addElement(state2); newFps[i].addElement(fpvv[i].elementAt(index)); } } } // Prepare the return value. Object[] res = new Object[3]; res[0] = newStates; res[1] = newFps; res[2] = System.currentTimeMillis() - lastInvocation; return res; } catch (WorkerException e) { throw e; } catch (OutOfMemoryError e) { throw new RemoteException("OutOfMemoryError occurred at worker: " + uri.toASCIIString(), e); } catch (Throwable e) { throw new WorkerException(e.getMessage(), e, state1, state2, true); } } /* (non-Javadoc) * @see tlc2.tool.distributed.TLCWorkerRMI#exit() */ public void exit() throws NoSuchObjectException { ToolIO.out.println(uri.getHost() + ", work completed at: " + new Date() + " Computed: " + this.work.getStatesComputed() + " Thank you!"); UnicastRemoteObject.unexportObject(TLCWorker.this, true); } /* (non-Javadoc) * @see tlc2.tool.distributed.TLCWorkerRMI#getStatesComputed() */ public long getStatesComputed() throws RemoteException { return this.work.getStatesComputed(); } /* (non-Javadoc) * @see tlc2.tool.distributed.TLCWorkerRMI#isAlive() */ public boolean isAlive() { return true; } /* (non-Javadoc) * @see tlc2.tool.distributed.TLCWorkerRMI#getURI() */ public URI getURI() throws RemoteException { return uri; } private int getPort() { try { // this only works on >= Sun Java 1.6 // sun.rmi.transport.LiveRef liveRef = ((UnicastRef) ref).getLiveRef(); // return liveRef.getPort(); // load the SUN class if available ClassLoader cl = ClassLoader.getSystemClassLoader(); Class<?> unicastRefClass = cl.loadClass("sun.rmi.server.UnicastRef"); // get the LiveRef obj Method method = unicastRefClass.getMethod( "getLiveRef", (Class[]) null); Object liveRef = method.invoke(getRef(), (Object[]) null); // Load liveref class Class<?> liveRefClass = cl.loadClass("sun.rmi.transport.LiveRef"); // invoke getPort on LiveRef instance method = liveRefClass.getMethod( "getPort", (Class[]) null); return (Integer) method.invoke(liveRef, (Object[]) null); } catch (SecurityException e) { MP.printError(EC.GENERAL, "trying to get a port for a worker", e); // LL changed call on 7 April 2012 } catch (IllegalArgumentException e) { MP.printError(EC.GENERAL, "trying to get a port for a worker",e); // LL changed call on 7 April 2012 } catch (ClassCastException e) { MP.printError(EC.GENERAL, "trying to get a port for a worker",e); // LL changed call on 7 April 2012 } catch (NoSuchMethodException e) { MP.printError(EC.TLC_DISTRIBUTED_VM_VERSION, e); } catch (IllegalAccessException e) { MP.printError(EC.TLC_DISTRIBUTED_VM_VERSION, e); } catch (InvocationTargetException e) { MP.printError(EC.TLC_DISTRIBUTED_VM_VERSION, e); } catch (ClassNotFoundException e) { MP.printError(EC.TLC_DISTRIBUTED_VM_VERSION, e); } return 0; } public long getLastInvocation() { return lastInvocation; } public static void main(String args[]) { ToolIO.out.println("TLC Worker " + TLCGlobals.versionOfTLC); // Must have exactly one arg: a hostname (spec is read from the server // connecting to). if(args.length != 1) { printErrorMsg("Error: Missing hostname of the TLC server to be contacted."); return; } final String serverName = args[0]; try { String url = "//" + serverName + ":" + TLCServer.Port + "/TLCServer"; // try to repeatedly connect to the server until it becomes available int i = 1; TLCServerRMI server = null; while(true) { try { server = (TLCServerRMI) Naming.lookup(url); break; } catch (ConnectException e) { // if the cause if a java.NET.ConnectException the server is // simply not ready yet final Throwable cause = e.getCause(); if(cause instanceof java.net.ConnectException) { long sleep = (long) Math.sqrt(i); ToolIO.out.println("Server " + serverName + " unreachable, sleeping " + sleep + "s for server to come online..."); Thread.sleep(sleep * 1000); i *= 2; } else { // some other exception occurred which we do not know // how to handle throw e; } } } long irredPoly = server.getIrredPolyForFP(); FP64.Init(irredPoly); // this call has to be made before the first UniqueString gets // created! Otherwise workers and server end up creating different // unique strings for the same String value. UniqueString.setSource((InternRMI)server); if (fts == null) { fts = new RMIFilenameToStreamResolver(); } fts.setTLCServer(server); DistApp work = new TLCApp(server.getSpecFileName(), server.getConfigFileName(), server.getCheckDeadlock(), server.getPreprocess(), fts, 0); final IFPSetManager fpSetManager = server.getFPSetManager(); // spawn as many worker threads as we have cores final int numCores = Runtime.getRuntime().availableProcessors(); runnables = new TLCWorkerRunnable[numCores]; for (int j = 0; j < numCores; j++) { runnables[j] = new TLCWorkerRunnable(server, fpSetManager, work); Thread t = new Thread(runnables[j], "TLCWorkerRunnable t.start(); } // schedule a timer to periodically (60s) check server aliveness keepAliveTimer = new Timer("TLCWorker KeepAlive Timer", true); keepAliveTimer.schedule(new TLCTimerTask(runnables, url), 10000, 60000); ToolIO.out.println("TLC worker ready at: " + new Date()); } catch (Throwable e) { // Assert.printStack(e); MP.printError(EC.GENERAL, e); ToolIO.out.println("Error: Failed to start worker " + " for server " + serverName + ".\n" + e.getMessage()); } ToolIO.out.flush(); } private static void printErrorMsg(String msg) { ToolIO.out.println(msg); ToolIO.out .println("Usage: java " + TLCWorker.class.getName() + " host"); } public static void setFilenameToStreamResolver(RMIFilenameToStreamResolver aFTS) { fts = aFTS; } /** * Terminates all {@link TLCWorker}s currently running concurrently by * gracefully unregistering with RMI. Additionally it terminates each * keep-alive timer. */ public static void shutdown() throws NoSuchObjectException { // Exit the keepAliveTimer if (keepAliveTimer != null) { keepAliveTimer.cancel(); } // Exit and unregister all worker threads for (int i = 0; i < runnables.length; i++) { TLCWorker worker = runnables[i].getTLCWorker(); worker.exit(); } fts = null; runnables = new TLCWorkerRunnable[0]; } public static class TLCWorkerRunnable implements Runnable { private final TLCServerRMI aServer; private final IFPSetManager anFpSetManager; private final DistApp aWork; private TLCWorker worker; public TLCWorkerRunnable(TLCServerRMI aServer, IFPSetManager anFpSetManager, DistApp aWork) { this.aServer = aServer; this.anFpSetManager = anFpSetManager; this.aWork = aWork; } /* (non-Javadoc) * @see java.lang.Runnable#run() */ public void run() { try { worker = new TLCWorker(aWork, anFpSetManager, InetAddress.getLocalHost().getCanonicalHostName()); aServer.registerWorker(worker); } catch (RemoteException e) { throw new RuntimeException(e); } catch (UnknownHostException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } public TLCWorker getTLCWorker() { return worker; } } }
package controllers; import static org.fest.assertions.Assertions.assertThat; import static play.mvc.Http.Status.*; import static play.test.Helpers.status; import org.junit.Test; import play.mvc.Result; import test.IntegrationTest; public class CommentControllerTest extends IntegrationTest { @Test public void testDelete() { Result result; result = getInstance(CommentController.class).delete(-11L, -111L); assertThat(status(result)).isEqualTo(SEE_OTHER); result = getInstance(CommentController.class).delete(-11L, 42L); assertThat(status(result)).isEqualTo(NOT_FOUND); } @Test public void testEditForm() { Result result; result = getInstance(CommentController.class).editForm(-11L, -111L); assertThat(status(result)).isEqualTo(NOT_FOUND); login("testuser"); result = getInstance(CommentController.class).editForm(-11L, -111L); assertThat(status(result)).isEqualTo(OK); } /*/
package lexical; import java.util.*; import data.Instruction; import data.Kind; import data.Result; import datastructures.BasicBlock; import datastructures.ControlFlowGraph; import datastructures.Function; public class Parser { private List<Token> tokenList; private Function main; private List<Function> functions; private int currentIndex; private Token currentToken; private HashMap<String, ArrayList<String>> herp; private String[] predefined = { "InputNum" , "OutputNum", "OutputNewLine" }; public static void main(String[] args){ if( args.length < 1){ System.out.println("Error. No file given."); System.exit(1); } Tokenizer t = new Tokenizer(); t.tokenize(args[0]); List<Parser> parsers = new ArrayList<Parser>(); Parser p = new Parser(t.getTokenList()); p.computation(); } /* * Constructor for Parser class */ public Parser(List<Token> tokenList){ this.tokenList = tokenList; this.main = new Function("main"); this.currentIndex = 0; this.currentToken = tokenList.get(0); } /* * This function is what is used to iterate through our tokenList obtained from file. */ public void nextToken(){ this.currentIndex++; if (currentIndex < tokenList.size()){ this.currentToken = this.tokenList.get(this.currentIndex); } else { System.out.println("Error. Went over file boundary!"); System.exit(2); } } /* * Now begins our recursive descent tree. We start at the top with computation * and work our way down. We already identified identifiers and numbers from * the project specification for the tree, so no need to analyze their digits and * letters again. We break this into blocks of the analysis. */ public void computation(){ if (currentToken.getTokenType() != TokenTypes.mainToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); //variable declarations if they exist if ( currentToken.getTokenType() == TokenTypes.varToken ||currentToken.getTokenType() == TokenTypes.arrToken){ while (currentToken.getTokenType() == TokenTypes.varToken || currentToken.getTokenType() == TokenTypes.arrToken){ varDecl(); } } //function declarations if they exist if ( currentToken.getTokenType() == TokenTypes.funcToken || currentToken.getTokenType() == TokenTypes.procToken){ while (currentToken.getTokenType() == TokenTypes.funcToken || currentToken.getTokenType() == TokenTypes.procToken){ funcDecl(); } } if (currentToken.getTokenType() != TokenTypes.beginToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); //Assuming mandatory statSequence(); if (currentToken.getTokenType() != TokenTypes.endToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); if (currentToken.getTokenType() != TokenTypes.periodToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } System.out.println("Compiled successfully."); //DONE } //stage 2 public void funcBody(Function scope){ if (currentToken.getTokenType() == TokenTypes.varToken || currentToken.getTokenType() == TokenTypes.arrToken){ varDecl(scope); } //function body if (currentToken.getTokenType() != TokenTypes.beginToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); if (currentToken.getTokenType() == TokenTypes.letToken || currentToken.getTokenType() == TokenTypes.callToken || currentToken.getTokenType() == TokenTypes.ifToken || currentToken.getTokenType() == TokenTypes.whileToken || currentToken.getTokenType() == TokenTypes.returnToken){ statSequence(scope); } if (currentToken.getTokenType() != TokenTypes.endToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); } public void formalParam(Function scope){ nextToken(); if (currentToken.getTokenType() == TokenTypes.ident){ nextToken(); if (currentToken.getTokenType() == TokenTypes.commaToken){ while (currentToken.getTokenType() == TokenTypes.commaToken){ nextToken(); if (currentToken.getTokenType() != TokenTypes.ident){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); } } } if (currentToken.getTokenType() != TokenTypes.closeparenToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); //Done } public void funcDecl(){ nextToken(); Parser functionParser = new Parser(); functionParser.setName("") functionParser.subComputation(); addToParsers(functionParser); if (currentToken.getTokenType() != TokenTypes.ident){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } Function scope = new Function(currentToken.getTokenString()); //Declare new function with ident name nextToken(); if (currentToken.getTokenType() == TokenTypes.openparenToken){ formalParam(scope); } if (currentToken.getTokenType() != TokenTypes.semiToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); funcBody(scope); if (currentToken.getTokenType() != TokenTypes.semiToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); //done } public Result varDecl(Function scope){ typeDecl(); if (currentToken.getTokenType() != TokenTypes.ident){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); if (currentToken.getTokenType() == TokenTypes.commaToken){ while (currentToken.getTokenType() == TokenTypes.commaToken){ nextToken(); if (currentToken.getTokenType() != TokenTypes.ident){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); } } if (currentToken.getTokenType() != TokenTypes.semiToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); //done return null; } public void typeDecl(Function scope){ if (currentToken.getTokenType() == TokenTypes.varToken){ nextToken(); return; //VAR declaration, done } nextToken(); if (currentToken.getTokenType() != TokenTypes.openbracketToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } while (currentToken.getTokenType() == TokenTypes.openbracketToken){ nextToken(); if (currentToken.getTokenType() != TokenTypes.number){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); if (currentToken.getTokenType() != TokenTypes.closebracketToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); //done } } //stage 3 /* * statSequence = statement { ";" statement } */ public Result statSequence(Function scope){ Result x = null; ControlFlowGraph cfg = scope.getCFG(); scope.getCFG().getNextBlock(); if (currentToken.getTokenType() == TokenTypes.letToken || currentToken.getTokenType() == TokenTypes.callToken || currentToken.getTokenType() == TokenTypes.returnToken || currentToken.getTokenType() == TokenTypes.whileToken || currentToken.getTokenType() == TokenTypes.ifToken){ x = statement(scope); } else { System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } while (currentToken.getTokenType() == TokenTypes.semiToken){ nextToken(); if (currentToken.getTokenType() == TokenTypes.letToken || currentToken.getTokenType() == TokenTypes.callToken || currentToken.getTokenType() == TokenTypes.returnToken || currentToken.getTokenType() == TokenTypes.whileToken || currentToken.getTokenType() == TokenTypes.ifToken){ x = statement(scope); } else { System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } } return x; } /* * state = assignment | funcCall | ifStatement | whileStatement | returnStatement */ public Result statement(Function scope){ Result statement; switch(currentToken.getTokenType()){ case letToken: statement = assignment(scope); //Create instruction here //Then add instruction to next block break; case callToken: statement = funcCall(scope); //Create instruction here //Then add instruction to next block break; case ifToken: statement = ifStatement(scope); //Create instructions for ifStatement and global instruction list //Then add instructions to next block and global instruction list break; case whileToken: statement = whileStatement(scope); //Create instructions for whileLoop and global instruction list //Then add instructions to next block and global instruction list break; case returnToken: statement = returnStatement(scope); //Create instruction here //Then add instruction to next block break; default: System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } //done return statement; } //state 4 /* * returnStatement = "return" [ expression ] */ public Result returnStatement(Function scope){ Node returnNode = null; returnNode = new Node(currentToken); nextToken(); if (currentToken.getTokenType() == TokenTypes.ident || currentToken.getTokenType() == TokenTypes.number || currentToken.getTokenType() == TokenTypes.openparenToken || currentToken.getTokenType() == TokenTypes.callToken){ Node expression = expression(scope); returnNode.setLeftNode(expression); } else { System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } return returnNode; } public Result whileStatement(Function scope){ nextToken(); relation(); if (currentToken.getTokenType() != TokenTypes.doToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); statSequence(); if (currentToken.getTokenType() != TokenTypes.odToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); //done } public Result ifStatement(Function scope){ nextToken(); relation(); if (currentToken.getTokenType() != TokenTypes.thenToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); statSequence(); if (currentToken.getTokenType() == TokenTypes.elseToken){ nextToken(); statSequence(); } if (currentToken.getTokenType() != TokenTypes.fiToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); //done } public Result funcCall(Function scope){ nextToken(); if (currentToken.getTokenType() != TokenTypes.ident){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); if (currentToken.getTokenType() == TokenTypes.openparenToken){ nextToken(); if (currentToken.getTokenType() == TokenTypes.number || currentToken.getTokenType() == TokenTypes.openparenToken || currentToken.getTokenType() == TokenTypes.callToken || currentToken.getTokenType() == TokenTypes.ident){ expression(); //Multiple arguments if (currentToken.getTokenType() == TokenTypes.commaToken){ while (currentToken.getTokenType() == TokenTypes.commaToken){ nextToken(); expression(); } } } if (currentToken.getTokenType() != TokenTypes.closeparenToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); } //done } /* * "let" designator "<-" expression */ public Node assignment(Function scope){ nextToken(); Result left = designator(scope); if (currentToken.getTokenType() != TokenTypes.becomesToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); Result right = expression(scope); //TODO: something regarding scope here return assignmentNode; } //stage 5 /* * relation = expression relOp expression */ public Result relation(Function scope){ Result relation; relation = expression(scope); relation.setKind(Kind.RELATION); if (currentToken.getTokenType() == TokenTypes.eqlToken || currentToken.getTokenType() == TokenTypes.leqToken || currentToken.getTokenType() == TokenTypes.lssToken || currentToken.getTokenType() == TokenTypes.gtrToken || currentToken.getTokenType() == TokenTypes.geqToken || currentToken.getTokenType() == TokenTypes.neqToken){ //if it's a relation operator relation = new Node(currentToken); nextToken(); Node rightExp = expression(scope); relation.setLeftNode(leftExp); relation.setRightNode(rightExp); } else { System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } //done return relation; } /* * expression = term { ("+" | "-") term } */ public Result expression(Function scope){ Result x, y; x = term(scope); if (currentToken.getTokenType() == TokenTypes.plusToken || currentToken.getTokenType() == TokenTypes.minusToken){ TokenTypes op = currentToken.getTokenType(); nextToken(); y = expression(scope); x = combine(x, y, op); } //end return x; } /* * term = factor { ("*" | "/") factor } */ public Result term(Function scope){ Result x, y; x = factor(scope); if (currentToken.getTokenType() == TokenTypes.timesToken || currentToken.getTokenType() == TokenTypes.divToken){ TokenTypes op = currentToken.getTokenType(); nextToken(); y = term(scope); x = combine(x, y, op); } //end return x; } /* * factor = designator | number | "(" expression ")" | funcCall */ public Result factor(Function scope){ Result factor = null; if (currentToken.getTokenType() == TokenTypes.ident) factor = designator(scope); else if (currentToken.getTokenType() == TokenTypes.number){ factor = new Result(Kind.CONSTANT); factor.setConstVal(Integer.parseInt(currentToken.getTokenString())); nextToken(); } else if (currentToken.getTokenType() == TokenTypes.callToken) factor = funcCall(scope); else if (currentToken.getTokenType() == TokenTypes.openparenToken){ nextToken(); factor = expression(scope); if (currentToken.getTokenType() != TokenTypes.closeparenToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); } else { System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } return factor; } /* * designator = ident{ "[" expression "]" } */ public Result designator(Function scope){ Result designator; if (currentToken.getTokenType() != TokenTypes.ident){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } designator = new Result(Kind.VAR); if (true){ /* CHECK IF IDENTIFIER IS IN SCOPE */ } nextToken(); if (currentToken.getTokenType() == TokenTypes.openbracketToken) designator.setKind(Kind.ARRAY); while (currentToken.getTokenType() == TokenTypes.openbracketToken){ nextToken(); Result y = expression(scope); designator.appendArrayDimension(y.getConstVal()); if (currentToken.getTokenType() != TokenTypes.closebracketToken){ System.err.println(new Throwable().getStackTrace()[0].getLineNumber());System.exit(3); } nextToken(); } //TODO: SCOPE WORK ON THIS PART return designator; } /* * Combining results is useful for terms and expressions */ public Result combine(Result x, Result y, TokenTypes operation){ Result combine = new Result(Kind.CONSTANT); switch (operation){ case timesToken: case divToken: case plusToken: case minusToken: default: System.out.println("Incorrect operation."); System.exit(0); } return combine; } }
package tlc2.tool.liveness; import tlc2.tool.TLCState; import tlc2.tool.Tool; /** * LNConj - a conjunction. (contains list of conjuncts) LNDisj - a disjunction. * (contains list of disjuncts) LNAll - Allways: []e LNEven - Eventually: <>e * LNNeg - Negation: -e LNState - State predicate. Concrete types: LNStateAST, * LNStateEnabled LNAction - Transition predicate. LNNext - next. ()e. Only used * for tableau construction. Not part of TLA * * LNState and LNAction have tags. When constructing the tableau, we will have * to check whether two primitives are equal to each other, to distinguish * atoms. We could do it just by checking the object pointers to the Act and * State ASTNodes. But to make it absolutely explicit, I will use integer tags. * These are initialized to distinct values immediately before tableau * construction, used during tableau construction, and not used any more. * * There's a little bit of a hierarchy for the LNState. That's because * LNStateAST (which has just an ASTNode for the state predicate) must be * evaluated differently from LNStateEnabled (which has ENABLED ast in it) * * We are going to end up evaluating LNState and LNAction when we come to * construct the tableau graph. That's for the EAs, the EAs, and for local * consistency. Therefore LNState and LNAction have appropriate eval functions. **/ public abstract class LiveExprNode { /** * getLevel() = 0 --> constant getLevel() = 1 --> state expression * getLevel() = 2 --> action expression getLevel() = 3 --> temporal * expression */ public abstract int getLevel(); /* Returns true iff the expression contains action. */ public abstract boolean containAction(); /** * @param s1 First state * @param s2 Second (successor) state * @param tool (Technical Tool implementation) * @return true iff both states are consistent with this {@link LiveExprNode}. */ public abstract boolean eval(Tool tool, TLCState s1, TLCState s2); /* The string representation. */ public final String toString() { StringBuffer sb = new StringBuffer(); this.toString(sb, ""); return sb.toString(); } public abstract void toString(StringBuffer sb, String padding); /** * This method returns true or false for whether two LiveExprNodes are * syntactically equal. */ public abstract boolean equals(LiveExprNode exp); /* Return A if this expression is of form []<>A. */ public LiveExprNode getAEBody() { return null; } /* Return A if this expression is of form <>[]A. */ public LiveExprNode getEABody() { return null; } /** * Return true if this expression is a general temporal formula containing * no []<>A or <>[]A. */ public boolean isGeneralTF() { return true; } /* This method pushes a negation all the way down to the atoms. */ public LiveExprNode pushNeg() { // for the remaining types, simply negate: return new LNNeg(this); } /** * This method pushes a negation all the way down to the atoms. It is * currently not used. */ public LiveExprNode pushNeg(boolean hasNeg) { if (hasNeg) { return new LNNeg(this); } return this; } /** * The method simplify does some simple simplifications before starting any * real work. It will get rid of any boolean constants (of type LNBool). */ public LiveExprNode simplify() { // for the remaining types, simply negate: return this; } /** * The method toDNF turns a LiveExprNode into disjunctive normal form. */ public LiveExprNode toDNF() { // For the remaining types, there is nothing to do: return this; } /** * This method eliminates (flattens) singleton conjunctions and * disjunctions. For example, /\[single-thing] is rewritten to single-thing. * Note: With the current version of toDNF, there is probably no need for * calling this method. */ public LiveExprNode flattenSingleJunctions() { // Finally, for the remaining types, there is nothing to do: return this; } /** * This method makes all conjunctions and disjunctions binary. This is for * tableau 'triple' construction. We'll do a recursive thing to balance the * binary trees. Note that there can be no LNActions. */ public LiveExprNode makeBinary() { return this; } /** * TagExpr tags all Act and State subexpressions in an expression. It * returns the maximum tag used so that the caller can proceed with other * tags in its depth-first traversal. */ public int tagExpr(int tag) { return tag; } /** * The method extractPromises, given a formula, returns all the promises in * its closure. All promises are in the form <>p. (We assume that we have * pushed all negations inside. So, there are no -[]ps.) The closure of a * formula says: for all subformulas of p, they are also in the closure. And * some other rules, none of which have the possibility of creating a * promise! So we only need look at subformulas of p. */ public void extractPromises(TBPar promises) { // Finally, for the remaining kinds, there is nothing to do. return; } public String toDotViz() { // By default just return the regular toString rep. return toString(); } }
package org.antlr.v4.semantics; import org.antlr.runtime.tree.CommonTree; import org.antlr.runtime.tree.Tree; import org.antlr.v4.automata.LexerATNFactory; import org.antlr.v4.parse.ANTLRLexer; import org.antlr.v4.parse.ANTLRParser; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.misc.IntervalSet; import org.antlr.v4.runtime.misc.MultiMap; import org.antlr.v4.tool.Alternative; import org.antlr.v4.tool.Attribute; import org.antlr.v4.tool.AttributeDict; import org.antlr.v4.tool.ErrorManager; import org.antlr.v4.tool.ErrorType; import org.antlr.v4.tool.Grammar; import org.antlr.v4.tool.LabelElementPair; import org.antlr.v4.tool.LabelType; import org.antlr.v4.tool.LeftRecursiveRule; import org.antlr.v4.tool.LexerGrammar; import org.antlr.v4.tool.Rule; import org.antlr.v4.tool.ast.AltAST; import org.antlr.v4.tool.ast.GrammarAST; import org.antlr.v4.tool.ast.TerminalAST; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** Check for symbol problems; no side-effects. Inefficient to walk rules * and such multiple times, but I like isolating all error checking outside * of code that actually defines symbols etc... * * Side-effect: strip away redef'd rules. */ public class SymbolChecks { Grammar g; SymbolCollector collector; Map<String, Rule> nameToRuleMap = new HashMap<String, Rule>(); Set<String> tokenIDs = new HashSet<String>(); Map<String, Set<String>> actionScopeToActionNames = new HashMap<String, Set<String>>(); public ErrorManager errMgr; protected final Set<String> reservedNames = new HashSet<String>(); { reservedNames.addAll(LexerATNFactory.getCommonConstants()); } public SymbolChecks(Grammar g, SymbolCollector collector) { this.g = g; this.collector = collector; this.errMgr = g.tool.errMgr; for (GrammarAST tokenId : collector.tokenIDRefs) { tokenIDs.add(tokenId.getText()); } } public void process() { // methods affect fields, but no side-effects outside this object // So, call order sensitive // First collect all rules for later use in checkForLabelConflict() if (g.rules != null) { for (Rule r : g.rules.values()) nameToRuleMap.put(r.name, r); } checkReservedNames(g.rules.values()); checkActionRedefinitions(collector.namedActions); checkForLabelConflicts(g.rules.values()); } public void checkActionRedefinitions(List<GrammarAST> actions) { if (actions == null) return; String scope = g.getDefaultActionScope(); String name; GrammarAST nameNode; for (GrammarAST ampersandAST : actions) { nameNode = (GrammarAST) ampersandAST.getChild(0); if (ampersandAST.getChildCount() == 2) { name = nameNode.getText(); } else { scope = nameNode.getText(); name = ampersandAST.getChild(1).getText(); } Set<String> scopeActions = actionScopeToActionNames.get(scope); if (scopeActions == null) { // init scope scopeActions = new HashSet<String>(); actionScopeToActionNames.put(scope, scopeActions); } if (!scopeActions.contains(name)) { scopeActions.add(name); } else { errMgr.grammarError(ErrorType.ACTION_REDEFINITION, g.fileName, nameNode.token, name); } } } /** * Make sure a label doesn't conflict with another symbol. * Labels must not conflict with: rules, tokens, scope names, * return values, parameters, and rule-scope dynamic attributes * defined in surrounding rule. Also they must have same type * for repeated defs. */ public void checkForLabelConflicts(Collection<Rule> rules) { for (Rule r : rules) { checkForAttributeConflicts(r); Map<String, LabelElementPair> labelNameSpace = new HashMap<>(); for (int i = 1; i <= r.numberOfAlts; i++) { Alternative a = r.alt[i]; for (List<LabelElementPair> pairs : a.labelDefs.values()) { if (r.hasAltSpecificContexts()) { // Collect labelName-labeledRules map for rule with alternative labels. Map<String, List<LabelElementPair>> labelPairs = new HashMap<>(); for (LabelElementPair p : pairs) { String labelName = findAltLabelName(p.label); if (labelName != null) { List<LabelElementPair> list; if (labelPairs.containsKey(labelName)) { list = labelPairs.get(labelName); } else { list = new ArrayList<>(); labelPairs.put(labelName, list); } list.add(p); } } for (List<LabelElementPair> internalPairs : labelPairs.values()) { labelNameSpace.clear(); checkLabelPairs(r, labelNameSpace, internalPairs); } } else { checkLabelPairs(r, labelNameSpace, pairs); } } } } } private void checkLabelPairs(Rule r, Map<String, LabelElementPair> labelNameSpace, List<LabelElementPair> pairs) { for (LabelElementPair p : pairs) { checkForLabelConflict(r, p.label); String name = p.label.getText(); LabelElementPair prev = labelNameSpace.get(name); if (prev == null) { labelNameSpace.put(name, p); } else { checkForTypeMismatch(r, prev, p); } } } private String findAltLabelName(CommonTree label) { if (label == null) { return null; } else if (label instanceof AltAST) { AltAST altAST = (AltAST) label; if (altAST.altLabel != null) { return altAST.altLabel.toString(); } else if (altAST.leftRecursiveAltInfo != null) { return altAST.leftRecursiveAltInfo.altLabel.toString(); } else { return findAltLabelName(label.parent); } } else { return findAltLabelName(label.parent); } } private void checkForTypeMismatch(Rule r, LabelElementPair prevLabelPair, LabelElementPair labelPair) { // label already defined; if same type, no problem if (prevLabelPair.type != labelPair.type) { // Current behavior: take a token of rule declaration in case of left-recursive rule // Desired behavior: take a token of proper label declaration in case of left-recursive rule // Such behavior is referring to the fact that the warning is typically reported on the actual label redefinition, // but for left-recursive rules the warning is reported on the enclosing rule. org.antlr.runtime.Token token = r instanceof LeftRecursiveRule ? ((GrammarAST) r.ast.getChild(0)).getToken() : labelPair.label.token; errMgr.grammarError( ErrorType.LABEL_TYPE_CONFLICT, g.fileName, token, labelPair.label.getText(), labelPair.type + "!=" + prevLabelPair.type); } if (!prevLabelPair.element.getText().equals(labelPair.element.getText()) && (prevLabelPair.type.equals(LabelType.RULE_LABEL) || prevLabelPair.type.equals(LabelType.RULE_LIST_LABEL)) && (labelPair.type.equals(LabelType.RULE_LABEL) || labelPair.type.equals(LabelType.RULE_LIST_LABEL))) { org.antlr.runtime.Token token = r instanceof LeftRecursiveRule ? ((GrammarAST) r.ast.getChild(0)).getToken() : labelPair.label.token; String prevLabelOp = prevLabelPair.type.equals(LabelType.RULE_LIST_LABEL) ? "+=" : "="; String labelOp = labelPair.type.equals(LabelType.RULE_LIST_LABEL) ? "+=" : "="; errMgr.grammarError( ErrorType.LABEL_TYPE_CONFLICT, g.fileName, token, labelPair.label.getText() + labelOp + labelPair.element.getText(), prevLabelPair.label.getText() + prevLabelOp + prevLabelPair.element.getText()); } } public void checkForLabelConflict(Rule r, GrammarAST labelID) { String name = labelID.getText(); if (nameToRuleMap.containsKey(name)) { ErrorType etype = ErrorType.LABEL_CONFLICTS_WITH_RULE; errMgr.grammarError(etype, g.fileName, labelID.token, name, r.name); } if (tokenIDs.contains(name)) { ErrorType etype = ErrorType.LABEL_CONFLICTS_WITH_TOKEN; errMgr.grammarError(etype, g.fileName, labelID.token, name, r.name); } if (r.args != null && r.args.get(name) != null) { ErrorType etype = ErrorType.LABEL_CONFLICTS_WITH_ARG; errMgr.grammarError(etype, g.fileName, labelID.token, name, r.name); } if (r.retvals != null && r.retvals.get(name) != null) { ErrorType etype = ErrorType.LABEL_CONFLICTS_WITH_RETVAL; errMgr.grammarError(etype, g.fileName, labelID.token, name, r.name); } if (r.locals != null && r.locals.get(name) != null) { ErrorType etype = ErrorType.LABEL_CONFLICTS_WITH_LOCAL; errMgr.grammarError(etype, g.fileName, labelID.token, name, r.name); } } public void checkForAttributeConflicts(Rule r) { checkDeclarationRuleConflicts(r, r.args, nameToRuleMap.keySet(), ErrorType.ARG_CONFLICTS_WITH_RULE); checkDeclarationRuleConflicts(r, r.args, tokenIDs, ErrorType.ARG_CONFLICTS_WITH_TOKEN); checkDeclarationRuleConflicts(r, r.retvals, nameToRuleMap.keySet(), ErrorType.RETVAL_CONFLICTS_WITH_RULE); checkDeclarationRuleConflicts(r, r.retvals, tokenIDs, ErrorType.RETVAL_CONFLICTS_WITH_TOKEN); checkDeclarationRuleConflicts(r, r.locals, nameToRuleMap.keySet(), ErrorType.LOCAL_CONFLICTS_WITH_RULE); checkDeclarationRuleConflicts(r, r.locals, tokenIDs, ErrorType.LOCAL_CONFLICTS_WITH_TOKEN); checkLocalConflictingDeclarations(r, r.retvals, r.args, ErrorType.RETVAL_CONFLICTS_WITH_ARG); checkLocalConflictingDeclarations(r, r.locals, r.args, ErrorType.LOCAL_CONFLICTS_WITH_ARG); checkLocalConflictingDeclarations(r, r.locals, r.retvals, ErrorType.LOCAL_CONFLICTS_WITH_RETVAL); } protected void checkDeclarationRuleConflicts(Rule r, AttributeDict attributes, Set<String> ruleNames, ErrorType errorType) { if (attributes == null) { return; } for (Attribute attribute : attributes.attributes.values()) { if (ruleNames.contains(attribute.name)) { errMgr.grammarError( errorType, g.fileName, attribute.token != null ? attribute.token : ((GrammarAST) r.ast.getChild(0)).token, attribute.name, r.name); } } } protected void checkLocalConflictingDeclarations(Rule r, AttributeDict attributes, AttributeDict referenceAttributes, ErrorType errorType) { if (attributes == null || referenceAttributes == null) { return; } Set<String> conflictingKeys = attributes.intersection(referenceAttributes); for (String key : conflictingKeys) { errMgr.grammarError( errorType, g.fileName, attributes.get(key).token != null ? attributes.get(key).token : ((GrammarAST) r.ast.getChild(0)).token, key, r.name); } } protected void checkReservedNames(Collection<Rule> rules) { for (Rule rule : rules) { if (reservedNames.contains(rule.name)) { errMgr.grammarError(ErrorType.RESERVED_RULE_NAME, g.fileName, ((GrammarAST) rule.ast.getChild(0)).getToken(), rule.name); } } } public void checkForModeConflicts(Grammar g) { if (g.isLexer()) { LexerGrammar lexerGrammar = (LexerGrammar) g; for (String modeName : lexerGrammar.modes.keySet()) { if (!modeName.equals("DEFAULT_MODE") && reservedNames.contains(modeName)) { Rule rule = lexerGrammar.modes.get(modeName).iterator().next(); g.tool.errMgr.grammarError(ErrorType.MODE_CONFLICTS_WITH_COMMON_CONSTANTS, g.fileName, rule.ast.parent.getToken(), modeName); } if (g.getTokenType(modeName) != Token.INVALID_TYPE) { Rule rule = lexerGrammar.modes.get(modeName).iterator().next(); g.tool.errMgr.grammarError(ErrorType.MODE_CONFLICTS_WITH_TOKEN, g.fileName, rule.ast.parent.getToken(), modeName); } } } } public void checkForUnreachableTokens(Grammar g) { if (g.isLexer()) { LexerGrammar lexerGrammar = (LexerGrammar) g; for (List<Rule> rules : lexerGrammar.modes.values()) { // Collect string literal lexer rules for each mode List<Rule> stringLiteralRules = new ArrayList<>(); List<List<String>> stringLiteralValues = new ArrayList<>(); for (int i = 0; i < rules.size(); i++) { Rule rule = rules.get(i); if (!rule.isFragment()) { List<String> ruleStringAlts = getSingleTokenValues(rule); if (ruleStringAlts != null && ruleStringAlts.size() > 0) { stringLiteralRules.add(rule); stringLiteralValues.add(ruleStringAlts); } } } // Check string sets intersection for (int i = 0; i < stringLiteralRules.size(); i++) { List<String> firstTokenStringValues = stringLiteralValues.get(i); Rule rule1 = stringLiteralRules.get(i); checkForOverlap(g, rule1, rule1, firstTokenStringValues, stringLiteralValues.get(i)); for (int j = i + 1; j < stringLiteralRules.size(); j++) { checkForOverlap(g, rule1, stringLiteralRules.get(j), firstTokenStringValues, stringLiteralValues.get(j)); } } } } } private void checkForOverlap(Grammar g, Rule rule1, Rule rule2, List<String> firstTokenStringValues, List<String> secondTokenStringValues) { for (int i = 0; i < firstTokenStringValues.size(); i++) { int secondTokenInd = rule1 == rule2 ? i + 1 : 0; // Compare with self or not String str1 = firstTokenStringValues.get(i); for (int j = secondTokenInd; j < secondTokenStringValues.size(); j++) { String str2 = secondTokenStringValues.get(j); if (str1.equals(str2)) { errMgr.grammarError(ErrorType.TOKEN_UNREACHABLE, g.fileName, ((GrammarAST) rule2.ast.getChild(0)).token, rule2.name, str2, rule1.name); } } } } public List<String> getSingleTokenValues(Rule rule) { List<String> values = new ArrayList<>(); for (Alternative alt : rule.alt) { if (alt != null) { // select first alt if token has a command Tree rootNode = alt.ast.getChildCount() == 2 && alt.ast.getChild(0) instanceof AltAST && alt.ast.getChild(1) instanceof GrammarAST ? alt.ast.getChild(0) : alt.ast; if (rootNode.getTokenStartIndex() == -1) { continue; // ignore tokens from parser that start as T__ } // Ignore alt if contains not only string literals (repetition, optional) boolean ignore = false; StringBuilder currentValue = new StringBuilder(); for (int i = 0; i < rootNode.getChildCount(); i++) { Tree child = rootNode.getChild(i); if (!(child instanceof TerminalAST)) { ignore = true; break; } TerminalAST terminalAST = (TerminalAST)child; if (terminalAST.token.getType() != ANTLRLexer.STRING_LITERAL) { ignore = true; break; } else { String text = terminalAST.token.getText(); currentValue.append(text.substring(1, text.length() - 1)); } } if (!ignore) { values.add(currentValue.toString()); } } } return values; } // CAN ONLY CALL THE TWO NEXT METHODS AFTER GRAMMAR HAS RULE DEFS (see semanticpipeline) public void checkRuleArgs(Grammar g, List<GrammarAST> rulerefs) { if (rulerefs == null) return; for (GrammarAST ref : rulerefs) { String ruleName = ref.getText(); Rule r = g.getRule(ruleName); GrammarAST arg = (GrammarAST) ref.getFirstChildWithType(ANTLRParser.ARG_ACTION); if (arg != null && (r == null || r.args == null)) { errMgr.grammarError(ErrorType.RULE_HAS_NO_ARGS, g.fileName, ref.token, ruleName); } else if (arg == null && (r != null && r.args != null)) { errMgr.grammarError(ErrorType.MISSING_RULE_ARGS, g.fileName, ref.token, ruleName); } } } public void checkForQualifiedRuleIssues(Grammar g, List<GrammarAST> qualifiedRuleRefs) { for (GrammarAST dot : qualifiedRuleRefs) { GrammarAST grammar = (GrammarAST) dot.getChild(0); GrammarAST rule = (GrammarAST) dot.getChild(1); g.tool.log("semantics", grammar.getText() + "." + rule.getText()); Grammar delegate = g.getImportedGrammar(grammar.getText()); if (delegate == null) { errMgr.grammarError(ErrorType.NO_SUCH_GRAMMAR_SCOPE, g.fileName, grammar.token, grammar.getText(), rule.getText()); } else { if (g.getRule(grammar.getText(), rule.getText()) == null) { errMgr.grammarError(ErrorType.NO_SUCH_RULE_IN_SCOPE, g.fileName, rule.token, grammar.getText(), rule.getText()); } } } } }
import drafts.com.sun.star.accessibility.XAccessible; import drafts.com.sun.star.accessibility.XAccessibleContext; import drafts.com.sun.star.accessibility.XAccessibleComponent; import drafts.com.sun.star.accessibility.XAccessibleExtendedComponent; import drafts.com.sun.star.accessibility.XAccessibleAction; import drafts.com.sun.star.accessibility.XAccessibleImage; import drafts.com.sun.star.accessibility.XAccessibleRelationSet; import drafts.com.sun.star.accessibility.XAccessibleStateSet; import drafts.com.sun.star.accessibility.XAccessibleText; import drafts.com.sun.star.accessibility.XAccessibleEditableText; import drafts.com.sun.star.accessibility.AccessibleTextType; import drafts.com.sun.star.accessibility.XAccessibleEventListener; import drafts.com.sun.star.accessibility.XAccessibleEventBroadcaster; import drafts.com.sun.star.accessibility.AccessibleEventObject; import drafts.com.sun.star.accessibility.AccessibleEventId; import com.sun.star.lang.XServiceInfo; import com.sun.star.lang.IndexOutOfBoundsException; import com.sun.star.uno.UnoRuntime; import java.util.Vector; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.tree.*; import javax.swing.event.*; // JDK 1.4. // import java.util.regex.Pattern; // import java.util.regex.Matcher; /** This class is a start to collect the handling of a JTree and a DefaultTreeModel. */ public class AccessibilityTree extends JTree implements TreeExpansionListener, TreeWillExpandListener { /** Create a new accessibility tree. Use the specified message display for displaying messages and the specified canvas to draw the graphical representations of accessible objects on. */ public AccessibilityTree ( MessageInterface aMessageDisplay, Print aPrinter) { maMessageDisplay = aMessageDisplay; maPrinter = aPrinter; AccessibilityTreeModel aModel = new AccessibilityTreeModel ( new StringNode ("Please press Update button", null), aMessageDisplay, aPrinter); setModel (aModel); maCellRenderer = new AccessibleTreeCellRenderer(); // setCellRenderer (maCellRenderer); // allow editing of XAccessibleText interfaces // setEditable (true); // maTreeModel.addTreeModelListener( new TextUpdateListener() ); addMouseListener (new MouseListener (this)); // Listen to expansions and collapses to change the mouse cursor. mnExpandLevel = 0; addTreeWillExpandListener (this); addTreeExpansionListener (this); } // Change cursor during expansions to show the user that this is a // lengthy operation. public void treeWillExpand (TreeExpansionEvent e) { if (mnExpandLevel == 0) { setCursor (new Cursor (Cursor.WAIT_CURSOR)); message ("expanding node "); } mnExpandLevel += 1; } public void treeWillCollapse (TreeExpansionEvent e) { if (mnExpandLevel == 0) { message ("collapsing node "); setCursor (new Cursor (Cursor.WAIT_CURSOR)); } mnExpandLevel += 1; } public void treeExpanded (TreeExpansionEvent e) { mnExpandLevel -= 1; if (mnExpandLevel == 0) { message (""); setCursor (new Cursor (Cursor.DEFAULT_CURSOR)); } } public void treeCollapsed (TreeExpansionEvent e) { mnExpandLevel -= 1; if (mnExpandLevel == 0) { message (""); setCursor (new Cursor (Cursor.DEFAULT_CURSOR)); } } public void SetCanvas (Canvas aCanvas) { maCanvas = aCanvas; ((AccessibilityTreeModel)getModel()).setCanvas (maCanvas); } /** Predicate class to determine whether a node should be expanded * For use with expandTree method */ abstract class Expander { abstract public boolean expand(Object aObject); } /** expand all nodes */ class AllExpander extends Expander { public boolean expand(Object aObject) { return true; } } /** expand all nodes with accessibility roles > 100 */ class ShapeExpander extends Expander { public boolean expand (Object aObject) { if (aObject instanceof AccTreeNode) { AccTreeNode aNode = (AccTreeNode)aObject; XAccessibleContext xContext = aNode.getContext(); if (xContext != null) if (xContext.getAccessibleRole() >= 100) return true; } return false; } } /** Expand the nodes in the subtree rooted in aNode according to the the specified expander. The tree is locked during the expansion. */ protected void expandTree (AccessibleTreeNode aNode, Expander aExpander) { if (mnExpandLevel == 0) { message ("Expanding tree"); setEnabled (false); } mnExpandLevel += 1; ((AccessibilityTreeModel)getModel()).lock (); try { expandTree (new TreePath (aNode.createPath()), aExpander); } catch (Exception e) { // Ignore } mnExpandLevel -= 1; if (mnExpandLevel == 0) { setEnabled (true); ((AccessibilityTreeModel)getModel()).unlock (aNode); message (""); } } private TreePath expandTree( TreePath aPath, Expander aExpander ) { // return first expanded object TreePath aFirst = null; // System.out.print ("e"); try { // get 'our' object Object aObj = aPath.getLastPathComponent(); // expand this object, if the Expander tells us so if( aExpander.expand( aObj ) ) { expandPath (aPath); if( aFirst == null ) aFirst = aPath; } // visit all children if (aObj instanceof AccessibleTreeNode) { AccessibleTreeNode aNode = (AccessibleTreeNode)aObj; int nLength = aNode.getChildCount(); for( int i = 0; i < nLength; i++ ) { TreePath aRet = expandTree( aPath.pathByAddingChild( aNode.getChild( i ) ), aExpander ); if( aFirst == null ) aFirst = aRet; } } } catch (Exception e) { System.out.println ("caught exception while expanding tree path " + aPath + ": " + e); e.printStackTrace (); } return aFirst; } /** Expand all nodes and their subtrees that represent shapes. Call * this method from the outside. */ public void expandShapes () { expandShapes ((AccessibleTreeNode)getModel().getRoot()); } public void expandShapes (AccessibleTreeNode aNode) { expandTree (aNode, new ShapeExpander()); } /** Expand all nodes */ public void expandAll () { expandAll ((AccessibleTreeNode)getModel().getRoot()); } public void expandAll (AccessibleTreeNode aNode) { expandTree (aNode, new AllExpander()); } protected void message (String message) { maMessageDisplay.message (message); } public void disposing (com.sun.star.lang.EventObject e) { System.out.println ("disposing " + e); } class MouseListener extends MouseAdapter { private AccessibilityTree maTree; public MouseListener (AccessibilityTree aTree) {maTree=aTree;} public void mousePressed(MouseEvent e) { popupTrigger(e); } public void mouseClicked(MouseEvent e) { popupTrigger(e); } public void mouseEntered(MouseEvent e) { popupTrigger(e); } public void mouseExited(MouseEvent e) { popupTrigger(e); } public void mouseReleased(MouseEvent e) { popupTrigger(e); } public boolean popupTrigger( MouseEvent e ) { boolean bIsPopup = e.isPopupTrigger(); if( bIsPopup ) { int selRow = getRowForLocation(e.getX(), e.getY()); if (selRow != -1) { TreePath aPath = getPathForLocation(e.getX(), e.getY()); // check for actions Object aObject = aPath.getLastPathComponent(); if( aObject instanceof AccTreeNode ) { AccTreeNode aNode = (AccTreeNode)aObject; JPopupMenu aMenu = new JPopupMenu(); Vector aActions = new Vector(); aMenu.add (new ShapeExpandAction(maTree, aNode)); aMenu.add (new SubtreeExpandAction(maTree, aNode)); aNode.getActions(aActions); for( int i = 0; i < aActions.size(); i++ ) { aMenu.add( new NodeAction( aActions.elementAt(i).toString(), aNode, i ) ); } aMenu.show( AccessibilityTree.this, e.getX(), e.getY() ); } else if (aObject instanceof AccessibleTreeNode) { AccessibleTreeNode aNode = (AccessibleTreeNode)aObject; String[] aActionNames = aNode.getActions(); int nCount=aActionNames.length; if (nCount > 0) { JPopupMenu aMenu = new JPopupMenu(); for (int i=0; i<nCount; i++) aMenu.add( new NodeAction( aActionNames[i], aNode, i)); aMenu.show (AccessibilityTree.this, e.getX(), e.getY()); } } } } return bIsPopup; } } class NodeAction extends AbstractAction { private int mnIndex; private AccessibleTreeNode maNode; public NodeAction( String aName, AccessibleTreeNode aNode, int nIndex ) { super( aName ); maNode = aNode; mnIndex = nIndex; } public void actionPerformed(ActionEvent e) { maNode.performAction(mnIndex); } } // This action expands all shapes in the subtree rooted in the specified node. class ShapeExpandAction extends AbstractAction { private AccessibilityTree maTree; private AccTreeNode maNode; public ShapeExpandAction (AccessibilityTree aTree, AccTreeNode aNode) { super ("Expand Shapes"); maTree = aTree; maNode = aNode; } public void actionPerformed (ActionEvent e) { maTree.expandShapes (maNode); } } // This action expands all nodes in the subtree rooted in the specified node. class SubtreeExpandAction extends AbstractAction { private AccessibilityTree maTree; private AccTreeNode maNode; public SubtreeExpandAction (AccessibilityTree aTree, AccTreeNode aNode) { super ("Expand Subtree"); maTree = aTree; maNode = aNode; } public void actionPerformed (ActionEvent e) { maTree.expandAll (maNode); } } /** listen to tree model changes in order to update XAccessibleText objects */ class TextUpdateListener implements TreeModelListener { public void treeNodesChanged(TreeModelEvent e) { // if the change is to the first child of a DefaultMutableTreeNode // with an XAccessibleText child, then we call updateText int[] aIndices = e.getChildIndices(); if( (aIndices != null) && (aIndices.length > 0) ) { // we have a parent... lets check for XAccessibleText then DefaultMutableTreeNode aParent = (DefaultMutableTreeNode) (e.getTreePath().getLastPathComponent()); DefaultMutableTreeNode aNode = (DefaultMutableTreeNode) (aParent.getChildAt(aIndices[0])); if( aParent.getUserObject() instanceof XAccessibleText) { // aha! we have an xText. So we can now check for // the various cases we support XAccessibleText xText = (XAccessibleText)aParent.getUserObject(); if( aIndices[0] == 0 ) { // first child! Then we call updateText updateText( xText, aNode.toString() ); } else { // JDK 1.4: // // check for pattern "Selection:" // Matcher m = Pattern.compile( // "selection: \\[(-?[0-9]+),(-?[0-9]+)\\] \".*" ). // matcher( aNode.toString() ); // if( m.matches() ) // try // // aha! Selection: // setSelection( xText, // Integer.parseInt(m.group(1)), // Integer.parseInt(m.group(2)) ); // catch( NumberFormatException f ) // // ignore } } } } // don't care: public void treeNodesInserted(TreeModelEvent e) { ; } public void treeNodesRemoved(TreeModelEvent e) { ; } public void treeStructureChanged(TreeModelEvent e) { ; } /** update the text */ boolean updateText( XAccessibleText xText, String sNew ) { // is this text editable? if not, fudge you and return XAccessibleEditableText xEdit = (XAccessibleEditableText) UnoRuntime.queryInterface ( XAccessibleEditableText.class, xText); if (xEdit == null) return false; String sOld = xText.getText(); // false alarm? Early out if no change was done! if( sOld.equals( sNew ) ) return false; // get the minimum length of both strings int nMinLength = sOld.length(); if( sNew.length() < nMinLength ) nMinLength = sNew.length(); // count equal characters from front and end int nFront = 0; while( (nFront < nMinLength) && (sNew.charAt(nFront) == sOld.charAt(nFront)) ) nFront++; int nBack = 0; while( (nBack < nMinLength) && ( sNew.charAt(sNew.length()-nBack-1) == sOld.charAt(sOld.length()-nBack-1) ) ) nBack++; if( nFront + nBack > nMinLength ) nBack = nMinLength - nFront; // so... the first nFront and the last nBack characters // are the same. Change the others! String sDel = sOld.substring( nFront, sOld.length() - nBack ); String sIns = sNew.substring( nFront, sNew.length() - nBack ); System.out.println("edit text: " + sOld.substring(0, nFront) + " [ " + sDel + " -> " + sIns + " ] " + sOld.substring(sOld.length() - nBack) ); boolean bRet = false; try { // edit the text, and use // (set|insert|delete|replace)Text as needed if( nFront+nBack == 0 ) bRet = xEdit.setText( sIns ); else if( sDel.length() == 0 ) bRet = xEdit.insertText( sIns, nFront ); else if( sIns.length() == 0 ) bRet = xEdit.deleteText( nFront, sOld.length()-nBack ); else bRet = xEdit.replaceText(nFront, sOld.length()-nBack,sIns); } catch( IndexOutOfBoundsException e ) { bRet = false; } return bRet; } boolean setSelection( XAccessibleText xText, int p1, int p2 ) { try { return xText.setSelection( p1, p2 ); } catch( com.sun.star.lang.IndexOutOfBoundsException f ) { return false; } } // /** replace the given node with a new xText node */ // void updateNode( XAccessibleText xText, // DefaultMutableTreeNode aNode ) // // create a new node // DefaultMutableTreeNode aNew = newTextTreeNode( xText ); // // get parent (must be DefaultMutableTreeNode) // DefaultMutableTreeNode aParent = // (DefaultMutableTreeNode)aNode.getParent(); // if( aParent != null ) // // remove old sub-tree, and insert new one // int nIndex = aParent.getIndex( aNode ); // aParent.remove( nIndex ); // aParent.insert( aNew, nIndex ); } protected MessageInterface maMessageDisplay; protected Print maPrinter; protected AccessibleTreeCellRenderer maCellRenderer; private Canvas maCanvas; private boolean mbFirstShapeSeen; private int mnExpandLevel; }
package com.developersguild.pewpew; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.PooledEngine; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.CircleShape; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; import com.developersguild.pewpew.components.AnimationComponent; import com.developersguild.pewpew.components.BackgroundComponent; import com.developersguild.pewpew.components.BodyComponent; import com.developersguild.pewpew.components.BoundsComponent; import com.developersguild.pewpew.components.CameraComponent; import com.developersguild.pewpew.components.HealthComponent; import com.developersguild.pewpew.components.MovementComponent; import com.developersguild.pewpew.components.PlayerComponent; import com.developersguild.pewpew.components.StateComponent; import com.developersguild.pewpew.components.StructureComponent; import com.developersguild.pewpew.components.TextureComponent; import com.developersguild.pewpew.components.TransformComponent; import com.developersguild.pewpew.systems.RenderingSystem; public class Level { public static final float WORLD_WIDTH = 10; public static final float WORLD_HEIGHT = 15 * 20; // I think the second number is the number of screens public static final int WORLD_STATE_RUNNING = 0; public float heightSoFar; public int state; public int score; private PooledEngine engine; public Level(PooledEngine engine) { this.engine = engine; } public void create(World world) { Entity player = createPlayer(world); createCamera(player); createBackground(); generateLevel(world); this.heightSoFar = 0; this.state = WORLD_STATE_RUNNING; this.score = 0; } private void generateLevel(World world) { // create obstacles createStructure(StructureComponent.SIZE_SMALL, 3.0f, 10.0f, world); // create enemies } private void createCamera(Entity target) { Entity entity = engine.createEntity(); CameraComponent camera = new CameraComponent(); camera.camera = engine.getSystem(RenderingSystem.class).getCamera(); camera.target = target; entity.add(camera); engine.addEntity(entity); } private Entity createPlayer(World world) { Entity entity = engine.createEntity(); AnimationComponent animation = engine.createComponent(AnimationComponent.class); BoundsComponent bounds = engine.createComponent(BoundsComponent.class); MovementComponent movement = engine.createComponent(MovementComponent.class); TransformComponent position = engine.createComponent(TransformComponent.class); PlayerComponent player = engine.createComponent(PlayerComponent.class); BodyComponent body = engine.createComponent(BodyComponent.class); StateComponent state = engine.createComponent(StateComponent.class); TextureComponent texture = engine.createComponent(TextureComponent.class); animation.animations.put(PlayerComponent.STATE_NORMAL, Assets.shipNormal); bounds.bounds.width = PlayerComponent.WIDTH; bounds.bounds.height = PlayerComponent.HEIGHT; position.pos.set(5.0f, 2.5f, 0.0f); position.scale.set(2.0f / 3.0f, 2.0f / 3.0f); // Create player body BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyDef.BodyType.DynamicBody; bodyDef.position.set(position.pos.x, position.pos.y); body.body = world.createBody(bodyDef); // Define a shape with the vertices PolygonShape polygon = new PolygonShape(); polygon.setAsBox(PlayerComponent.WIDTH / 2.f, PlayerComponent.HEIGHT / 2.f); // Create a fixture with the shape FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = polygon; fixtureDef.density = 0.5f; fixtureDef.friction = 0.4f; fixtureDef.restitution = 0.6f; // Assign shape to body body.body.createFixture(fixtureDef); // Clean up polygon.dispose(); state.set(PlayerComponent.STATE_NORMAL); entity.add(animation); entity.add(bounds); entity.add(movement); entity.add(position); entity.add(player); entity.add(body); entity.add(state); entity.add(texture); engine.addEntity(entity); createHealthBar(entity); return entity; } private void createHealthBar(Entity target) { Entity entity = engine.createEntity(); HealthComponent health = engine.createComponent(HealthComponent.class); TransformComponent position = engine.createComponent(TransformComponent.class); TextureComponent texture = engine.createComponent(TextureComponent.class); health.currentHealth = (int) (health.STARTING_HEALTH * health.healthMultiplier); health.target = target.getComponent(TransformComponent.class).pos; position.pos.set(target.getComponent(TransformComponent.class).pos); //position = target.getComponent(TransformComponent.class); texture.region = Assets.healthRegion; entity.add(health); entity.add(position); entity.add(texture); engine.addEntity(entity); } private void createStructure(int size, float x, float y, World world) { Entity entity = new Entity(); StructureComponent structure = engine.createComponent(StructureComponent.class); BoundsComponent bounds = engine.createComponent(BoundsComponent.class); TransformComponent position = engine.createComponent(TransformComponent.class); StateComponent state = engine.createComponent(StateComponent.class); TextureComponent texture = engine.createComponent(TextureComponent.class); BodyComponent body = engine.createComponent(BodyComponent.class); bounds.bounds.width = StructureComponent.WIDTH; bounds.bounds.height = StructureComponent.HEIGHT; position.pos.set(x, y, 1.0f); texture.region = Assets.roofRegion; state.set(StructureComponent.STATE_ALIVE); structure.size = size; if (size == StructureComponent.SIZE_SMALL) { // small structure } else { // large structure } // Create body BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyDef.BodyType.StaticBody; bodyDef.position.set(position.pos.x, position.pos.y); body.body = world.createBody(bodyDef); // Define a shape with the vertices PolygonShape polygon = new PolygonShape(); polygon.setAsBox(StructureComponent.WIDTH / 2.f, StructureComponent.HEIGHT / 2.f); // Assign shape to body body.body.createFixture(polygon, 0.0f); // Clean up polygon.dispose(); entity.add(structure); entity.add(bounds); entity.add(position); entity.add(state); entity.add(texture); entity.add(body); engine.addEntity(entity); } private void createBackground() { Entity entity = engine.createEntity(); BackgroundComponent background = engine.createComponent(BackgroundComponent.class); TransformComponent position = engine.createComponent(TransformComponent.class); TextureComponent texture = engine.createComponent(TextureComponent.class); texture.region = Assets.backgroundRegion; entity.add(background); entity.add(position); entity.add(texture); engine.addEntity(entity); } }
/* * $Id: RunKbartReport.java,v 1.12 2014-06-27 03:02:54 pgust Exp $ */ package org.lockss.devtools; import org.apache.commons.cli.*; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.lockss.exporter.biblio.BibliographicItem; import org.lockss.exporter.biblio.BibliographicItemImpl; import org.lockss.exporter.biblio.BibliographicUtil; import org.lockss.exporter.kbart.KbartConverter; import org.lockss.exporter.kbart.KbartExportFilter; import static org.lockss.exporter.kbart.KbartExportFilter.*; import org.lockss.exporter.kbart.KbartExporter; import org.lockss.exporter.kbart.KbartTitle; import org.lockss.exporter.kbart.KbartTitle.Field; import com.csvreader.CsvReader; import org.lockss.util.StringUtil; import java.io.*; import java.nio.charset.Charset; import java.util.*; /** * Reads holdings data from outside, and processes it into a KBART report. * The iteration over the input should probably be extracted to an external * class. * <p> * Uses the Apache Commons cli library, which has some quirks: * <ul> * <li>By default, it is not possible to display a usage message where the * options are in the order in which they are specified.</li> * <li>If any required option is missing, parsing fails and the CommandLine * object is null, preventing one from providing any useful feedback, and * rendering the use of a help (-h) option pointless.</li> * </ul> * This unfortunately leads to some messy options setup as seen below. * * @author Neil Mayo */ public class RunKbartReport { // Alternative names for non-KBART fields in the input file. /** Case-insensitive name for a volume string. */ protected static final String VOLUME_STR = "volume"; /** Case-insensitive name for a year/date string. */ protected static final String YEAR_STR = "year"; /** Case-insensitive name for a issue string. */ protected static final String ISSUE_STR = "issue"; /** Case-insensitive name for an ISSN-L string. */ protected static final String ISSNL_STR = "issnl"; /** Array of the non-KBART field names. */ protected static final String[] nonKbartFields = {VOLUME_STR, YEAR_STR, ISSUE_STR, ISSNL_STR}; /** Array of the possible fields for volume string. */ protected static final String[] volFields = {VOLUME_STR, "param[volume]", "param[volume_name]", "param[volume_str]"}; /** Array of the possible fields for year string. */ protected static final String[] yrFields = {YEAR_STR, "param[year]"}; /** Array of the possible fields for issue string. */ protected static final String[] issFields = {ISSUE_STR, "param[num_issue_range]", "param[issue_set]", "param[issue_no]", "param[issues]", "param[issue_no.]", "param[issue_dir]"}; static public enum PubType { book, journal }; /** An input stream providing the CSV input data. */ private final InputStream inputStream; // Settings from the command line private final boolean hideEmptyColumns; private final boolean showTdbStatus; private KbartExportFilter.ColumnOrdering columnOrdering; private final PubType publicationType; //private static final String DATA_FORMATS_CONFIG_FILE = "data-formats.xml"; /* data-formats.xml org.lockss.exporter.kbart.Data-Format format @name display-name desc cols */ /*private static List<KbartExportFilter.ColumnOrdering> dataFormats; static { InputStream file = ClassLoader.getSystemClassLoader().getResourceAsStream(DATA_FORMATS_CONFIG_FILE); }*/ /*private static List<KbartExportFilter.ColumnOrdering> dataFormats = new ArrayList<KbartExportFilter.ColumnOrdering>() {{ KbartExportFilter.PredefinedColumnOrdering.values(); }};*/ /** * Construct an instance of this class with the supplied properties. * @param publicationType * @param hideEmptyColumns * @param showTdbStatus * @param columnOrdering * @param inputStream * @param outputStream */ protected RunKbartReport(PubType publicationType, boolean hideEmptyColumns, boolean showTdbStatus, PredefinedColumnOrdering columnOrdering, InputStream inputStream, OutputStream outputStream) { this.publicationType = publicationType; this.hideEmptyColumns = hideEmptyColumns; this.showTdbStatus = showTdbStatus; this.inputStream = inputStream; this.columnOrdering = columnOrdering; long s = System.currentTimeMillis(); // Now we are doing an export - create the exporter KbartExporter kexp = createExporter(); // Make sure the exporter was properly instantiated if (kexp==null) die("Could not create exporter"); // Do the export kexp.export(outputStream); System.err.format("Export took approximately %ss\n", (System.currentTimeMillis() - s) / 1000); } /** * Make an exporter to be used in an export; this involves extracting and * converting titles from the TDB and passing to the exporter's constructor. * The exporter is configured with the basic settings; further configuration * may be necessary for custom exports. * * @return a usable exporter, or null if one could not be created */ private KbartExporter createExporter() { // The list of KbartTitles to export; each title represents a TdbTitle over // a particular range of coverage. List<KbartTitle> titles = null; // Get the list of BibliographicItems and turn them into // KbartTitles which represent the coverage ranges available for the titles. try { titles = KbartConverter.convertTitleAus( new KbartCsvTitleIterator(inputStream, publicationType) ); } catch (Exception e) { die("Could not read CSV file. "+e.getMessage(), e); } System.err.println(titles.size()+" KbartTitles for export"); // Create a filter KbartExportFilter filter = new KbartExportFilter(titles, columnOrdering, hideEmptyColumns, false, false); // Create and configure a CSV exporter KbartExporter kexp = KbartExporter.OutputFormat.CSV.makeExporter(titles, filter); return kexp; } /** * An iterator for a CSV input file, outputting a List of BibliographicItems * per sequence of consecutive records for the same title. Multiple records * for the same title, with different coverage data, should be listed * consecutively or they will not be combined into a list. * Empty lines will be silently ignored. */ static class KbartCsvTitleIterator implements Iterator<List<BibliographicItem>> { /** The iterator on the records in the CSV file. */ private final KbartCsvIterator recordIterator; /** The next item from the record iterator, to start a new title. */ private BibliographicItem nextItem = null; protected KbartCsvTitleIterator( InputStream inputStream, PubType publicationType) throws IOException, IllegalArgumentException { this.recordIterator = new KbartCsvIterator(inputStream, publicationType); if (recordIterator.hasNext()) { this.nextItem = recordIterator.next(); } } public boolean hasNext() { // If there are more CSV records, there is another title //return recordIterator.hasNext(); return nextItem!=null; } public List<BibliographicItem> next() { if (nextItem==null) throw new NoSuchElementException(); // Create a title with the next item Vector<BibliographicItem> title = new Vector<BibliographicItem>() {{ add(nextItem); }}; // Read the records until one differs while (recordIterator.hasNext()) { nextItem = recordIterator.next(); // Add this item to the title if it is the first or if it // appears to have the same id as the previous; otherwise break if (title.isEmpty() || BibliographicUtil.haveSameIdentity(title.lastElement(), nextItem)) { title.add(nextItem); /*if (!title.isEmpty()) System.err.format("Same identity:\n %s\n %s\n", title.lastElement(), nextItem);*/ } else { return title; } } // No more records nextItem = null; return title; } public void remove() { throw new UnsupportedOperationException(); } } /** * An iterator for a CSV input file, outputting a BibliographicItem per * record. If there are multiple records for the same title, with different * coverage data, they should be listed consecutively or they will not be * combined. Empty lines will be silently ignored. */ static class KbartCsvIterator implements Iterator<BibliographicItem> { private final CsvReader csvReader; private String[] nextLine; protected final BibliographicItemFieldMapping mapping; protected final PubType publicationType; /** * Create an iterator on a CSV file, which returns a BibliographicItem for * each line. * @param inputStream * @param publicationType * @throws IOException * @throws RuntimeException */ protected KbartCsvIterator(InputStream inputStream, PubType publicationType) throws IOException, RuntimeException { this.publicationType = publicationType; this.csvReader = new CsvReader(inputStream, Charset.forName("utf-8")); // Read first line as header line csvReader.readHeaders(); // If the first line is not an appropriate list of field names // for the mapping, an exception is thrown this.mapping = new BibliographicItemFieldMapping(csvReader.getHeaders()); // Read the first line of data try { this.nextLine = getNonEmptyLine(csvReader); } catch (Exception e) { throw new NoSuchElementException("There are no data rows."); } } public boolean hasNext() { return nextLine != null; } /** * Read from the iterator until the first non-empty line. * @param csvIterator * @return the next line, or null if there is no such line */ private static String[] getNonEmptyLine(CsvReader csvReader) { String[] line = new String[0]; while (line!=null && ArrayUtils.isEmpty(line)) { try { if (csvReader.readRecord()) line = csvReader.getValues(); else return null; } catch (IOException e) { line = null; } } return line; } /** * * @return a BibliographicItem representing the next non-empty record */ public BibliographicItem next() throws NoSuchElementException { if (nextLine==null) throw new NoSuchElementException(); // Create the next BibliographicItem BibliographicItem bibItem = makeBibItem(nextLine); // Get next non-empty line nextLine = getNonEmptyLine(csvReader); return bibItem; } public void remove() { throw new UnsupportedOperationException(); } private BibliographicItem makeBibItem(String[] props) { return mapping.getBibliographicItem(props); } /** * A mapping of BibliographicItem fields to their column positions in the * input file. Looks for standard KBART field names, and also combined * range strings for volume, year and issue. */ protected class BibliographicItemFieldMapping { /** Map of KBART Fields to field positions. */ private final Map<Field, Integer> kbartFieldPositions; /** Map of alternative field names to field positions. */ private final Map<String, Integer> otherFieldPositions; protected final boolean containsIdField; protected final boolean containsRangeField; /** * Takes an array of header labels, and * @param header an array of header strings */ BibliographicItemFieldMapping(String[] header) { this.kbartFieldPositions = new HashMap<Field, Integer>(); this.otherFieldPositions = new HashMap<String, Integer>(); // Map field names that match KBART names, to their position for (int i=0; i< header.length; i++) { String s = header[i]; try { Field field = Field.valueOf(s.toUpperCase()); kbartFieldPositions.put(field, i); } catch (Exception e) { // No such KBART field; map the field name to a position otherFieldPositions.put(s.toLowerCase(), i); } } this.containsIdField = containsIdField(); this.containsRangeField = containsRangeField(); if (!containsIdField) throw new IllegalArgumentException("No id fields."); //if (!containsRangeField) } /** * Get the value of the field from the array, using the mapping. * @param f the field to find * @param values a list of values matching the field mapping * @return the mapped value of the field, or empty string if no such field or it is empty */ public String getValue(Field f, String[] values) { try { //return fieldPositions.containsKey(f) ? values[fieldPositions.get(f)] : null; String s = values[kbartFieldPositions.get(f)]; // Return empty string if the string is empty or null return StringUtil.isNullString(s) ? "" : s; } catch (Exception e) { return ""; } } /** * Get the value of the field from the array, using the mapping. * @param name the name of the field to find * @param values a list of values matching the field mapping * @return the mapped value of the field, or <tt>null</tt> if no such field or it is empty */ public String getValue(String name, String[] values) { try { String s = values[otherFieldPositions.get(name)]; // Return null if the string is empty return StringUtil.isNullString(s) ? null : s; } catch (Exception e) { return null; } } /** * Try and find a field value from one of the several possible field names * enumerated in the candidates. The first non-null non-empty value is * returned. * @param values * @return */ public String findValue(String[] values, String[] candidates) { for (String f : candidates) { String val = getValue(f, values); if (val!=null) return val; } return null; } private boolean containsIdField() { for (Field f : Field.idFields) { if (kbartFieldPositions.keySet().contains(f)) return true; } return false; } private boolean containsRangeField() { for (Field f : Field.rangeFields) { if (kbartFieldPositions.keySet().contains(f)) return true; } return false; } /** * Create a BibliographicItem with field values taken from the value set * supplied. Uses BibliographicItemImpl to take advantage of * its basic functionality, in particular the getIssn() implementation. * @param values an array of mapped String values * @return */ public BibliographicItem getBibliographicItem(final String[] values) { return new BibliographicItemImpl() { @Override public String toString() { String pubIdentifier = getIsbn(); if (StringUtil.isNullString(pubIdentifier)) { pubIdentifier = getIssn(); } return String.format("BibliographicItem %s %s", pubIdentifier, getPublicationTitle()); } } .setPrintIsbn(getValue(Field.PRINT_IDENTIFIER, values)) .setEisbn(getValue(Field.ONLINE_IDENTIFIER, values)) .setPrintIssn(getValue(Field.PRINT_IDENTIFIER, values)) .setEissn(getValue(Field.ONLINE_IDENTIFIER, values)) .setIssnL(getValue(ISSNL_STR, values)) .setPublicationTitle(getValue(Field.PUBLICATION_TITLE, values)) .setPublisherName(getValue(Field.PUBLISHER_NAME, values)) .setName(getValue("name", values)) // not standard KBART field .setStartVolume(getValue(Field.NUM_FIRST_VOL_ONLINE, values)) .setEndVolume(getValue(Field.NUM_LAST_VOL_ONLINE, values)) .setStartYear(getValue(Field.DATE_FIRST_ISSUE_ONLINE, values)) .setEndYear(getValue(Field.DATE_LAST_ISSUE_ONLINE, values)) .setStartIssue(getValue(Field.NUM_FIRST_ISSUE_ONLINE, values)) .setEndIssue(getValue(Field.NUM_LAST_ISSUE_ONLINE, values)) .setCoverageDepth(getValue(Field.COVERAGE_DEPTH, values)) // Set volume/year/issue strings last - if they are non-null, they // will be used to set the start and end values too, overriding // what might have been set earlier in set[Start|End]* .setVolume(findValue(values, volFields)) .setYear(findValue(values, yrFields)) .setIssue(findValue(values, issFields)) .setPublicationType(publicationType.toString()); } } } // OPTIONS PROCESSING // Short names of options private static final String SOPT_HELP = "h"; private static final String SOPT_HIDE_EMPTY_COLS = "e"; private static final String SOPT_DATA = "d"; private static final String SOPT_FILE = "i"; private static final String SOPT_SHOW_STATUS = "s"; private static final String FOR_JOURNALS = "J"; private static final String FOR_BOOKS = "B"; private static final KbartExporter.OutputFormat defaultOutput = KbartExporter.OUTPUT_FORMAT_DEFAULT; private static final PredefinedColumnOrdering DEFAULT_COLUMN_ORDERING = KbartExportFilter.COLUMN_ORDERING_DEFAULT; /** * Options spec. */ private static Options options = new Options(); /** * A list to track the desired order of options in usage output, as Apache * Commons doesn't use the order of addition by default. */ private static List<Option> optionList = new ArrayList<Option>(); /** * Add the given OptionGroup to the options order list as well as the * options spec. * @param g an OptionGroup * @param setReq whether to set the option as a required one */ private static void addOptionGroup(OptionGroup g, boolean setReq) { g.setRequired(setReq); for (Object opt : g.getOptions()) { optionList.add((Option)opt); } options.addOptionGroup(g); } /** * Add the given Option to the options order list as well as the options spec. * @param o an Option * @param setReq whether to set the option as a required one */ private static void addOption(Option o, boolean setReq) { o.setRequired(setReq); optionList.add(o); options.addOption(o); } /** * Add the given Option to the options order list as well as the options spec, * as an optional Option. * @param o an Option */ private static void addOption(Option o) { addOption(o, false); } /** * Add the given OptionGroup to the options spec, and its component Options * to the options order list. An OptionGroup contains mutually exclusive * Options. The selected/default option is set to the first in the list by * default. * @param og an OptionGroup */ private static void addOptionGroup(OptionGroup og) { for (Object o : og.getOptions()) optionList.add((Option)o); options.addOptionGroup(og); } // Create all the options, add them to the spec and mark those that are required. static { // options for generating MD file OptionGroup reportTypeGroup = new OptionGroup() .addOption(OptionBuilder .withDescription("for books") .withLongOpt("books") .create(FOR_BOOKS)) .addOption(OptionBuilder .withDescription("for journals") .withLongOpt("journals") .create(FOR_JOURNALS)); addOptionGroup(reportTypeGroup, true); // The input file option is required addOption(new Option(SOPT_FILE, "input-file", true, "Path to the input file"), true); // Help option addOption(new Option(SOPT_HELP, "help", false, "Show help")); // Option to hide empty cols addOption(new Option(SOPT_HIDE_EMPTY_COLS, "hide-empty-cols", false, "Hide output columns that are empty.")); // Output data format - defines the fields and their ordering addOption(new Option(SOPT_DATA, "data-format", true, "Format of the output data records.")); // Option to show TDB status // TODO Not yet available //addOption(new Option(SOPT_SHOW_STATUS, "show-tdb-status", false, "Show status field from TDB.")); } private static void selectDefaultGroupOption(OptionGroup og, Option opt) { try { og.setSelected(opt); } catch (AlreadySelectedException e) {/*Don't care*/} catch (NoSuchElementException e) { System.err.format("The default option %s is not available.", opt); og.setRequired(true); // The user must specify } } /** * Print a message, and exit. * @param msg a message */ private static void die(String msg) { System.err.println(msg); System.exit(1); } /** * Print a message with exception, show exception stack trace, and exit. * @param msg a message * @param e an exception */ private static void die(String msg, Exception e) { System.err.format("%s %s\n", msg, e); e.printStackTrace(); System.exit(1); } /** * Print a usage message. * @param error whether a parsing error provoked this usage display */ private static void usage(boolean error) { HelpFormatter help = new HelpFormatter(); // Set a comparator that will output the options in the order // they were specified above help.setOptionComparator(new Comparator<Option>() { public int compare(Option option, Option option1) { Integer i = optionList.indexOf(option); Integer i1 = optionList.indexOf(option1); return i.compareTo(i1); } }); // Print blank line System.err.println(); help.printHelp("RunKbartReport", options, true); if (error) { for (Object o : options.getRequiredOptions()) { System.err.format("Note that the -%s option is required\n", o); } } // Show defaults System.err.println(""); //System.err.println("Default output format is "+defaultOutput); //System.err.println("Default data format is "+DEFAULT_COLUMN_ORDERING); // Print data format options System.err.format("Data format argument must be one of the following " + "identifiers (default %s):\n", DEFAULT_COLUMN_ORDERING.name()); for (PredefinedColumnOrdering ord : PredefinedColumnOrdering.values()) { System.err.format(" %s (%s)\n", ord.name(), ord.description); } System.err.format("\nInput file should be UTF-8 encoded and include a " + "header row with field names matching KBART field names or any of the " + "following: %s.\n\n", StringUtils.join(nonKbartFields, ", ")); System.exit(0); } /** * Parse options and create an instance. * See new KbartExportFilter(titles) for default options. * @param args */ public static void main(String[] args) { // Try parsing the args CommandLine cl = null; try { cl = new GnuParser().parse(options, args); } catch (ParseException e) { //e.printStackTrace(); System.err.println("Could not parse options"); usage(true); } if (cl==null || cl.hasOption(SOPT_HELP)) usage(false); // Determine the ordering for the output data PredefinedColumnOrdering ordering; try { ordering = PredefinedColumnOrdering.valueOf( cl.getOptionValue(SOPT_DATA) ); } catch (Exception e) { ordering = DEFAULT_COLUMN_ORDERING; } PubType pubType = null; if (cl.hasOption(FOR_JOURNALS)) pubType = PubType.journal; if (cl.hasOption(FOR_BOOKS)) pubType = PubType.book; // Create an instance try { // input from named file or stdin if "-" specified String f = cl.getOptionValue(SOPT_FILE); InputStream in = "-".equals(f) ? System.in : new FileInputStream(f); new RunKbartReport( pubType, cl.hasOption(SOPT_HIDE_EMPTY_COLS), cl.hasOption(SOPT_SHOW_STATUS), ordering, in, System.out ); } catch (Exception e) { System.err.println("Could not create RunKbartReport: "+e.getMessage()); } } }
package io.grpc; import java.util.concurrent.TimeUnit; /** * A {@link Channel} that provides lifecycle management. */ public abstract class ManagedChannel extends Channel { /** * Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately * cancelled. */ public abstract ManagedChannel shutdown(); /** * Returns whether the channel is shutdown. Shutdown channels immediately cancel any new calls, * but may still have some calls being processed. * * @see #shutdown() * @see #isTerminated() */ public abstract boolean isShutdown(); /** * Returns whether the channel is terminated. Terminated channels have no running calls and * relevant resources released (like TCP connections). * * @see #isShutdown() */ public abstract boolean isTerminated(); /** * Initiates a forceful shutdown in which preexisting and new calls are cancelled. Although * forceful, the shutdown process is still not instantaneous; {@link #isTerminated()} will likely * return {@code false} immediately after this method returns. * * <p>NOT YET IMPLEMENTED. This method currently behaves identically to shutdown(). */ public abstract ManagedChannel shutdownNow(); /** * Waits for the channel to become terminated, giving up if the timeout is reached. * * @return whether the channel is terminated, as would be done by {@link #isTerminated()}. */ public abstract boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException; }
// Triple Play - utilities for use in PlayN-based games package tripleplay.ui; import playn.core.Pointer; import playn.core.Pointer.Event; import playn.core.Sound; import pythagoras.f.IDimension; import pythagoras.f.Point; import react.Signal; import react.Slot; import react.Value; /** * Controls the behavior of a widget (how it responds to pointer events). */ public abstract class Behavior<T extends Element<T>> implements Pointer.Listener { /** Implements button-like behavior: selects the element when the pointer is in bounds, and * deselects on release. This is a pretty common case and inherited by {@link Click}. */ public static class Select<T extends Element<T>> extends Behavior<T> { public Select (T owner) { super(owner); } @Override protected void onPress (Pointer.Event event) { updateSelected(true); } @Override protected void onHover (Pointer.Event event, boolean inBounds) { updateSelected(inBounds); } @Override protected boolean onRelease (Pointer.Event event) { // it's a click if we ended in bounds return updateSelected(false); } @Override protected void onCancel (Pointer.Event event) { updateSelected(false); } @Override protected void onClick (Pointer.Event event) { // nothing by default, subclasses wire this up as needed } } /** A behavior that ignores everything. This allows subclasses to easily implement a single * {@code onX} method. */ public static class Ignore<T extends Element<T>> extends Behavior<T> { public Ignore (T owner) { super(owner); } @Override protected void onPress (Pointer.Event event) {} @Override protected void onHover (Pointer.Event event, boolean inBounds) {} @Override protected boolean onRelease (Pointer.Event event) { return false; } @Override protected void onCancel (Pointer.Event event) {} @Override protected void onClick (Pointer.Event event) {} } /** Implements clicking behavior. */ public static class Click<T extends Element<T>> extends Select<T> { /** A delay (in milliseconds) during which the owner will remain unclickable after it has * been clicked. This ensures that users don't hammer away at a widget, triggering * multiple responses (which code rarely protects against). Inherited. */ public static Style<Integer> DEBOUNCE_DELAY = Style.newStyle(true, 500); /** A signal emitted with our owner when clicked. */ public Signal<T> clicked = Signal.create(); public Click (T owner) { super(owner); } /** Triggers a click. */ public void click () { soundAction(); clicked.emit(_owner); // emit a click event } @Override public void layout () { super.layout(); _debounceDelay = resolveStyle(DEBOUNCE_DELAY); } @Override protected void onPress (Pointer.Event event) { // ignore press events if we're still in our debounce interval if (event.time() - _lastClickStamp > _debounceDelay) super.onPress(event); } @Override protected void onClick (Pointer.Event event) { _lastClickStamp = event.time(); click(); } protected int _debounceDelay; protected double _lastClickStamp; } /** Implements toggling behavior. */ public static class Toggle<T extends Element<T>> extends Behavior<T> { /** A signal emitted with our owner when clicked. */ public final Signal<T> clicked = Signal.create(); /** Indicates whether our owner is selected. It may be listened to, and updated. */ public final Value<Boolean> selected = Value.create(false); public Toggle (T owner) { super(owner); selected.connect(selectedDidChange()); } /** Triggers a click. */ public void click () { soundAction(); clicked.emit(_owner); // emit a click event } @Override protected void onPress (Pointer.Event event) { _anchorState = _owner.isSelected(); selected.update(!_anchorState); } @Override protected void onHover (Pointer.Event event, boolean inBounds) { selected.update(inBounds ? !_anchorState : _anchorState); } @Override protected boolean onRelease (Pointer.Event event) { return _anchorState != _owner.isSelected(); } @Override protected void onCancel (Pointer.Event event) { selected.update(_anchorState); } @Override protected void onClick (Pointer.Event event) { click(); } protected boolean _anchorState; } /** * Tracks the pressed position as an anchor and delegates to subclasses to update state based * on anchor and drag position. */ public static abstract class Track<T extends Element<T>> extends Ignore<T> { /** A distance, in event coordinates, used to decide if tracking should be temporarily * cancelled. If the pointer is hovered more than this distance outside of the owner's * bounds, the tracking will revert to the anchor position, just like when the pointer is * cancelled. A null value indicates that the tracking will be unconfined in this way. * TODO: default to 35 if no Slider uses are relying on lack of hover limit. */ public static Style<Float> HOVER_LIMIT = Style.newStyle(true, (Float)null); /** Holds the necessary data for the currently active press. {@code Track} subclasses can * derive if more transient information is needed. */ public class State { /** Time the press started. */ public final double pressTime; /** The press and drag positions. */ public final Point press, drag; /** Creates a new tracking state with the given starting press event. */ public State (Pointer.Event event) { pressTime = event.time(); toPoint(event, press = new Point()); drag = new Point(press); } /** Updates the state to the current event value and called {@link Track#onTrack()}. */ public void update (Pointer.Event event) { boolean cancel = false; if (_hoverLimit != null) { float lim = _hoverLimit, lx = event.localX(), ly = event.localY(); IDimension size = _owner.size(); cancel = lx + lim < 0 || ly + lim < 0 || lx - lim >= size.width() || ly - lim >= size.height(); } toPoint(event, drag); onTrack(press, cancel ? press : drag); } } protected Track (T owner) { super(owner); } /** * Called when the pointer is dragged. After cancel or if the pointer goes outside the * hover limit, drag will be equal to anchor. * @param anchor the pointer position when initially pressed * @param drag the current pointer position */ abstract protected void onTrack (Point anchor, Point drag); /** * Creates the state instance for the given press. Subclasses may return an instance * of a derived {@code State} if more information is needed during tracking. */ protected State createState (Pointer.Event press) { return new State(press); } /** * Converts an event to coordinates consumed by {@link #onTrack(Point, Point)}. By * default, simply uses the local x, y. */ protected void toPoint (Pointer.Event event, Point dest) { dest.set(event.localX(), event.localY()); } @Override protected void onPress (Event event) { _state = createState(event); } @Override protected void onHover (Event event, boolean inBounds) { if (_state != null) _state.update(event); } @Override protected boolean onRelease (Event event) { _state = null; return false; } @Override protected void onCancel (Event event) { // track to the press position to cancel if (_state != null) onTrack(_state.press, _state.press); _state = null; } @Override public void layout () { super.layout(); _hoverLimit = resolveStyle(HOVER_LIMIT); } protected State _state; protected Float _hoverLimit; } /** A click behavior that captures the pointer and optionally issues clicks based on some time * based function. */ public static abstract class Capturing<T extends Element<T>> extends Click<T> implements Interface.Task { protected Capturing (T owner) { super(owner); } @Override protected void onPress (Event event) { super.onPress(event); event.capture(); _task = _owner.root().iface().addTask(this); } @Override protected void onCancel (Event event) { super.onCancel(event); cancelTask(); } @Override protected boolean onRelease (Event event) { super.onRelease(event); cancelTask(); return false; } /** Cancels the time-based task. This is called automatically by the pointer release * and cancel events. */ protected void cancelTask () { if (_task == null) return; _task.remove(); _task = null; } protected Interface.TaskHandle _task; } /** Captures the pointer and dispatches one click on press, a second after an initial delay * and at regular intervals after that. */ public static class RapidFire<T extends Element<T>> extends Capturing<T> { /** Milliseconds after the first click that the second click is dispatched. */ public static final Style<Integer> INITIAL_DELAY = Style.newStyle(true, 200); /** Milliseconds between repeated click dispatches. */ public static final Style<Integer> REPEAT_DELAY = Style.newStyle(true, 75); /** Creates a new rapid fire behavior for the given owner. */ public RapidFire (T owner) { super(owner); } @Override protected void onPress (Event event) { super.onPress(event); _timeInBounds = 0; click(); } @Override protected void onHover (Event event, boolean inBounds) { super.onHover(event, inBounds); if (!inBounds) _timeInBounds = -1; else if (_timeInBounds < 0) { _timeInBounds = 0; click(); } } @Override public void update (int delta) { if (_timeInBounds < 0) return; int was = _timeInBounds; _timeInBounds += delta; int limit = was < _initDelay ? _initDelay : _initDelay + _repDelay * ((was - _initDelay) / _repDelay + 1); if (was < limit && _timeInBounds >= limit) click(); } @Override public void layout () { super.layout(); _initDelay = _owner.resolveStyle(INITIAL_DELAY); _repDelay = _owner.resolveStyle(REPEAT_DELAY); } protected int _initDelay, _repDelay, _timeInBounds; } public Behavior (T owner) { _owner = owner; } @Override public void onPointerStart (Pointer.Event event) { if (_owner.isEnabled()) onPress(event); } @Override public void onPointerDrag (Pointer.Event event) { if (_owner.isEnabled()) onHover(event, _owner.contains(event.localX(), event.localY())); } @Override public void onPointerEnd (Pointer.Event event) { if (onRelease(event)) onClick(event); } @Override public void onPointerCancel (Pointer.Event event) { onCancel(event); } /** Called when our owner is laid out. If the behavior needs to resolve configuration via * styles, this is where it should do it. */ public void layout () { _actionSound = resolveStyle(Style.ACTION_SOUND); } /** Emits the action sound for our owner, if one is configured. */ public void soundAction () { if (_actionSound != null) _actionSound.play(); } /** Resolves the value for the supplied style via our owner. */ protected <V> V resolveStyle (Style<V> style) { return Styles.resolveStyle(_owner, style); } /** Returns the {@link Root} to which our owning element is added, or null. */ protected Root root () { return _owner.root(); } /** Called when the pointer is pressed down on our element. */ protected abstract void onPress (Pointer.Event event); /** Called as the user drags the pointer around after pressing. Derived classes map this onto * the widget state, such as updating selectedness. */ protected abstract void onHover (Pointer.Event event, boolean inBounds); /** Called when the pointer is released after having been pressed on this widget. This should * return true if the gesture is considered a click, in which case {@link #onClick} will * be called automatically. */ protected abstract boolean onRelease (Pointer.Event event); /** Called when the interaction is canceled after having been pressed on this widget. This * should not result in a call to {@link #onClick}. */ protected abstract void onCancel (Pointer.Event event); /** Called when the pointer is released and the subclass decides that it is a click, i.e. * returns true from {@link #onRelease(Pointer.Event)}. */ protected abstract void onClick (Pointer.Event event); /** Updates the selected state of our owner, invalidating if selectedness changes. * @return true if the owner was selected on entry. */ protected boolean updateSelected (boolean selected) { boolean wasSelected = _owner.isSelected(); if (selected != wasSelected) { _owner.set(Element.Flag.SELECTED, selected); _owner.invalidate(); } return wasSelected; } /** Slot for calling {@link #updateSelected(boolean)}. */ protected Slot<Boolean> selectedDidChange () { return new Slot<Boolean>() { @Override public void onEmit (Boolean selected) { updateSelected(selected); } }; } protected final T _owner; protected Sound _actionSound; }
//package declaration package view.tabs; //import declarations import java.awt.Color; import java.awt.event.ActionListener; import java.awt.event.MouseListener; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.SwingConstants; import javax.swing.border.LineBorder; import model.settings.ViewSettings; import control.interfaces.MenuListener; import control.tabs.CPaintStatus; import control.tabs.CTabSelection; import control.tabs.ControlTabPainting; import view.util.Item1Menu; import view.util.Item1Button; import view.util.VColorPanel; import view.util.mega.MButton; /** * The Selection Tab. * * @author Julius Huelsmann * @version %I%, %U% */ @SuppressWarnings("serial") public final class Selection extends Tab { /** * array of colors to change the first or the second color. */ private MButton [] jbtn_colors; /** * Buttons for the second and the first color. */ private Item1Button tb_color; /** * Color fetcher. */ private Item1Menu it_color; /** * integer values. */ private final int distance = 5, heightLabel = 20, htf = 135, twoHundred = 200; /** * The JCheckBox for changing the pen. */ private JCheckBox jcb_points, jcb_line, jcb_maths; /** * Empty Utility class Constructor. */ public Selection() { super(2); super.setOpaque(false); super.setLayout(null); } public void applySize() { super.applySize(); int x = initCololrs(distance, false, null, null, null, null); x = initPen(x, false, null); initOthers(x, false, null, null); } /** * * @param _cPaint the ControlTabPainting instance * @param _cts the CTabSelection instance * @param _ml the MenuListener instance */ public void initialize( final ControlTabPainting _cPaint, final CTabSelection _cts, final MenuListener _ml, final CPaintStatus _controlPaintStatus){ int x = initCololrs(distance, true, _cPaint, _cts, _ml, _controlPaintStatus); x = initPen(x, true, _cts); initOthers(x, true, _ml, _controlPaintStatus); } /** * * @param _x the x coordinate * @param _paint the boolean. * * * @param _controlTabPainting * instance of ControlTabPainting handling the * MouseEvents for the color selection in color * pane * * @param _cTabSelection * instance of ControlTabSelection handling the * ActionEvents for the color button selection * * @param _ml * implements MenuListener _ml which handles menu * opening and closing events for being able to repaint * or to do other necessary stuff. * * @return the new x coordinate */ private int initCololrs(final int _x, final boolean _paint, final MouseListener _controlTabPainting, final ActionListener _cTabSelection, final MenuListener _ml, final CPaintStatus _controlPaintStatus) { if (_paint) { //the first color for the first pen tb_color = new Item1Button(null); tb_color.setOpaque(true); // tb_color.addMouseListener(CPaintStatus.getInstance()); tb_color.setBorder(BorderFactory.createCompoundBorder( new LineBorder(Color.black), new LineBorder(Color.white))); } tb_color.setLocation(_x, ViewSettings.getDistanceBetweenItems()); tb_color.setSize(ViewSettings.getItemMenu1Width(), ViewSettings.getItemMenu1Height()); if (_paint) { tb_color.setText("Farbe 1"); tb_color.setActivable(false); super.add(tb_color); } final int distanceBetweenColors = 2; int width = (2 + 2 + 1) * (2 + 2 + 1) - 2 - 2; int height = width + 2 + 1 + 2 * (2 + 1); int anzInR = 2 + 2 + 2 + 1; if (_paint) { jbtn_colors = new MButton[anzInR * (2 + 2)]; } for (int i = 0; i < jbtn_colors.length; i++) { if (_paint) { jbtn_colors[i] = new MButton(); } jbtn_colors[i].setBounds(tb_color.getX() + tb_color.getWidth() + distanceBetweenColors + (i % anzInR) * (width + distanceBetweenColors), distanceBetweenColors + (i / anzInR) * (height + distanceBetweenColors), width, height); if (_paint) { jbtn_colors[i].setOpaque(true); jbtn_colors[i].addActionListener(_cTabSelection); jbtn_colors[i].addMouseListener(_controlPaintStatus); jbtn_colors[i].addMouseListener(_controlTabPainting); jbtn_colors[i].setBorder(BorderFactory.createCompoundBorder( new LineBorder(Color.black), new LineBorder(Color.white))); super.add(jbtn_colors[i]); } } if (_paint) { int i = 0; final int three = 3; final Color c1n0 = Color.black, c1n1 = new Color(80, 80, 80), c1n2 = new Color(160, 160, 160), c1n3 = Color.white, c2n0 = new Color(23, 32, 164), c2n1 = new Color(63, 72, 204), c2n2 = new Color(103, 112, 244), c2n3 = new Color(153, 162, 255), c3n0 = new Color(180, 10, 10), c3n1 = new Color(200, 20, 20), c3n2 = new Color(250, 75, 75), c3n3 = new Color(255, 100, 100), c4n0 = new Color(24, 157, 45), c4n1 = new Color(34, 177, 67), c4n2 = new Color(64, 197, 97), c4n3 = new Color(104, 255, 147), c5n0 = new Color(235, 107, 73), c5n1 = new Color(255, 127, 93), c5n2 = new Color(255, 147, 113), c5n3 = new Color(255, 187, 153), c6n0 = new Color(133, 33, 134), c6n1 = new Color(163, 73, 164), c6n2 = new Color(193, 103, 194), c6n3 = new Color(255, 153, 254), c7n0 = new Color(112, 146, 190), c7n1 = new Color(200, 191, 231), c7n2 = new Color(255, 201, 14), c7n3 = new Color(120, 74, 50); //schwarz bis grau jbtn_colors[i + anzInR * 0].setBackground(c1n0); jbtn_colors[i + anzInR * 1].setBackground(c1n1); jbtn_colors[i + anzInR * 2].setBackground(c1n2); jbtn_colors[i + anzInR * three].setBackground(c1n3); //blue i++; jbtn_colors[i + anzInR * 0].setBackground(c2n0); jbtn_colors[i + anzInR * 1].setBackground(c2n1); jbtn_colors[i + anzInR * 2].setBackground(c2n2); jbtn_colors[i + anzInR * three].setBackground(c2n3); //red i++; jbtn_colors[i + anzInR * 0].setBackground(c3n0); jbtn_colors[i + anzInR * 1].setBackground(c3n1); jbtn_colors[i + anzInR * 2].setBackground(c3n2); jbtn_colors[i + anzInR * three].setBackground(c3n3); //green i++; jbtn_colors[i + anzInR * 0].setBackground(c4n0); jbtn_colors[i + anzInR * 1].setBackground(c4n1); jbtn_colors[i + anzInR * 2].setBackground(c4n2); jbtn_colors[i + anzInR * three].setBackground(c4n3); //orange i++; jbtn_colors[i + anzInR * 0].setBackground(c5n0); jbtn_colors[i + anzInR * 1].setBackground(c5n1); jbtn_colors[i + anzInR * 2].setBackground(c5n2); jbtn_colors[i + anzInR * three].setBackground(c5n3); //pink i++; jbtn_colors[i + anzInR * 0].setBackground(c6n0); jbtn_colors[i + anzInR * 1].setBackground(c6n1); jbtn_colors[i + anzInR * 2].setBackground(c6n2); jbtn_colors[i + anzInR * three].setBackground(c6n3); i++; jbtn_colors[i + anzInR * 0].setBackground(c7n0); jbtn_colors[i + anzInR * 1].setBackground(c7n1); jbtn_colors[i + anzInR * 2].setBackground(c7n2); jbtn_colors[i + anzInR * three].setBackground(c7n3); } if (_paint) { it_color = new Item1Menu(true); it_color.setMenuListener(_ml); it_color.addMouseListener(_controlPaintStatus); } it_color.setSize(ViewSettings.getSIZE_PNL_CLR()); if (_paint) { it_color.setBorder(false); it_color.setText("+ Farben"); } it_color.setLocation(jbtn_colors[jbtn_colors.length - 1].getX() + ViewSettings.getDistanceBetweenItems() + jbtn_colors[jbtn_colors.length - 1].getWidth(), ViewSettings.getDistanceBetweenItems()); if (_paint) { it_color.getMPanel().add(new VColorPanel(jbtn_colors, _ml, _controlPaintStatus)); it_color.setBorder(false); } it_color.setIcon("icon/palette.png"); if (_paint) { super.add(it_color); } int xLocationSeparation = it_color.getWidth() + it_color.getX() + ViewSettings.getDistanceBeforeLine(); insertSectionStuff("Farben", _x, xLocationSeparation, 0, _paint); return xLocationSeparation + ViewSettings.getDistanceBetweenItems(); } /** * initialize the pen. * @param _x the x coordinate * @param _paint whether to paint the items * * @param _cTabSelection * instance of ControlTabSelection handling the * ActionEvents for all buttons inside this tab * * @return the new x coordinate */ private int initPen(final int _x, final boolean _paint, final CTabSelection _cTabSelection) { if (_paint) { jcb_points = new JCheckBox("points"); jcb_points.setSelected(true); jcb_points.setOpaque(false); } jcb_points.setBounds(_x, distance, twoHundred, heightLabel); if (_paint) { jcb_points.setVerticalAlignment(SwingConstants.TOP); jcb_points.setFocusable(false); jcb_points.addActionListener(_cTabSelection); super.add(jcb_points); jcb_line = new JCheckBox("line"); jcb_line.setVerticalAlignment(SwingConstants.TOP); jcb_line.setFocusable(false); jcb_line.setOpaque(false); } jcb_line.setBounds(_x, jcb_points.getHeight() + jcb_points.getY() + distance, twoHundred, heightLabel); if (_paint) { jcb_line.addActionListener(_cTabSelection); super.add(jcb_line); jcb_maths = new JCheckBox("maths"); jcb_maths.setFocusable(false); jcb_maths.setOpaque(false); jcb_maths.setVerticalAlignment(SwingConstants.TOP); } jcb_maths.setBounds(_x, jcb_line.getHeight() + jcb_line.getY() + distance, twoHundred, heightLabel); if (_paint) { jcb_maths.addActionListener(_cTabSelection); super.add(jcb_maths); //deactivate the items because at the beginning there is no item //selected. _cTabSelection.deactivateOp(); } int xLocationSeparation = jcb_maths.getWidth() + jcb_maths.getX() + ViewSettings.getDistanceBeforeLine(); insertSectionStuff("Pen", _x, xLocationSeparation, 1, _paint); return xLocationSeparation + ViewSettings.getDistanceBetweenItems(); } private Item1Button tb_changePen; private Item1Button tb; private Item1Menu it_stift1; /** * initialize other items. * @param _x the x coordinate * @param _paint whether to paint or not * @param _ml * implements MenuListener _ml which handles menu * opening and closing events for being able to repaint * or to do other necessary stuff. * */ private void initOthers(final int _x, final boolean _paint, final MenuListener _ml, final CPaintStatus _controlPaintStatus) { if (_paint) { tb = new Item1Button(null); tb.setOpaque(true); } tb.setSize(htf, htf); tb.setLocation(_x + distance, distance); if (_paint) { tb.setText("Groesse aendern"); tb.setBorder(BorderFactory.createCompoundBorder( new LineBorder(Color.black), new LineBorder(Color.white))); tb.setActivable(false); tb.setIcon("icon/tabs/write/write.png"); super.add(tb); tb_changePen = new Item1Button(null); tb_changePen.setOpaque(true); } tb_changePen.setSize(htf, htf); tb_changePen.setLocation(tb.getX() + tb.getWidth() + distance, tb.getY()); if (_paint) { tb_changePen.setText("Stift aendern"); tb_changePen.setBorder(BorderFactory.createCompoundBorder( new LineBorder(Color.black), new LineBorder(Color.white))); tb_changePen.setActivable(false); } tb_changePen.setIcon("icon/tabs/write/write.png"); if (_paint) { super.add(tb_changePen); //pen 1 it_stift1 = new Item1Menu(false); it_stift1.setMenuListener(_ml); it_stift1.addMouseListener(_controlPaintStatus); it_stift1.setBorder(null); it_stift1.setBorder(false); it_stift1.setText("Drehen/Spiegeln"); } it_stift1.setLocation(tb_changePen.getX() + tb_changePen.getWidth() + distance, tb_changePen.getY()); it_stift1.setSize(twoHundred, twoHundred + twoHundred / 2); if (_paint) { it_stift1.setActivable(); it_stift1.setItemsInRow((byte) 1); it_stift1.setBorder(false); super.add(it_stift1); } int xLocationSeparation = it_stift1.getWidth() + it_stift1.getX() + ViewSettings.getDistanceBeforeLine(); insertSectionStuff("Farben", _x, xLocationSeparation, 1, _paint); // return xLocationSeparation + ViewSettings.getDistanceBetweenItems(); } /** * @return the jcb_points */ public JCheckBox getJcb_points() { return jcb_points; } /** * @return the jcb_line */ public JCheckBox getJcb_line() { return jcb_line; } /** * @return the jcb_maths */ public JCheckBox getJcb_maths() { return jcb_maths; } /** * @return the jbtn_colors */ public MButton [] getJbtn_colors() { return jbtn_colors; } /** * @return the tb_color */ public Item1Button getTb_color() { return tb_color; } }
/* * $Id: MockCachedUrl.java,v 1.57 2014-12-27 03:42:28 tlipkis Exp $ */ package org.lockss.test; import java.io.*; import java.math.*; import java.util.*; import java.security.MessageDigest; import org.lockss.plugin.*; import org.lockss.daemon.*; import org.lockss.util.*; import org.lockss.rewriter.*; import org.lockss.extractor.*; /** * This is a mock version of <code>CachedUrl</code> used for testing * * @author Thomas S. Robertson * @version 0.0 */ public class MockCachedUrl implements CachedUrl { Logger log = Logger.getLogger(MockCachedUrl.class); private ArrayList versions; private ArchivalUnit au; private String url; private InputStream cachedIS; private CIProperties cachedProp = new CIProperties(); private boolean isLeaf = true; private boolean doesExist = false; private String content = null; private long contentSize = -1; private Reader reader = null; private String cachedFile = null; private boolean isResource; private int version = 0; private LinkRewriterFactory lrf = null; private FileMetadataExtractor metadataExtractor = null; public MockCachedUrl(String url) { this.versions = new ArrayList(); this.url = url; } public MockCachedUrl(String url, ArchivalUnit au) { this(url); this.au = au; } /** * Construct a mock cached URL that is backed by a file. * * @param url * @param file The name of the file to load. * @param isResource If true, load the file name as a * resource. If false, load as a file. */ public MockCachedUrl(String url, String file, boolean isResource) { this(url); this.isResource = isResource; cachedFile = file; } public ArchivalUnit getArchivalUnit() { return au; } public String getUrl() { return url; } public CachedUrl getCuVersion(int version) { if (version == 0) { return this; } else if (versions.isEmpty()) { throw new UnsupportedOperationException("No versions."); } else { return (CachedUrl)versions.get(version); } } public CachedUrl[] getCuVersions() { return getCuVersions(Integer.MAX_VALUE); } public CachedUrl[] getCuVersions(int maxVersions) { int min = Math.min(maxVersions, versions.size() + 1); // Always supply this as the current version CachedUrl[] retVal = new CachedUrl[min]; retVal[0] = this; if (min > 1) { System.arraycopy((CachedUrl[])versions.toArray(new CachedUrl[min]), 0, retVal, 1, min - 1); } return retVal; } public void setVersion(int version) { this.version = version; } public int getVersion() { return version; } public MockCachedUrl addVersion(String content) { // Special case: If this is the first version, alias for 'addContent' if (this.content == null) { this.content = content; return this; } else { MockCachedUrl mcu = new MockCachedUrl(url, au); mcu.content = content; mcu.version = versions.size() + 1; versions.add(mcu); return mcu; } } public Reader openForReading() { if (content != null) { return new StringReader(content); } if (reader != null) { return reader; } return new StringReader(""); } public LinkRewriterFactory getLinkRewriterFactory() { return lrf; } public void setLinkRewriterFactory(LinkRewriterFactory lrf) { this.lrf = lrf; } public void setOption(String option, String val) { } public boolean hasContent() { return doesExist || content != null; } public boolean isLeaf() { return isLeaf; } public void setIsLeaf(boolean isLeaf) { this.isLeaf = isLeaf; } public int getType() { return CachedUrlSetNode.TYPE_CACHED_URL; } public void setExists(boolean doesExist) { this.doesExist = doesExist; } // Read interface - used by the proxy. private InputStream newHashedInputStream(InputStream is, HashedInputStream.Hasher hasher) { return new BufferedInputStream(new HashedInputStream(is, hasher)); } public InputStream getUnfilteredInputStream(HashedInputStream.Hasher hasher) { log.debug3("MockCachedUrl.getUnfilteredInputStream with " + (hasher == null ? "no " : "") + "Hasher"); if (hasher == null) { return getUnfilteredInputStream(); } return newHashedInputStream(getUnfilteredInputStream(), hasher); } public InputStream getUnfilteredInputStream() { log.debug3("MockCachedUrl.getUnfilteredInputStream"); try { if (cachedFile != null) { if (isResource) { return ClassLoader.getSystemClassLoader(). getResourceAsStream(cachedFile); } else { return new FileInputStream(cachedFile); } } } catch (IOException ex) { return null; } if (content != null) { return new StringInputStream(content); } return cachedIS; } public InputStream openForHashing() { return openForHashing(null); } public InputStream openForHashing(HashedInputStream.Hasher hasher) { String contentType = getContentType(); InputStream is = null; // look for a FilterFactory if (au != null) { FilterFactory fact = au.getHashFilterFactory(contentType); if (fact != null) { InputStream unfis = getUnfilteredInputStream(); if (hasher != null) { unfis = newHashedInputStream(unfis, hasher); } if (log.isDebug3()) { log.debug3("Filtering " + contentType + " with " + fact.getClass().getName()); } try { return fact.createFilteredInputStream(au, unfis, getEncoding()); } catch (PluginException e) { IOUtil.safeClose(unfis); throw new RuntimeException(e); } } } return getUnfilteredInputStream(); } public long getContentSize() { if (contentSize != -1) { return contentSize; } if (content != null) { return content.length(); } if (cachedFile != null) { if (isResource) { InputStream in = ClassLoader.getSystemClassLoader(). getResourceAsStream(cachedFile); try { return in.skip(Long.MAX_VALUE); } catch (IOException e) { return 100; } finally { IOUtil.safeClose(in); } } else { return new File(cachedFile).length(); } } return content == null ? 0 : content.length(); } public CIProperties getProperties(){ return cachedProp; } public void addProperty(String key, String value) { cachedProp.setProperty(key, value); } public String getContentType(){ return cachedProp.getProperty(PROPERTY_CONTENT_TYPE); } public String getEncoding(){ return Constants.DEFAULT_ENCODING; } // Write interface - used by the crawler. public void storeContent(InputStream input, CIProperties headers) throws IOException { cachedIS = input; cachedProp = headers; } public FileMetadataExtractor getFileMetadataExtractor(MetadataTarget target) { return metadataExtractor; } //mock specific acessors public void setInputStream(InputStream is){ cachedIS = is; } public void setContent(String content) { this.content = content; } public String getContent() { return content; } public void setContentSize(long size) { this.contentSize = size; } public void setReader(Reader reader) { this.reader = reader; } public void setProperties(CIProperties prop){ cachedProp = prop; } public void setProperty(String key, String val) { cachedProp.put(key, val); } public void setFileMetadataExtractor(FileMetadataExtractor me) { metadataExtractor = me; } public void release() { } public CachedUrl getArchiveMemberCu(ArchiveMemberSpec ams) { return null; } @Override public boolean isArchiveMember() { return false; } public String toString() { StringBuffer sb = new StringBuffer(url.length()+17); sb.append("[MockCachedUrl: "); sb.append(url); sb.append(", v: "); sb.append(version); sb.append("]"); return sb.toString(); } }
package org.biojavax; import java.net.URI; import java.net.URISyntaxException; import junit.framework.*; import org.biojava.utils.ChangeVetoException; /** * * @author Mark Schreiber */ public class SimpleNamespaceTest extends TestCase { SimpleNamespace ns; SimpleNamespace ns2; String name = "test space"; String acronym = "by any other name"; String authority = "respect mah authoritaaah!!!"; String desc = "description"; String uriString = "file:///foo.bar"; public SimpleNamespaceTest(String testName) { super(testName); } protected void setUp() throws Exception { ns = (SimpleNamespace)RichObjectFactory.getObject(SimpleNamespace.class, new Object[]{name}); ns2 = (SimpleNamespace)RichObjectFactory.getObject(SimpleNamespace.class, new Object[]{name}); } protected void tearDown() throws Exception { ns = null; ns2 = null; } public static Test suite() { TestSuite suite = new TestSuite(SimpleNamespaceTest.class); return suite; } /** * Test of setAcronym method, of class org.biojavax.SimpleNamespace. */ public void testSetAcronym() { System.out.println("testSetAcronym"); try{ ns.setAcronym(acronym); assertEquals(acronym, ns.getAcronym()); }catch(ChangeVetoException ex){ fail("Was not expecting "+ex.getClass().getName()); } } /** * Test of setAuthority method, of class org.biojavax.SimpleNamespace. */ public void testSetAuthority() { System.out.println("testSetAuthority"); try{ ns.setAuthority(authority); assertEquals(authority, ns.getAuthority()); }catch(ChangeVetoException ex){ fail("Was not expecting "+ex.getClass().getName()); } } /** * Test of setDescription method, of class org.biojavax.SimpleNamespace. */ public void testSetDescription() { System.out.println("testSetDescription"); try{ ns.setDescription(desc); assertEquals(desc, ns.getDescription()); }catch(ChangeVetoException ex){ fail("Was not expecting "+ex.getClass().getName()); } } /** * Test of setURI method, of class org.biojavax.SimpleNamespace. */ public void testSetURI() throws URISyntaxException{ System.out.println("testSetURI"); URI uri = new URI(uriString); try{ ns.setURI(uri); assertEquals(uri, ns.getURI()); }catch(ChangeVetoException ex){ fail("Was not expecting "+ex.getClass().getName()); } } /** * Test of getAcronym method, of class org.biojavax.SimpleNamespace. */ public void testGetAcronym() { System.out.println("testGetAcronym"); //System.out.println(ns.getAcronym()); //should be set because of retreival from the LRU cache assertEquals(acronym, ns.getAcronym()); } /** * Test of getAuthority method, of class org.biojavax.SimpleNamespace. */ public void testGetAuthority() { System.out.println("testGetAuthority"); assertEquals(authority,ns.getAuthority()); } /** * Test of getDescription method, of class org.biojavax.SimpleNamespace. */ public void testGetDescription() { System.out.println("testGetDescription"); //should be set because of LRU cache assertEquals(desc, ns.getDescription()); try{ ns.setDescription(desc); }catch(Exception ex){ fail("Was not expecting "+ex.getClass().getName()); } assertEquals(desc, ns.getDescription()); } /** * Test of getName method, of class org.biojavax.SimpleNamespace. */ public void testGetName() { System.out.println("testGetName"); assertEquals(name, ns.getName()); } /** * Test of getURI method, of class org.biojavax.SimpleNamespace. */ public void testGetURI() { System.out.println("testGetURI"); assertEquals(uriString, ns.getURI().toString()); } /** * Test of compareTo method, of class org.biojavax.SimpleNamespace. */ public void testCompareTo() { System.out.println("testCompareTo"); assertTrue(ns.compareTo(RichObjectFactory.getDefaultNamespace()) >1); assertTrue(RichObjectFactory.getDefaultNamespace().compareTo(ns) <1); assertTrue(ns.compareTo(ns2) == 0); } /** * Test of equals method, of class org.biojavax.SimpleNamespace. */ public void testEquals() { System.out.println("testEquals"); assertTrue(ns == ns2); assertTrue(ns.equals(ns2)); assertFalse(ns.equals(RichObjectFactory.getDefaultNamespace())); } /** * Test of hashCode method, of class org.biojavax.SimpleNamespace. */ public void testHashCode() { System.out.println("testHashCode"); assertTrue(ns.hashCode() == ns2.hashCode()); } /** * Test of toString method, of class org.biojavax.SimpleNamespace. */ public void testToString() { System.out.println("testToString"); assertEquals(name, ns.toString()); } }
package io.jooby; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class Issue1413 { @Test public void shouldDoPreflightWithCredentials() { new JoobyRunner(app -> { app.decorator(new CorsHandler(new Cors() .setMethods("*") .setOrigin("http://foo.com") .setUseCredentials(true) )); app.put("/api/v1/machines/{key}", ctx -> ctx.path("key").value()); app.post("/api/v1/machines/{key}", ctx -> ctx.path("key").value()); app.get("/api/v1/machines/{key}", ctx -> ctx.path("key").value()); }).ready(client -> { // OPTIONS (Pre-flight), checking PUT Method => OK and Access Control Headers Present client .header("Origin", "http://foo.com") .header("Access-Control-Request-Method", "PUT") .options("/api/v1/machines/123", rsp -> { assertEquals("", rsp.body().string()); assertEquals(200, rsp.code()); assertEquals("http://foo.com", rsp.header("Access-Control-Allow-Origin")); assertEquals("true", rsp.header("Access-Control-Allow-Credentials")); }); // POST Method by allowed origin => OK and Access Control Headers Present client .header("Origin", "http://foo.com") .post("/api/v1/machines/123", rsp -> { assertEquals("123", rsp.body().string()); assertEquals(200, rsp.code()); assertEquals("http://foo.com", rsp.header("Access-Control-Allow-Origin")); assertEquals("true", rsp.header("Access-Control-Allow-Credentials")); }); // Origin different from the allowed one => Forbidden client .header("Origin", "http://bar.com") .get("/api/v1/machines/123", rsp -> { assertEquals(403, rsp.code()); assertEquals(null, rsp.body().string()); assertEquals(null, rsp.header("Access-Control-Allow-Origin")); assertEquals(null, rsp.header("Access-Control-Allow-Credentials")); }); // PUT Method and allowed origin => OK and Access Control Headers Present client .header("Origin", "http://foo.com") .put("/api/v1/machines/123", rsp -> { assertEquals("123", rsp.body().string()); assertEquals(200, rsp.code()); assertEquals("http://foo.com", rsp.header("Access-Control-Allow-Origin")); assertEquals("true", rsp.header("Access-Control-Allow-Credentials")); }); }); } @Test public void shouldDoPreflightWithoutCredentials() { new JoobyRunner(app -> { app.decorator(new CorsHandler(new Cors() .setMethods("*") .setOrigin("http://foo.com") .setUseCredentials(false) )); app.put("/api/v1/machines/{key}", ctx -> ctx.path("key").value()); app.post("/api/v1/machines/{key}", ctx -> ctx.path("key").value()); app.get("/api/v1/machines/{key}", ctx -> ctx.path("key").value()); }).ready(client -> { // OPTIONS (Pre-flight), checking PUT Method => OK and Access Control Headers Present client .header("Origin", "http://foo.com") .header("Access-Control-Request-Method", "PUT") .options("/api/v1/machines/123", rsp -> { assertEquals("", rsp.body().string()); assertEquals(200, rsp.code()); assertEquals("http://foo.com", rsp.header("Access-Control-Allow-Origin")); assertEquals(null, rsp.header("Access-Control-Allow-Credentials")); }); // POST Method by allowed origin => OK and Access Control Headers Present client .header("Origin", "http://foo.com") .post("/api/v1/machines/123", rsp -> { assertEquals("123", rsp.body().string()); assertEquals(200, rsp.code()); assertEquals("http://foo.com", rsp.header("Access-Control-Allow-Origin")); assertEquals(null, rsp.header("Access-Control-Allow-Credentials")); }); // Origin different from the allowed one => Forbidden client .header("Origin", "http://bar.com") .get("/api/v1/machines/123", rsp -> { assertEquals(403, rsp.code()); assertEquals(null, rsp.body().string()); assertEquals(null, rsp.header("Access-Control-Allow-Origin")); assertEquals(null, rsp.header("Access-Control-Allow-Credentials")); }); // PUT Method and allowed origin => OK and Access Control Headers Present client .header("Origin", "http://foo.com") .put("/api/v1/machines/123", rsp -> { assertEquals("123", rsp.body().string()); assertEquals(200, rsp.code()); assertEquals("http://foo.com", rsp.header("Access-Control-Allow-Origin")); assertEquals(null, rsp.header("Access-Control-Allow-Credentials")); }); }); } }
package h2o.testng; import h2o.testng.db.MySQL; import h2o.testng.db.MySQLConfig; import h2o.testng.utils.CommonHeaders; import h2o.testng.utils.Dataset; import h2o.testng.utils.FunctionUtils; import h2o.testng.utils.Param; import h2o.testng.utils.RecordingTestcase; import hex.Model; import hex.deeplearning.DeepLearningConfig; import hex.glm.GLMConfig; import hex.tree.drf.DRFConfig; import hex.tree.gbm.GBMConfig; import java.util.HashMap; import org.apache.commons.lang.StringUtils; import org.testng.Assert; import org.testng.Reporter; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import water.TestNGUtil; public class TestNG extends TestNGUtil { @BeforeClass public void beforeClass() { String dbConfigFilePath = System.getProperty("dbConfigFilePath"); algorithm = System.getProperty("algorithm"); size = System.getProperty("size"); testcaseId = System.getProperty("testcaseId"); if (StringUtils.isNotEmpty(testcaseId)) { algorithm = ""; size = ""; } dataSetCharacteristic = FunctionUtils.readDataSetCharacteristic(); if (StringUtils.isNotEmpty(dbConfigFilePath)) { MySQLConfig.initConfig().setConfigFilePath(dbConfigFilePath); MySQL.createTable(); } System.out.println(String.format("run TestNG with algorithm: %s, size: %s, testcaseId: %s", algorithm, size, testcaseId)); } @DataProvider(name = "SingleTestcase") public static Object[][] dataProvider() { Object[][] result = null; Object[][] data = FunctionUtils.readAllTestcase(dataSetCharacteristic, algorithm); if (data == null || data.length == 0) { return null; } // set testcaseId if (StringUtils.isNotEmpty(testcaseId)) { result = new Object[1][data[0].length]; int i = 0; for (i = 0; i < data.length; i++) { if (testcaseId.equals(data[i][0])) { result[0] = data[i]; break; } } if (i == data.length) { System.out.println("Can not find testcase_id:" + testcaseId); return null; } return result; } // set size result = FunctionUtils.removeAllTestcase(data, size); return result; } @Test(dataProvider = "SingleTestcase") public void basic(String testcase_id, String test_description, String train_dataset_id, String validate_dataset_id, Dataset train_dataset, Dataset validate_dataset, String algorithm, boolean isNegativeTestcase, HashMap<String, String> rawInput) { String testcaseStatus = "PASSED"; RecordingTestcase rt = new RecordingTestcase(); Param[] params = null; Model.Parameters modelParameter = null; String invalidMessage = null; String notImplMessage = null; redirectStandardStreams(); switch (algorithm) { case FunctionUtils.drf: params = DRFConfig.params; break; case FunctionUtils.gbm: params = GBMConfig.params; break; case FunctionUtils.glm: params = GLMConfig.params; break; case FunctionUtils.dl: params = DeepLearningConfig.params; break; default: System.out.println("Do not implement for algorithm: " + algorithm); } try { invalidMessage = FunctionUtils.validate(params, train_dataset_id, train_dataset, validate_dataset_id, validate_dataset, rawInput); if (FunctionUtils.drf.equals(algorithm)) { notImplMessage = FunctionUtils.checkImplemented(rawInput); } if (StringUtils.isNotEmpty(invalidMessage)) { System.out.println(invalidMessage); Assert.fail(String.format(invalidMessage)); } else if (StringUtils.isNotEmpty(notImplMessage)) { System.out.println(notImplMessage); Assert.fail(String.format(notImplMessage)); } else { // TODO: move modelParameter from here to FunctionUtils modelParameter = FunctionUtils.toModelParameter(params, algorithm, train_dataset_id, validate_dataset_id, train_dataset, validate_dataset, rawInput); FunctionUtils.basicTesting(algorithm, modelParameter, isNegativeTestcase, rawInput); } } catch (AssertionError ae) { testcaseStatus = "FAILED"; throw ae; } finally { // TODO: get memory by H2O's API System.out.println("Total Memory used in testcase:" + (rt.getUsedMemory() / RecordingTestcase.MB) + "MB"); System.out.println("Total Time used in testcase:" + (rt.getTimeRecording()) + "millis"); resetStandardStreams(); testcaseStatus = String.format("Testcase %s %s", rawInput.get(CommonHeaders.testcase_id), testcaseStatus); Reporter.log(testcaseStatus, true); } } @AfterClass public void afterClass() { FunctionUtils.closeAllFrameInDatasetCharacteristic(dataSetCharacteristic); } private static String algorithm = ""; private static String size = null; private static String testcaseId = null; private static HashMap<String, Dataset> dataSetCharacteristic; }
package test; import java.util.HashMap; import java.util.Map; import com.pugwoo.hessoa.client.SOAClient; import com.pugwoo.hessoa.test.api.entity.UserDO; import com.pugwoo.hessoa.test.api.service.ISchoolService; import com.pugwoo.hessoa.test.api.service.IUserService; import test.dto.UserVO; public class TestClient2 { public static void main(String[] args) throws Exception { IUserService userService = SOAClient.getService(IUserService.class); ISchoolService schoolService = SOAClient.getService(ISchoolService.class); System.out.println("userService:" + userService); System.out.println("schoolService:" + schoolService); UserVO userVO = new UserVO(); userVO.setName("nick"); userVO.setScore(99); userVO.setMything("mmm"); Map<Object, UserDO> map = new HashMap<Object, UserDO>(); map.put("nick", userVO); map.put(1, userVO); for(int i = 0; i < 10000; i++) { try { String result = userService.insert(map); System.out.println(i + ":" + result); Thread.sleep(10); } catch (Exception e) { e.printStackTrace(); } } } }
package hexaguin.advancedKinetics; import net.minecraft.block.Block; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.common.Configuration; import net.minecraftforge.common.MinecraftForge; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.PreInit; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.LanguageRegistry; @Mod(modid = AdvancedKinetics.modid, name = "Advanced Kinetics", version = "Beta 0.3") @NetworkMod(clientSideRequired = true, serverSideRequired = false) public class AdvancedKinetics { public static final String modid = "Hexaguin_AdvancedKinetics"; public static Block acceleratorBlock; public static Block launcherBlock; public static Block heartSandBlock; public static Block deflectorBlock; public static Block directionalLauncherBlock; public static int acceleratorID; public static int launcherID; public static int heartSandID; public static int deflectorID; public static int directionalLauncherID; @EventHandler public void preInit(FMLPreInitializationEvent event) { Configuration config = new Configuration(event.getSuggestedConfigurationFile()); config.load(); acceleratorID = config.getBlock("acceleratorID", 530).getInt(); launcherID = config.getBlock("launcherID", 531).getInt(); heartSandID = config.getBlock("heartSandID", 532).getInt(); deflectorID = config.getBlock("deflectorID", 533).getInt(); directionalLauncherID = config.getBlock("directionalLauncherID", 534).getInt(); config.save(); } @EventHandler public void load(FMLInitializationEvent event) { //adding blocks acceleratorBlock = new BlockAcceleratorBlock(acceleratorID,Material.iron) .setUnlocalizedName("acceleratorBlock") .setHardness(1.5F) .setTextureName("hexaguin_advancedkinetics:acceleratorBlock"); GameRegistry.registerBlock(acceleratorBlock, modid + acceleratorBlock.getUnlocalizedName().substring(5)); LanguageRegistry.addName(acceleratorBlock, "Kinetic Accelerator"); MinecraftForge.setBlockHarvestLevel(acceleratorBlock, "pickaxe", 1); launcherBlock = new BlockLauncherBlock(launcherID,Material.glass) .setUnlocalizedName("launcherBlock") .setHardness(3F) .setTextureName("hexaguin_advancedkinetics:launcherBlock"); GameRegistry.registerBlock(launcherBlock, modid + launcherBlock.getUnlocalizedName().substring(5)); LanguageRegistry.addName(launcherBlock, "Kinetic Vertical Velocity Enhancer"); MinecraftForge.setBlockHarvestLevel(launcherBlock, "pickaxe", 1); heartSandBlock = new HeartSandBlock(heartSandID,Material.sand) .setUnlocalizedName("heartSandBlock"); GameRegistry.registerBlock(heartSandBlock, modid + heartSandBlock.getUnlocalizedName().substring(5)); LanguageRegistry.addName(heartSandBlock, "Heartsand [WIP]"); deflectorBlock = new DeflectorBlock(deflectorID,Material.web) .setUnlocalizedName("deflectorBlock"); GameRegistry.registerBlock(deflectorBlock, modid + deflectorBlock.getUnlocalizedName().substring(5)); LanguageRegistry.addName(deflectorBlock, "Kinetic Deflector [WIP and SUPER buggy and broken]"); directionalLauncherBlock = new DirectionalLauncherBlock(directionalLauncherID,Material.glass) .setUnlocalizedName("directionalLauncherBlock") .setHardness(3F) .setTextureName("advancedkinetics:northLauncher"); GameRegistry.registerBlock(directionalLauncherBlock, ItemDirectionalLauncherBlock.class, modid + (directionalLauncherBlock.getUnlocalizedName().substring(5))); LanguageRegistry.addName(new ItemStack(directionalLauncherBlock,1, 0), "Kinetic Northbound Velocity Enhancer"); LanguageRegistry.addName(new ItemStack(directionalLauncherBlock,1, 1), "Kinetic Eastbound Velocity Enhancer"); LanguageRegistry.addName(new ItemStack(directionalLauncherBlock,1, 2), "Kinetic Southbound Velocity Enhancer"); LanguageRegistry.addName(new ItemStack(directionalLauncherBlock,1, 3), "Kinetic Westbound Velocity Enhancer"); MinecraftForge.setBlockHarvestLevel(directionalLauncherBlock, "pickaxe", 1); //adding Recipes ItemStack accelerator = new ItemStack(acceleratorBlock); ItemStack accelerator16 = new ItemStack(acceleratorBlock,16); ItemStack launcher = new ItemStack(launcherBlock); ItemStack northLauncher = new ItemStack(directionalLauncherBlock,1,0); ItemStack eastLauncher = new ItemStack(directionalLauncherBlock,1,1); ItemStack southLauncher = new ItemStack(directionalLauncherBlock,1,2); ItemStack westLauncher = new ItemStack(directionalLauncherBlock,1,3); ItemStack quartz = new ItemStack(Item.netherQuartz); ItemStack redstone = new ItemStack(Item.redstone); ItemStack enderPearl = new ItemStack(Item.enderPearl); ItemStack ironIngot = new ItemStack(Item.ingotIron); GameRegistry.addRecipe(accelerator16, new Object[] { "XYX", "YZY", "XYX", 'X',quartz, 'Y',enderPearl, 'Z',ironIngot }); GameRegistry.addRecipe(launcher, new Object[] { " X ", "YYY", " X ", 'X',enderPearl, 'Y',accelerator }); GameRegistry.addRecipe(northLauncher, new Object[] { "ZX ", " Y ", " ", 'X',enderPearl, 'Y',launcher, 'Z',quartz }); GameRegistry.addRecipe(southLauncher, new Object[] { "Z ", " Y ", " X ", 'X',enderPearl, 'Y',launcher, 'Z',quartz }); GameRegistry.addRecipe(eastLauncher, new Object[] { "Z ", " YX", " ", 'X',enderPearl, 'Y',launcher, 'Z',quartz }); GameRegistry.addRecipe(westLauncher, new Object[] { "Z ", "XY ", " ", 'X',enderPearl, 'Y',launcher, 'Z',quartz }); } }
package slib.platform.android.ui; import android.app.Activity; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Resources; import android.graphics.Color; import android.graphics.Point; import android.graphics.Rect; import android.net.Uri; import android.os.Build; import android.util.DisplayMetrics; import android.view.Display; import android.view.Gravity; import android.view.Surface; import android.view.View; import android.view.Window; import android.view.WindowManager; import java.io.File; import java.lang.reflect.Field; import me.leolin.shortcutbadger.ShortcutBadger; import slib.platform.android.Logger; import slib.platform.android.SlibActivity; import slib.platform.android.helper.FileHelper; public class Util { public static Display getDefaultDisplay(Activity activity) { return activity.getWindowManager().getDefaultDisplay(); } public static Point getDisplaySize(Display display) { Point pt = new Point(); DisplayMetrics metrics; if (display != null) { metrics = new DisplayMetrics(); display.getMetrics(metrics); } else { metrics = Resources.getSystem().getDisplayMetrics(); } pt.x = metrics.widthPixels; pt.y = metrics.heightPixels; return pt; } public static Point getDisplaySize(Activity activity) { return getDisplaySize(getDefaultDisplay(activity)); } public static float getDisplayDensity(Activity activity) { return activity.getResources().getDisplayMetrics().density; } public static int getScreenOrientation(Activity activity) { try { DisplayMetrics metrics; Display display = activity.getWindowManager().getDefaultDisplay(); if (display == null) { return 0; } metrics = new DisplayMetrics(); display.getMetrics(metrics); int rotation = display.getRotation(); int width = metrics.widthPixels; int height = metrics.heightPixels; if (((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) && height > width) || ((rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && width > height)) { switch(rotation) { case Surface.ROTATION_0: return 0; case Surface.ROTATION_90: return 90; case Surface.ROTATION_180: return 180; case Surface.ROTATION_270: return 270; default: break; } } else { switch(rotation) { case Surface.ROTATION_0: return 90; case Surface.ROTATION_90: return 0; case Surface.ROTATION_180: return 270; case Surface.ROTATION_270: return 180; default: break; } } } catch (Exception e) { Logger.exception(e); } return 0; } public static void setScreenOrientations(final Activity activity, final boolean flag0, final boolean flag90, final boolean flag180, final boolean flag270) { if (!(UiThread.isUiThread())) { activity.runOnUiThread(new Runnable() { @Override public void run() { setScreenOrientations(activity, flag0, flag90, flag180, flag270); } }); return; } try { int orientation; if (flag90 || flag270) { if (flag0 || flag180) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { orientation = ActivityInfo.SCREEN_ORIENTATION_FULL_USER; } else { orientation = ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR; } } else if (flag90 && flag270) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { orientation = ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE; } else { orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE; } } else if (flag270) { orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; } else { orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; } } else { if (flag0 && flag180) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { orientation = ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT; } else { orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT; } } else if (flag180) { orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; } else { orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; } } activity.setRequestedOrientation(orientation); } catch (Exception e) { e.printStackTrace(); } } public static Rect getSafeAreaInsets(Activity activity) { if (activity instanceof SlibActivity) { Rect rect = ((SlibActivity)activity).getLatestInsets(); if (rect != null) { return rect; } } Rect rect = new Rect(0, 0, 0, 0); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { try { Window window = activity.getWindow(); if ((window.getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0) { if ((window.getAttributes().flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0 || (window.getDecorView().getSystemUiVisibility() & View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) != 0) { rect.top = getStatusBarHeight(activity); } } } catch (Exception e) { e.printStackTrace(); } } return rect; } public static int getNavigationBarHeight(Activity activity) { try { Class<?> c = Class.forName("com.android.internal.R$dimen"); Object obj = c.newInstance(); Field field = c.getField("navigation_bar_height"); int x = Integer.parseInt(field.get(obj).toString()); return activity.getResources().getDimensionPixelSize(x); } catch (Exception e) { e.printStackTrace(); return 0; } } public static int getStatusBarHeight(Activity activity) { try { Class<?> c = Class.forName("com.android.internal.R$dimen"); Object obj = c.newInstance(); Field field = c.getField("status_bar_height"); int x = Integer.parseInt(field.get(obj).toString()); return activity.getResources().getDimensionPixelSize(x); } catch (Exception e) { e.printStackTrace(); return 0; } } public static final int STATUS_BAR_STYLE_HIDDEN = 0; public static final int STATUS_BAR_STYLE_DARK = 1; public static final int STATUS_BAR_STYLE_LIGHT = 2; public static void setStatusBarStyle(final Activity activity, final int style) { if (!(UiThread.isUiThread())) { activity.runOnUiThread(new Runnable() { @Override public void run() { setStatusBarStyle(activity, style); } }); return; } try { Window window = activity.getWindow(); if (style == STATUS_BAR_STYLE_HIDDEN) { window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); int flagSystemUI = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; if (style == STATUS_BAR_STYLE_DARK) { flagSystemUI |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; } window.getDecorView().setSystemUiVisibility(flagSystemUI); window.setStatusBarColor(Color.TRANSPARENT); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } } } } catch (Exception e) { e.printStackTrace(); } } public static int getAndroidAlignment(int align) { int ret = 0; int horz = align & 3; if (horz == 1) { ret |= Gravity.LEFT; } else if (horz == 2) { ret |= Gravity.RIGHT; } else { ret |= Gravity.CENTER_HORIZONTAL; } int vert = align & 12; if (vert == 4) { ret |= Gravity.TOP; } else if (vert == 8) { ret |= Gravity.BOTTOM; } else { ret |= Gravity.CENTER_VERTICAL; } return ret; } public static int getSlibAlignment(int gravity) { int ret = 0; if ((gravity & Gravity.LEFT) != 0) { ret |= 1; } else if ((gravity & Gravity.RIGHT) != 0) { ret |= 2; } if ((gravity & Gravity.TOP) != 0) { ret |= 4; } else if ((gravity & Gravity.BOTTOM) != 0) { ret |= 8; } return ret; } public static void openURL(final Activity activity, final String url) { activity.runOnUiThread(new Runnable() { @Override public void run() { try { if (url.startsWith("file: File file = new File(url.substring(7)); Uri uri = FileHelper.getUriForFile(activity, file); if (uri == null) { Logger.error("File exposed beyond app: " + file.getAbsolutePath()); return; } Intent intent; if (url.endsWith("jpg") || url.endsWith("jpeg") || url.endsWith("png")) { intent = new Intent(Intent.ACTION_VIEW);
package ar.app.display; import java.awt.*; import java.awt.event.ActionListener; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.util.concurrent.ExecutorService; import ar.*; import ar.app.util.ActionProvider; import ar.app.util.MostRecentOnlyExecutor; import ar.app.util.ZoomPanHandler; import ar.selectors.TouchesPixel; import ar.util.Util; /**Render and display exactly what fits on the screen. */ public class AggregatingDisplay extends ARComponent.Aggregating { protected static final long serialVersionUID = 1L; protected final ActionProvider aggregatesChangedProvider = new ActionProvider(); protected final TransferDisplay display; protected Aggregator<?,?> aggregator; protected Glyphset<?,?> dataset; private AffineTransform renderedTransform = new AffineTransform(); protected volatile boolean fullRender = false; protected volatile boolean renderError = false; protected volatile Aggregates<?> aggregates; protected ExecutorService renderPool = new MostRecentOnlyExecutor(1,"FullDisplay Render Thread"); protected final Renderer renderer; public AggregatingDisplay(Renderer renderer) { super(); this.renderer = renderer; display = new TransferDisplay(renderer); this.setLayout(new BorderLayout()); this.add(display, BorderLayout.CENTER); ZoomPanHandler.installOn(this); } /**Create a new instance. * */ public AggregatingDisplay(Aggregator<?,?> aggregator, Transfer<?,?> transfer, Glyphset<?,?> glyphs, Renderer renderer) { this(renderer); this.aggregator = aggregator; this.dataset = glyphs; display.transfer(transfer); ZoomPanHandler.installOn(this); } protected void finalize() {renderPool.shutdown();} public void addAggregatesChangedListener(ActionListener l) {aggregatesChangedProvider.addActionListener(l);} public Aggregates<?> refAggregates() {return display.refAggregates();} public void refAggregates(Aggregates<?> aggregates) { display.refAggregates(aggregates); } public Renderer renderer() {return renderer;} public Glyphset<?,?> dataset() {return dataset;} public void dataset(Glyphset<?,?> data, Aggregator<?,?> aggregator, Transfer<?,?> transfer) { this.dataset = data; this.aggregator = aggregator; this.transfer(transfer); aggregates(null, null); fullRender = true; renderError = false; this.repaint(); } public Transfer<?,?> transfer() {return display.transfer();} public void transfer(Transfer<?,?> t) { display.transfer(t); } public Aggregator<?,?> aggregator() {return aggregator;} public Aggregates<?> transferAggregates() {return display.transferAggregates();} public Aggregates<?> aggregates() {return aggregates;} public void aggregates(Aggregates<?> aggregates, AffineTransform renderedTransform) { display.aggregates(aggregates, renderedTransform); display.refAggregates(null); this.renderedTransform=renderedTransform; this.aggregates = aggregates; fullRender=false; aggregatesChangedProvider.fireActionListeners(); } public void renderAgain() { fullRender=true; renderError=false; repaint(); } public void paintComponent(Graphics g) { Runnable action = null; if (renderer == null || dataset == null || dataset.isEmpty() || aggregator == null || renderError == true) { g.setColor(Color.GRAY); g.fillRect(0, 0, this.getWidth(), this.getHeight()); } else if (fullRender) { action = new AggregateRender(); renderPool.execute(action); fullRender = false; } } public String toString() {return String.format("AggregatingDisplay[Dataset: %1$s, Transfer: %2$s]", dataset, display.transfer(), aggregator);} /**Use this transform to convert values from the absolute system * to the screen system. */ @Override public AffineTransform viewTransform() {return display.viewTransform();} @Override public AffineTransform renderTransform() {return new AffineTransform(renderedTransform);} @Override public void viewTransform(AffineTransform vt, boolean provisional) { //Only force full re-render if the zoom factor changed non-provisionally fullRender = !provisional && (renderedTransform == null || vt.getScaleX() != renderedTransform.getScaleX() || vt.getScaleY() != renderedTransform.getScaleY()); display.viewTransform(vt, provisional); repaint(); } public void zoomFit() { try { Rectangle2D content = (dataset == null ? null : dataset().bounds()); if (content ==null || content.isEmpty()) {return;} AffineTransform vt = Util.zoomFit(content, getWidth(), getHeight()); viewTransform(vt, false); } catch (Exception e) {} //Ignore all zoom-fit errors...they are usually caused by under-specified state } public Rectangle2D dataBounds() {return dataset.bounds();} private final class AggregateRender implements Runnable { public void run() { long start = System.currentTimeMillis(); try { AffineTransform vt = viewTransform(); Rectangle databounds = vt.createTransformedShape(dataset.bounds()).getBounds(); AffineTransform rt = Util.zoomFit(dataset.bounds(), databounds.width, databounds.height); rt.scale(vt.getScaleX()/rt.getScaleX(), vt.getScaleY()/rt.getScaleY()); @SuppressWarnings({"rawtypes"}) Selector selector = TouchesPixel.make(dataset); @SuppressWarnings({"unchecked","rawtypes"}) Aggregates<?> a = renderer.aggregate(dataset, selector, (Aggregator) aggregator, rt, databounds.width, databounds.height); AggregatingDisplay.this.aggregates(a, rt); long end = System.currentTimeMillis(); if (PERFORMANCE_REPORTING) { System.out.printf("%d ms (Base aggregates render on %d x %d grid)\n", (end-start), aggregates.highX()-aggregates.lowX(), aggregates.highY()-aggregates.lowY()); } } catch (Exception e) { renderError = true; String msg = e.getMessage() == null ? e.getClass().getName() : e.getMessage(); System.err.println(msg); e.printStackTrace(); } AggregatingDisplay.this.repaint(); } } }
package web.component.api.model; /** * * @author Hiroshi */ public interface LoadBalancerListener { public void setInstancePort(int instancePort); public void setServicePort(int servciePort); public Integer getInstancePort(); public Integer getServicePort(); public void setInstanceProtocol(String instanceProtocol); public void setServiceProtocol(String serviceProtocol); public String getInstanceProtocol(); public String getServiceProtocol(); public void setServerCertificate(String serverCertificateId); public LoadBalancer getLoadBalancer(); /* * Add this load balancer listener to load balancer. */ public void addTo(LoadBalancer lb); /* * Delete this load balancer listener from load balancer, and return the load balancer instance. * If this listener is not attached to any load balancer, return null. */ public LoadBalancer delete(); }
package lab3_progra2; import java.util.ArrayList; import java.util.Date; import javax.swing.JOptionPane; /** * * @author Franklin Garcia */ public class Lab3_progra2 { /** * @param args the command line arguments */ public static void main(String[] args) { String opcion = ""; ArrayList<Pueblo> lista_pueblo = new ArrayList(); ArrayList<Bestia> lista_bestias = new ArrayList(); while (!opcion.equalsIgnoreCase("5")) { opcion = JOptionPane.showInputDialog("Ingrese opcion \n" + "1-Agregar \n" + "2-Eliminar \n" + "3-Modificar \n" + "4-Batalla \n" + "5-Salir \n"); switch (opcion) { case "1": {//agregar String opcion1 = JOptionPane.showInputDialog("Ingrese opcion \n" + "1-Agregar pueblos \n" + "2-Agregar lugares \n" + "3-Agregar Integrantes \n" + "4-Agregar bestias"); switch (opcion1) { case "1": {//pueblos String nombre = JOptionPane.showInputDialog("Ingrese nombre"); lista_pueblo.add(new Pueblo(nombre)); JOptionPane.showMessageDialog(null, "Hecho"); } break; case "2": {//lugares String pueblos = ""; for (Pueblo p : lista_pueblo) { pueblos += "\n" + lista_pueblo.indexOf(p) + " " + p; } int op = Integer.parseInt(JOptionPane.showInputDialog(pueblos + "\n" + "Ingrese opcion")); String l = JOptionPane.showInputDialog("Ingrese tipo de lugar \n" + "1-Comarca \n" + "2-Gondor \n" + "3-Mordor \n"); switch (l) { case "1": {//comarca int casas = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero de casas")); int extension = Integer.parseInt(JOptionPane.showInputDialog("Extension territorio")); int numero = Integer.parseInt(JOptionPane.showInputDialog("numero de integrantes")); lista_pueblo.get(op).getLugares().add(new Comarca(casas, extension, numero)); JOptionPane.showMessageDialog(null, "Hecho"); } break; case "2": {//Gondor int parajes = Integer.parseInt(JOptionPane.showInputDialog("Parajes")); int extension = Integer.parseInt(JOptionPane.showInputDialog("Extension territorio")); int numero = Integer.parseInt(JOptionPane.showInputDialog("numero de integrantes")); lista_pueblo.get(op).getLugares().add(new Gondor(parajes, extension, numero)); JOptionPane.showMessageDialog(null, "Hecho"); } break; case "3": {//Mordor int guardianes = Integer.parseInt(JOptionPane.showInputDialog("Numero guardianes")); int extension = Integer.parseInt(JOptionPane.showInputDialog("Extension territorio")); int numero = Integer.parseInt(JOptionPane.showInputDialog("numero de integrantes")); lista_pueblo.get(op).getLugares().add(new Mordor(guardianes, extension, numero)); JOptionPane.showMessageDialog(null, "Hecho"); } break; } } break; case "3": {//Integrantes String p = ""; for (Pueblo i : lista_pueblo) { p += "\n" + lista_pueblo.indexOf(i) + " " + i; } int pueblo = Integer.parseInt(JOptionPane.showInputDialog(p + "\n" + "Ingrese Opcion de pueblo")); String l = ""; for (Lugar i : lista_pueblo.get(pueblo).getLugares()) { l += "\n" + lista_pueblo.get(pueblo).getLugares().indexOf(i) + " " + i; } int lugar = Integer.parseInt(JOptionPane.showInputDialog(l + "\n" + "Ingrese opcion de lugar")); String o = JOptionPane.showInputDialog("Ingrese opcion \n" + "1-Elfos \n" + "2-Enanos \n" + "3-Hobbits \n" + "4-Hombre \n" + "5-Maiar \n"); switch (o) { case "1": {//Elfos String nombre = JOptionPane.showInputDialog("Ingrese nombre"); String Apellido = JOptionPane.showInputDialog("Apellido"); double altura = Double.parseDouble(JOptionPane.showInputDialog("altura")); Date fecha_nacimiento = new Date(); String b = ""; for (Bestia u : lista_bestias) { b += "\n" + lista_bestias.indexOf(u) + " " + u; } int be = Integer.parseInt(JOptionPane.showInputDialog(b + "\n" + "Cual bestia")); Bestia bestia = lista_bestias.get(be); double ataque = Double.parseDouble(JOptionPane.showInputDialog("ataque")); boolean arma = false; String army = JOptionPane.showInputDialog("Tiene arma \n" + "1-si \n" + "2-No \n"); if (army.equals("1")) { arma = true; lista_pueblo.get(pueblo).getLugares().get(lugar).getIntegrante().add(new Elfos( arma, nombre, Apellido, altura, fecha_nacimiento, bestia, ataque, 443.00 + 10, 150.00 + 10, 335.00 + 10 )); } else { arma = false; lista_pueblo.get(pueblo).getLugares().get(lugar).getIntegrante().add(new Elfos( arma, nombre, Apellido, altura, fecha_nacimiento, bestia, ataque, 443.00, 150.00, 335.00 )); } JOptionPane.showMessageDialog(null, "Hecho"); } break; case "2": {//enanos String nombre = JOptionPane.showInputDialog("Ingrese nombre"); String Apellido = JOptionPane.showInputDialog("Apellido"); double altura = Double.parseDouble(JOptionPane.showInputDialog("altura")); Date fecha_nacimiento = new Date(); String b = ""; for (Bestia u : lista_bestias) { b += "\n" + lista_bestias.indexOf(u) + " " + u; } int be = Integer.parseInt(JOptionPane.showInputDialog(b + "\n" + "Cual bestia")); Bestia bestia = lista_bestias.get(be);//Hay que hacer la bestia primero double poder = Double.parseDouble(JOptionPane.showInputDialog("poder")); boolean barba = false; boolean hacha = false; Double ataque = 300.00, defensa = 200.00, curacion = 50.00; String Bar = JOptionPane.showInputDialog("Tiene barba \n" + "1-Si \n" + "2-No \n"); if (Bar.equals("1")) { ataque = ataque + 50; defensa = defensa + 50; curacion = curacion + 50; barba = true; } else { barba = false; } String ha = JOptionPane.showInputDialog("Tenemos hacha \n" + "1-si \n" + "2-No \n"); if (ha.equals("1")) { ataque = ataque + 50; defensa = defensa + 50; curacion = curacion + 50; hacha = true; } else { barba = false; } lista_pueblo.get(pueblo).getLugares().get(lugar).getIntegrante().add( new Enanos(barba, hacha, nombre, Apellido, altura, fecha_nacimiento, bestia, poder, ataque, defensa, curacion)); JOptionPane.showMessageDialog(null, "hecho"); } break; case "3": {//Hobits String nombre = JOptionPane.showInputDialog("Ingrese nombre"); String Apellido = JOptionPane.showInputDialog("Apellido"); double altura = Double.parseDouble(JOptionPane.showInputDialog("altura")); Date fecha_nacimiento = new Date(); String b = ""; for (Bestia u : lista_bestias) { b += "\n" + lista_bestias.indexOf(u) + " " + u; } int be = Integer.parseInt(JOptionPane.showInputDialog(b + "\n" + "Cual bestia")); Bestia bestia = lista_bestias.get(be); double poder = Double.parseDouble(JOptionPane.showInputDialog("poder")); int anillo = Integer.parseInt(JOptionPane.showInputDialog("Numero anillos")); lista_pueblo.get(pueblo).getLugares().get(lugar).getIntegrante().add(new Hobits(anillo, nombre, Apellido, altura, fecha_nacimiento, bestia, poder, 10.00 * anillo, 100.00 * anillo, 1.00 * anillo)); } break; case "4": {//Hombre String nombre = JOptionPane.showInputDialog("Ingrese nombre"); String Apellido = JOptionPane.showInputDialog("Apellido"); double altura = Double.parseDouble(JOptionPane.showInputDialog("altura")); Date fecha_nacimiento = new Date(); String b = ""; for (Bestia u : lista_bestias) { b += "\n" + lista_bestias.indexOf(u) + " " + u; } int be = Integer.parseInt(JOptionPane.showInputDialog(b + "\n" + "Cual bestia")); Bestia bestia = lista_bestias.get(be); double poder = Double.parseDouble(JOptionPane.showInputDialog("poder")); double ataque = 150; double defensa = 140; double curación = 50; int army = Integer.parseInt(JOptionPane.showInputDialog("Arma \n" + "1-Espada \n" + "2-Lanza \n" + "3-arco")); if (army == 1) { ataque = ataque + 150; } else if (army == 2) { ataque = ataque + 100; } else if (army == 3) { ataque = ataque + 50; } lista_pueblo.get(pueblo).getLugares().get(lugar).getIntegrante().add(new Hombres()); JOptionPane.showMessageDialog(null, "Hecho"); } break; case "5": {//Maiar String nombre = JOptionPane.showInputDialog("Ingrese nombre"); String Apellido = JOptionPane.showInputDialog("Apellido"); double altura = Double.parseDouble(JOptionPane.showInputDialog("altura")); Date fecha_nacimiento = new Date(); String b = ""; for (Bestia u : lista_bestias) { b += "\n" + lista_bestias.indexOf(u) + " " + u; } int be = Integer.parseInt(JOptionPane.showInputDialog(b + "\n" + "Cual bestia")); Bestia bestia = lista_bestias.get(be); double poder = Double.parseDouble(JOptionPane.showInputDialog("poder")); double ataque = 150; double defensa = 140; double curación = 50; int sombrero = Integer.parseInt(JOptionPane.showInputDialog("Tiene sombrero \n" + "1-si \n" + "2-no \n")); if (sombrero == 1) { curación = curación + 200; ataque = ataque + 200; } int baston = Integer.parseInt(JOptionPane.showInputDialog("Tiene baston \n" + "1-si \n" + "2-no \n")); if (baston == 1) { ataque = ataque + 200; } lista_pueblo.get(pueblo).getLugares().get(lugar).getIntegrante().add(new Maiar(baston, sombrero, nombre, Apellido, altura, fecha_nacimiento, bestia, poder, ataque, defensa, curación)); JOptionPane.showMessageDialog(null, "Hecho"); } break; } } case "4": {//Bestias String op = JOptionPane.showInputDialog("Ingrese opcion \n" + "1-Aguilas \n" + "2-Arañas \n" + "3-Balrogs \n" + "4-Bestias Aladas \n" + "5-Dragones \n"); switch (op) {//Aguilas case "1": { int garras = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero garras")); Boolean veneno = false; String ven = JOptionPane.showInputDialog("Tiene veneno \n" + "1-Si \n" + "2-No \n"); if (ven.equals("1")) { veneno = true; } else { veneno = false; } int defensa = Integer.parseInt(JOptionPane.showInputDialog("Nivel de defensa")); int ataque = Integer.parseInt(JOptionPane.showInputDialog("Nivel ataque")); int vida = Integer.parseInt(JOptionPane.showInputDialog("Vida")); int curacion = Integer.parseInt(JOptionPane.showInputDialog("Nivel de curacion")); String color = JOptionPane.showInputDialog("Color?"); lista_bestias.add(new Aguilas(color, garras, veneno, vida, defensa, ataque, curacion)); JOptionPane.showMessageDialog(null, "Hecho"); } break; case "2": { int garras = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero garras")); Boolean veneno = false; String ven = JOptionPane.showInputDialog("Tiene veneno \n" + "1-Si \n" + "2-No \n"); if (ven.equals("1")) { veneno = true; } else { veneno = false; } int defensa = Integer.parseInt(JOptionPane.showInputDialog("Nivel de defensa")); int ataque = Integer.parseInt(JOptionPane.showInputDialog("Nivel ataque")); int vida = Integer.parseInt(JOptionPane.showInputDialog("Vida")); int curacion = Integer.parseInt(JOptionPane.showInputDialog("Nivel de curacion")); String sexo = JOptionPane.showInputDialog("sexo"); if (sexo.equals("femenino")) { vida += 50; } lista_bestias.add(new Arañas(sexo, garras, veneno, vida, defensa, ataque, curacion)); JOptionPane.showMessageDialog(null, "Hecho"); } break; case "3": {//Balrogs int garras = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero garras")); Boolean veneno = false; String ven = JOptionPane.showInputDialog("Tiene veneno \n" + "1-Si \n" + "2-No \n"); if (ven.equals("1")) { veneno = true; } else { veneno = false; } int defensa = Integer.parseInt(JOptionPane.showInputDialog("Nivel de defensa")); int ataque = Integer.parseInt(JOptionPane.showInputDialog("Nivel ataque")); int vida = Integer.parseInt(JOptionPane.showInputDialog("Vida")); int curacion = Integer.parseInt(JOptionPane.showInputDialog("Nivel de curacion")); Boolean latigo; String l = JOptionPane.showInputDialog("Tienen latigo \n" + "1-si \n" + "2-no \n"); if (l.equals("1")) { latigo = true; } else { latigo = false; } lista_bestias.add(new Balrogs(latigo, garras, veneno, vida, defensa, ataque, curacion)); JOptionPane.showMessageDialog(null, "Hecho"); } break; case "4": {//Bestias aladas int garras = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero garras")); Boolean veneno = false; String ven = JOptionPane.showInputDialog("Tiene veneno \n" + "1-Si \n" + "2-No \n"); if (ven.equals("1")) { veneno = true; } else { veneno = false; } int defensa = Integer.parseInt(JOptionPane.showInputDialog("Nivel de defensa")); int ataque = Integer.parseInt(JOptionPane.showInputDialog("Nivel ataque")); int vida = Integer.parseInt(JOptionPane.showInputDialog("Vida")); int curacion = Integer.parseInt(JOptionPane.showInputDialog("Nivel de curacion")); double velocidad = Double.parseDouble(JOptionPane.showInputDialog("Velocidad")); lista_bestias.add(new BestiasAladas(velocidad, garras, veneno, defensa, ataque, vida, curacion)); JOptionPane.showMessageDialog(null, "velocidad"); } break; case "5": {//Dragones int garras = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero garras")); Boolean veneno = false; String ven = JOptionPane.showInputDialog("Tiene veneno \n" + "1-Si \n" + "2-No \n"); if (ven.equals("1")) { veneno = true; } else { veneno = false; } int defensa = Integer.parseInt(JOptionPane.showInputDialog("Nivel de defensa")); int ataque = Integer.parseInt(JOptionPane.showInputDialog("Nivel ataque")); int vida = Integer.parseInt(JOptionPane.showInputDialog("Vida")); int curacion = Integer.parseInt(JOptionPane.showInputDialog("Nivel de curacion")); double long_ala = Double.parseDouble(JOptionPane.showInputDialog("lon ala")); lista_bestias.add(new Dragones(long_ala, garras, veneno, defensa, ataque, vida, curacion)); JOptionPane.showMessageDialog(null, "hecho"); } break; } } break; } } break; case "2": {//eliminar String r = JOptionPane.showInputDialog(null, "1-Eliminar Pueblo \n" + "2-Eliminar Bestia \n" + "3-Elimianr lugares \n" + "4-Eliminar integrante \n" ); int re = Integer.parseInt(r); switch (re) { case 1: String resp; int cont = 0; JOptionPane.showMessageDialog(null, "A Continuacion se le muestran los pueblos"); for (Pueblo lp : lista_pueblo) { JOptionPane.showMessageDialog(null, "[" + cont + "]" + lp); cont++; } resp = JOptionPane.showInputDialog(null, "Que posicion desea eliminar?"); int respp = Integer.parseInt(resp); lista_pueblo.remove(respp); break; case 2: String resp1; int cont1 = 0; JOptionPane.showMessageDialog(null, "A Continuacion se le muestran los pueblos"); for (Bestia lb : lista_bestias) { JOptionPane.showMessageDialog(null, "[" + cont1 + "]" + lb); for (Bestia lp : lista_bestias) { JOptionPane.showMessageDialog(null, "[" + cont1 + "]" + lp); cont1++; } resp1 = JOptionPane.showInputDialog(null, "Que posicion desea eliminar?"); int respp1 = Integer.parseInt(resp1); lista_bestias.remove(respp1); break; } case 3: { String e = ""; for (Pueblo t : lista_pueblo) { e += "\n" + lista_pueblo.indexOf(t) + " " + t; } int pue = Integer.parseInt(JOptionPane.showInputDialog(e + "\n" + "Cual pueblo")); String t = ""; for (Lugar i : lista_pueblo.get(pue).getLugares()) { t += "\n" + lista_pueblo.get(pue).getLugares().indexOf(i) + " " + i; } int el = Integer.parseInt(JOptionPane.showInputDialog(t + "\n" + "Cual lugar")); lista_pueblo.get(pue).getLugares().remove(el); JOptionPane.showMessageDialog(null, "Hecho"); } break; case 4: { String e = ""; for (Pueblo t : lista_pueblo) { e += "\n" + lista_pueblo.indexOf(t) + " " + t; } int pue = Integer.parseInt(JOptionPane.showInputDialog(e + "\n" + "Cual pueblo")); String t = ""; for (Lugar i : lista_pueblo.get(pue).getLugares()) { t += "\n" + lista_pueblo.get(pue).getLugares().indexOf(i) + " " + i; } int el = Integer.parseInt(JOptionPane.showInputDialog(t + "\n" + "Cual lugar")); String u = ""; for (Integrante i : lista_pueblo.get(pue).getLugares().get(el).getIntegrante()) { u += "\n" + lista_pueblo.get(pue).getLugares().get(el).getIntegrante().indexOf(i) + " " + i; } int y = Integer.parseInt(JOptionPane.showInputDialog(u + "\n" + "Cual integrante")); lista_pueblo.get(pue).getLugares().get(el).getIntegrante().remove(y); JOptionPane.showMessageDialog(null, "Hecho"); } break; } } break; ////////////////////////////////////////////////////////////////777 / case "3": {//Modificar int contad = 0; int contad2 = 0; String respuesta; String respuesta2; String respuesta22; String respuesta3; String modif; String modif2; int respu; int respu2; int respu22; int respu3; int mod; int mod2; String modpueblo; respuesta = JOptionPane.showInputDialog(null, "1-Para modificar Pueblos \n" + "2-Para modificar Bestias \n" + "3-Para modificar Integrante \n"); respu = Integer.parseInt(respuesta); switch (respu) { case 1: for (Pueblo mp : lista_pueblo) { JOptionPane.showMessageDialog(null, "[" + contad2 + "]" + mp); contad2++; } respuesta22 = JOptionPane.showInputDialog(null, "Ingrese la posicion del pueblo que desea modificar"); respu22 = Integer.parseInt(respuesta22); modpueblo = JOptionPane.showInputDialog(null, "Ingrese nuevo nombre del pueblo"); lista_pueblo.get(respu22).setNombre(modpueblo); break; case 2: for (Bestia mb : lista_bestias) { JOptionPane.showMessageDialog(null, "[" + contad + "]" + mb); contad++; } respuesta2 = JOptionPane.showInputDialog(null, "Ingrese la posicion de la bestia que desea modificar"); respu2 = Integer.parseInt(respuesta2); respuesta3 = JOptionPane.showInputDialog(null, "1-Modificar garras \n " + "2-Modificar veneno"); respu3 = Integer.parseInt(respuesta3); if (respu3 == 1) { modif = JOptionPane.showInputDialog(null, "Cuantas garras desea"); mod = Integer.parseInt(modif); if (mod < 6) { lista_bestias.get(respu).setGarras(mod); } else { JOptionPane.showMessageDialog(null, "No puede tener mas de 6 gradas"); } } if (respu3 == 2) { modif2 = JOptionPane.showInputDialog(null, "1-Veneno\n" + "2-Sin veneno"); mod2 = Integer.parseInt(modif2); if (mod2 == 1) { lista_bestias.get(respu2).setVeneno(Boolean.TRUE); } else if (mod2 == 2) { lista_bestias.get(respu2).setVeneno(Boolean.FALSE); } } break; case 3: { String modp; int imodp; String modp2; int imodp2; String modp1; String modp11; String modificar; String modificaral; String modificarap; int modificaral1; int imodp1; int modp121; JOptionPane.showMessageDialog(null, "Acontinuacion los pueblos"); for (Pueblo mi : lista_pueblo) { JOptionPane.showMessageDialog(null, mi); } modp = JOptionPane.showInputDialog(null, "Ingrese la posicion del pueblo que desea modificar"); imodp = Integer.parseInt(modp); for (Lugar mip : lista_pueblo.get(imodp).getLugares()) { JOptionPane.showMessageDialog(null, mip); } modp1 = JOptionPane.showInputDialog(null, "Ingrese la posicion del lugar que desea modificar"); imodp1 = Integer.parseInt(modp); for (Integrante mip1 : lista_pueblo.get(imodp).getLugares().get(imodp1).getIntegrante()) { JOptionPane.showMessageDialog(null, mip1); } modp2 = JOptionPane.showInputDialog(null, "Ingrese la posicion del integrante que desea modificar"); imodp2 = Integer.parseInt(modp2); modp11 = JOptionPane.showInputDialog(null, "1-Modificar nombre" + "2-Mofificar altura" + "3-Modificar apellido"); modp121 = Integer.parseInt(modp11); switch (modp121) { case 1: { modificar = JOptionPane.showInputDialog(null, "Ingrese el nombre al que desea modificar"); lista_pueblo.get(imodp).getLugares().get(imodp1).getIntegrante().get(imodp2).setNombre(modificar); } break; case 2: { modificaral = JOptionPane.showInputDialog(null, "Ingrese la altura al que desea modificar"); modificaral1 = Integer.parseInt(modificaral); lista_pueblo.get(imodp).getLugares().get(imodp1).getIntegrante().get(imodp2).setAltura(modificaral1); } break; case 3: { modificarap = JOptionPane.showInputDialog(null, "Ingrese el apellido al que desea modificar"); lista_pueblo.get(imodp).getLugares().get(imodp1).getIntegrante().get(imodp2).setApellido(modificarap); } break; } } break; } } break; case "4": {//simulacion String f = JOptionPane.showInputDialog("1-simulacion unica \n" + "2-Simulacion lineal \n"); switch (f) { case "1": {//batalla unica String el = ""; for (Pueblo p : lista_pueblo) { el += "\n" + lista_pueblo.indexOf(p) + " " + p; } int lug = Integer.parseInt(JOptionPane.showInputDialog(el + "\n" + "cual lugar")); String e = ""; for (Lugar j : lista_pueblo.get(lug).getLugares()) { e += "\n" + lista_pueblo.get(lug).getLugares().indexOf(j) + " " + j; } int r = Integer.parseInt(JOptionPane.showInputDialog(e + "\n" + "Cual lugar")); String t = ""; for (Integrante j : lista_pueblo.get(lug).getLugares().get(r).getIntegrante()) { t += "\n" + lista_pueblo.get(lug).getLugares().get(r).getIntegrante().indexOf(j) + " " + j; } int Integrante1 = Integer.parseInt(JOptionPane.showInputDialog(t + "\n" + "Cual integrante")); String el1 = ""; for (Pueblo p : lista_pueblo) { el1 += "\n" + lista_pueblo.indexOf(p) + " " + p; } int lug1 = Integer.parseInt(JOptionPane.showInputDialog(el1 + "\n" + "cual lugar")); String e1 = ""; for (Lugar j : lista_pueblo.get(lug1).getLugares()) { e1 += "\n" + lista_pueblo.get(lug1).getLugares().indexOf(j) + " " + j; } int r1 = Integer.parseInt(JOptionPane.showInputDialog(e + "\n" + "Cual lugar")); String t1 = ""; for (Integrante j : lista_pueblo.get(lug1).getLugares().get(r1).getIntegrante()) { t1 += "\n" + lista_pueblo.get(lug1).getLugares().get(r1).getIntegrante().indexOf(j) + " " + j; } int Integrante2 = Integer.parseInt(JOptionPane.showInputDialog(t1 + "\n" + "Cual integrante")); } break; case "2":{//batalla lineal }break; } } break; } } } }
package lab3_progra2; import java.util.ArrayList; import java.util.Date; import javax.swing.JOptionPane; /** * * @author Franklin Garcia */ public class Lab3_progra2 { /** * @param args the command line arguments */ public static void main(String[] args) { String opcion = ""; ArrayList<Pueblo> lista_pueblo = new ArrayList(); ArrayList<Bestia> lista_bestias = new ArrayList(); while (!opcion.equalsIgnoreCase("5")) { opcion = JOptionPane.showInputDialog("Ingrese opcion \n" + "1-Agregar \n" + "2-Eliminar \n" + "3-Modificar \n" + "4-Batalla \n" + "5-Salir \n"); switch (opcion) { case "1": {//agregar String opcion1 = JOptionPane.showInputDialog("Ingrese opcion \n" + "1-Agregar pueblos \n" + "2-Agregar lugares \n" + "3-Agregar Integrantes \n" + "4-Agregar bestias"); switch (opcion1) { case "1": {//pueblos String nombre = JOptionPane.showInputDialog("Ingrese nombre"); lista_pueblo.add(new Pueblo(nombre)); JOptionPane.showMessageDialog(null, "Hecho"); } break; case "2": {//lugares String pueblos = ""; for (Pueblo p : lista_pueblo) { pueblos += "\n" + lista_pueblo.indexOf(p) + " " + p; } int op = Integer.parseInt(JOptionPane.showInputDialog(pueblos + "\n" + "Ingrese opcion")); String l = JOptionPane.showInputDialog("Ingrese tipo de lugar \n" + "1-Comarca \n" + "2-Gondor \n" + "3-Mordor \n"); switch (l) { case "1": {//comarca int casas = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero de casas")); int extension = Integer.parseInt(JOptionPane.showInputDialog("Extension territorio")); int numero = Integer.parseInt(JOptionPane.showInputDialog("numero de integrantes")); lista_pueblo.get(op).getLugares().add(new Comarca(casas, extension, numero)); JOptionPane.showMessageDialog(null, "Hecho"); } break; case "2": {//Gondor int parajes = Integer.parseInt(JOptionPane.showInputDialog("Parajes")); int extension = Integer.parseInt(JOptionPane.showInputDialog("Extension territorio")); int numero = Integer.parseInt(JOptionPane.showInputDialog("numero de integrantes")); lista_pueblo.get(op).getLugares().add(new Gondor(parajes, extension, numero)); JOptionPane.showMessageDialog(null, "Hecho"); } break; case "3": {//Mordor int guardianes = Integer.parseInt(JOptionPane.showInputDialog("Numero guardianes")); int extension = Integer.parseInt(JOptionPane.showInputDialog("Extension territorio")); int numero = Integer.parseInt(JOptionPane.showInputDialog("numero de integrantes")); lista_pueblo.get(op).getLugares().add(new Mordor(guardianes, extension, numero)); JOptionPane.showMessageDialog(null, "Hecho"); } break; } } break; case "3": {//Integrantes String p = ""; for (Pueblo i : lista_pueblo) { p += "\n" + lista_pueblo.indexOf(i) + " " + i; } int pueblo = Integer.parseInt(JOptionPane.showInputDialog(p + "\n" + "Ingrese Opcion de pueblo")); String l = ""; for (Lugar i : lista_pueblo.get(pueblo).getLugares()) { l += "\n" + lista_pueblo.get(pueblo).getLugares().indexOf(i) + " " + i; } int lugar = Integer.parseInt(JOptionPane.showInputDialog(l + "\n" + "Ingrese opcion de lugar")); String o = JOptionPane.showInputDialog("Ingrese opcion \n" + "1-Elfos \n" + "2-Enanos \n" + "3-Hobbits \n" + "4-Hombre \n" + "5-Maiar \n"); switch (o) { case "1": {//Elfos String nombre = JOptionPane.showInputDialog("Ingrese nombre"); String Apellido = JOptionPane.showInputDialog("Apellido"); double altura = Double.parseDouble(JOptionPane.showInputDialog("altura")); Date fecha_nacimiento = new Date(); String b = ""; for (Bestia u : lista_bestias) { b += "\n" + lista_bestias.indexOf(u) + " " + u; } int be = Integer.parseInt(JOptionPane.showInputDialog(b + "\n" + "Cual bestia")); Bestia bestia = lista_bestias.get(be); double ataque = Double.parseDouble(JOptionPane.showInputDialog("ataque")); boolean arma = false; String army = JOptionPane.showInputDialog("Tiene arma \n" + "1-si \n" + "2-No \n"); if (army.equals("1")) { arma = true; lista_pueblo.get(pueblo).getLugares().get(lugar).getIntegrante().add(new Elfos( arma, nombre, Apellido, altura, fecha_nacimiento, bestia, ataque, 443.00 + 10, 150.00 + 10, 335.00 + 10 )); } else { arma = false; lista_pueblo.get(pueblo).getLugares().get(lugar).getIntegrante().add(new Elfos( arma, nombre, Apellido, altura, fecha_nacimiento, bestia, ataque, 443.00, 150.00, 335.00 )); } JOptionPane.showMessageDialog(null, "Hecho"); } break; case "2": {//enanos String nombre = JOptionPane.showInputDialog("Ingrese nombre"); String Apellido = JOptionPane.showInputDialog("Apellido"); double altura = Double.parseDouble(JOptionPane.showInputDialog("altura")); Date fecha_nacimiento = new Date(); String b = ""; for (Bestia u : lista_bestias) { b += "\n" + lista_bestias.indexOf(u) + " " + u; } int be = Integer.parseInt(JOptionPane.showInputDialog(b + "\n" + "Cual bestia")); Bestia bestia = lista_bestias.get(be);//Hay que hacer la bestia primero double poder = Double.parseDouble(JOptionPane.showInputDialog("poder")); boolean barba = false; boolean hacha = false; Double ataque = 300.00, defensa = 200.00, curacion = 50.00; String Bar = JOptionPane.showInputDialog("Tiene barba \n" + "1-Si \n" + "2-No \n"); if (Bar.equals("1")) { ataque = ataque + 50; defensa = defensa + 50; curacion = curacion + 50; barba = true; } else { barba = false; } String ha = JOptionPane.showInputDialog("Tenemos hacha \n" + "1-si \n" + "2-No \n"); if (ha.equals("1")) { ataque = ataque + 50; defensa = defensa + 50; curacion = curacion + 50; hacha = true; } else { barba = false; } lista_pueblo.get(pueblo).getLugares().get(lugar).getIntegrante().add( new Enanos(barba, hacha, nombre, Apellido, altura, fecha_nacimiento, bestia, poder, ataque, defensa, curacion)); JOptionPane.showMessageDialog(null, "hecho"); } break; case "3": {//Hobits String nombre = JOptionPane.showInputDialog("Ingrese nombre"); String Apellido = JOptionPane.showInputDialog("Apellido"); double altura = Double.parseDouble(JOptionPane.showInputDialog("altura")); Date fecha_nacimiento = new Date(); String b = ""; for (Bestia u : lista_bestias) { b += "\n" + lista_bestias.indexOf(u) + " " + u; } int be = Integer.parseInt(JOptionPane.showInputDialog(b + "\n" + "Cual bestia")); Bestia bestia = lista_bestias.get(be); double poder = Double.parseDouble(JOptionPane.showInputDialog("poder")); int anillo = Integer.parseInt(JOptionPane.showInputDialog("Numero anillos")); lista_pueblo.get(pueblo).getLugares().get(lugar).getIntegrante().add(new Hobits(anillo, nombre, Apellido, altura, fecha_nacimiento, bestia, poder, 10.00 * anillo, 100.00 * anillo, 1.00 * anillo)); } break; case "4": {//Hombre String nombre = JOptionPane.showInputDialog("Ingrese nombre"); String Apellido = JOptionPane.showInputDialog("Apellido"); double altura = Double.parseDouble(JOptionPane.showInputDialog("altura")); Date fecha_nacimiento = new Date(); String b = ""; for (Bestia u : lista_bestias) { b += "\n" + lista_bestias.indexOf(u) + " " + u; } int be = Integer.parseInt(JOptionPane.showInputDialog(b + "\n" + "Cual bestia")); Bestia bestia = lista_bestias.get(be); double poder = Double.parseDouble(JOptionPane.showInputDialog("poder")); double ataque = 150; double defensa = 140; double curación = 50; int army = Integer.parseInt(JOptionPane.showInputDialog("Arma \n" + "1-Espada \n" + "2-Lanza \n" + "3-arco")); if (army == 1) { ataque = ataque + 150; } else if (army == 2) { ataque = ataque + 100; } else if (army == 3) { ataque = ataque + 50; } lista_pueblo.get(pueblo).getLugares().get(lugar).getIntegrante().add(new Hombres()); JOptionPane.showMessageDialog(null, "Hecho"); } break; case "5": {//Maiar String nombre = JOptionPane.showInputDialog("Ingrese nombre"); String Apellido = JOptionPane.showInputDialog("Apellido"); double altura = Double.parseDouble(JOptionPane.showInputDialog("altura")); Date fecha_nacimiento = new Date(); String b = ""; for (Bestia u : lista_bestias) { b += "\n" + lista_bestias.indexOf(u) + " " + u; } int be = Integer.parseInt(JOptionPane.showInputDialog(b + "\n" + "Cual bestia")); Bestia bestia = lista_bestias.get(be); double poder = Double.parseDouble(JOptionPane.showInputDialog("poder")); double ataque = 150; double defensa = 140; double curación = 50; int sombrero = Integer.parseInt(JOptionPane.showInputDialog("Tiene sombrero \n" + "1-si \n" + "2-no \n")); if (sombrero == 1) { curación = curación + 200; ataque = ataque + 200; } int baston = Integer.parseInt(JOptionPane.showInputDialog("Tiene baston \n" + "1-si \n" + "2-no \n")); if (baston == 1) { ataque = ataque + 200; } lista_pueblo.get(pueblo).getLugares().get(lugar).getIntegrante().add(new Maiar(baston, sombrero, nombre, Apellido, altura, fecha_nacimiento, bestia, poder, ataque, defensa, curación)); JOptionPane.showMessageDialog(null, "Hecho"); } break; } } case "4": {//Bestias String op = JOptionPane.showInputDialog("Ingrese opcion \n" + "1-Aguilas \n" + "2-Arañas \n" + "3-Balrogs \n" + "4-Bestias Aladas \n" + "5-Dragones \n"); switch (op) {//Aguilas case "1": { int garras = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero garras")); Boolean veneno = false; String ven = JOptionPane.showInputDialog("Tiene veneno \n" + "1-Si \n" + "2-No \n"); if (ven.equals("1")) { veneno = true; } else { veneno = false; } int defensa = Integer.parseInt(JOptionPane.showInputDialog("Nivel de defensa")); int ataque = Integer.parseInt(JOptionPane.showInputDialog("Nivel ataque")); int vida = Integer.parseInt(JOptionPane.showInputDialog("Vida")); int curacion = Integer.parseInt(JOptionPane.showInputDialog("Nivel de curacion")); String color = JOptionPane.showInputDialog("Color?"); lista_bestias.add(new Aguilas(color, garras, veneno, vida, defensa, ataque, curacion)); JOptionPane.showMessageDialog(null, "Hecho"); } break; case "2": { int garras = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero garras")); Boolean veneno = false; String ven = JOptionPane.showInputDialog("Tiene veneno \n" + "1-Si \n" + "2-No \n"); if (ven.equals("1")) { veneno = true; } else { veneno = false; } int defensa = Integer.parseInt(JOptionPane.showInputDialog("Nivel de defensa")); int ataque = Integer.parseInt(JOptionPane.showInputDialog("Nivel ataque")); int vida = Integer.parseInt(JOptionPane.showInputDialog("Vida")); int curacion = Integer.parseInt(JOptionPane.showInputDialog("Nivel de curacion")); String sexo = JOptionPane.showInputDialog("sexo"); if (sexo.equals("femenino")) { vida += 50; } lista_bestias.add(new Arañas(sexo, garras, veneno, vida, defensa, ataque, curacion)); JOptionPane.showMessageDialog(null, "Hecho"); } break; case "3": {//Balrogs int garras = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero garras")); Boolean veneno = false; String ven = JOptionPane.showInputDialog("Tiene veneno \n" + "1-Si \n" + "2-No \n"); if (ven.equals("1")) { veneno = true; } else { veneno = false; } int defensa = Integer.parseInt(JOptionPane.showInputDialog("Nivel de defensa")); int ataque = Integer.parseInt(JOptionPane.showInputDialog("Nivel ataque")); int vida = Integer.parseInt(JOptionPane.showInputDialog("Vida")); int curacion = Integer.parseInt(JOptionPane.showInputDialog("Nivel de curacion")); Boolean latigo; String l = JOptionPane.showInputDialog("Tienen latigo \n" + "1-si \n" + "2-no \n"); if (l.equals("1")) { latigo = true; } else { latigo = false; } lista_bestias.add(new Balrogs(latigo, garras, veneno, vida, defensa, ataque, curacion)); JOptionPane.showMessageDialog(null, "Hecho"); } break; case "4": {//Bestias aladas int garras = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero garras")); Boolean veneno = false; String ven = JOptionPane.showInputDialog("Tiene veneno \n" + "1-Si \n" + "2-No \n"); if (ven.equals("1")) { veneno = true; } else { veneno = false; } int defensa = Integer.parseInt(JOptionPane.showInputDialog("Nivel de defensa")); int ataque = Integer.parseInt(JOptionPane.showInputDialog("Nivel ataque")); int vida = Integer.parseInt(JOptionPane.showInputDialog("Vida")); int curacion = Integer.parseInt(JOptionPane.showInputDialog("Nivel de curacion")); double velocidad = Double.parseDouble(JOptionPane.showInputDialog("Velocidad")); lista_bestias.add(new BestiasAladas(velocidad, garras, veneno, defensa, ataque, vida, curacion)); JOptionPane.showMessageDialog(null, "velocidad"); } break; case "5": {//Dragones int garras = Integer.parseInt(JOptionPane.showInputDialog("Ingrese numero garras")); Boolean veneno = false; String ven = JOptionPane.showInputDialog("Tiene veneno \n" + "1-Si \n" + "2-No \n"); if (ven.equals("1")) { veneno = true; } else { veneno = false; } int defensa = Integer.parseInt(JOptionPane.showInputDialog("Nivel de defensa")); int ataque = Integer.parseInt(JOptionPane.showInputDialog("Nivel ataque")); int vida = Integer.parseInt(JOptionPane.showInputDialog("Vida")); int curacion = Integer.parseInt(JOptionPane.showInputDialog("Nivel de curacion")); double long_ala = Double.parseDouble(JOptionPane.showInputDialog("lon ala")); lista_bestias.add(new Dragones(long_ala, garras, veneno, defensa, ataque, vida, curacion)); JOptionPane.showMessageDialog(null, "hecho"); } break; } } break; } } break; case "2": {//eliminar String r = JOptionPane.showInputDialog(null, "1-Eliminar Pueblo \n" + "2-Eliminar Bestia \n" + "3-Elimianr lugares \n" + "4-Eliminar integrante \n" ); int re = Integer.parseInt(r); switch (re) { case 1: String resp; int cont = 0; JOptionPane.showMessageDialog(null, "A Continuacion se le muestran los pueblos"); for (Pueblo lp : lista_pueblo) { JOptionPane.showMessageDialog(null, "[" + cont + "]" + lp); cont++; } resp = JOptionPane.showInputDialog(null, "Que posicion desea eliminar?"); int respp = Integer.parseInt(resp); lista_pueblo.remove(respp); break; case 2: String resp1; int cont1 = 0; JOptionPane.showMessageDialog(null, "A Continuacion se le muestran los pueblos"); for (Bestia lb : lista_bestias) { JOptionPane.showMessageDialog(null, "[" + cont1 + "]" + lb); for (Bestia lp : lista_bestias) { JOptionPane.showMessageDialog(null, "[" + cont1 + "]" + lp); cont1++; } resp1 = JOptionPane.showInputDialog(null, "Que posicion desea eliminar?"); int respp1 = Integer.parseInt(resp1); lista_bestias.remove(respp1); break; } case 3: { String e = ""; for (Pueblo t : lista_pueblo) { e += "\n" + lista_pueblo.indexOf(t) + " " + t; } int pue = Integer.parseInt(JOptionPane.showInputDialog(e + "\n" + "Cual pueblo")); String t = ""; for (Lugar i : lista_pueblo.get(pue).getLugares()) { t += "\n" + lista_pueblo.get(pue).getLugares().indexOf(i) + " " + i; } int el = Integer.parseInt(JOptionPane.showInputDialog(t + "\n" + "Cual lugar")); lista_pueblo.get(pue).getLugares().remove(el); JOptionPane.showMessageDialog(null, "Hecho"); } break; case 4: { String e = ""; for (Pueblo t : lista_pueblo) { e += "\n" + lista_pueblo.indexOf(t) + " " + t; } int pue = Integer.parseInt(JOptionPane.showInputDialog(e + "\n" + "Cual pueblo")); String t = ""; for (Lugar i : lista_pueblo.get(pue).getLugares()) { t += "\n" + lista_pueblo.get(pue).getLugares().indexOf(i) + " " + i; } int el = Integer.parseInt(JOptionPane.showInputDialog(t + "\n" + "Cual lugar")); String u = ""; for (Integrante i : lista_pueblo.get(pue).getLugares().get(el).getIntegrante()) { u += "\n" + lista_pueblo.get(pue).getLugares().get(el).getIntegrante().indexOf(i) + " " + i; } int y = Integer.parseInt(JOptionPane.showInputDialog(u + "\n" + "Cual integrante")); lista_pueblo.get(pue).getLugares().get(el).getIntegrante().remove(y); JOptionPane.showMessageDialog(null, "Hecho"); } break; } } break; ////////////////////////////////////////////////////////////////777 / case "3": {//Modificar int contad = 0; int contad2 = 0; String respuesta; String respuesta2; String respuesta22; String respuesta3; String modif; String modif2; int respu; int respu2; int respu22; int respu3; int mod; int mod2; String modpueblo; respuesta = JOptionPane.showInputDialog(null, "1-Para modificar Pueblos \n" + "2-Para modificar Bestias \n" + "3-Para modificar Integrante \n"); respu = Integer.parseInt(respuesta); switch (respu) { case 1: for (Pueblo mp : lista_pueblo) { JOptionPane.showMessageDialog(null, "[" + contad2 + "]" + mp); contad2++; } respuesta22 = JOptionPane.showInputDialog(null, "Ingrese la posicion del pueblo que desea modificar"); respu22 = Integer.parseInt(respuesta22); modpueblo = JOptionPane.showInputDialog(null, "Ingrese nuevo nombre del pueblo"); lista_pueblo.get(respu22).setNombre(modpueblo); break; case 2: for (Bestia mb : lista_bestias) { JOptionPane.showMessageDialog(null, "[" + contad + "]" + mb); contad++; } respuesta2 = JOptionPane.showInputDialog(null, "Ingrese la posicion de la bestia que desea modificar"); respu2 = Integer.parseInt(respuesta2); respuesta3 = JOptionPane.showInputDialog(null, "1-Modificar garras \n " + "2-Modificar veneno"); respu3 = Integer.parseInt(respuesta3); if (respu3 == 1) { modif = JOptionPane.showInputDialog(null, "Cuantas garras desea"); mod = Integer.parseInt(modif); if (mod < 6) { lista_bestias.get(respu).setGarras(mod); } else { JOptionPane.showMessageDialog(null, "No puede tener mas de 6 gradas"); } } if (respu3 == 2) { modif2 = JOptionPane.showInputDialog(null, "1-Veneno\n" + "2-Sin veneno"); mod2 = Integer.parseInt(modif2); if (mod2 == 1) { lista_bestias.get(respu2).setVeneno(Boolean.TRUE); } else if (mod2 == 2) { lista_bestias.get(respu2).setVeneno(Boolean.FALSE); } } break; case 3: { String modp; int imodp; String modp2; int imodp2; String modp1; String modp11; String modificar; String modificaral; String modificarap; int modificaral1; int imodp1; int modp121; JOptionPane.showMessageDialog(null, "Acontinuacion los pueblos"); for (Pueblo mi : lista_pueblo) { JOptionPane.showMessageDialog(null, mi); } modp = JOptionPane.showInputDialog(null, "Ingrese la posicion del pueblo que desea modificar"); imodp = Integer.parseInt(modp); for (Lugar mip : lista_pueblo.get(imodp).getLugares()) { JOptionPane.showMessageDialog(null, mip); } modp1 = JOptionPane.showInputDialog(null, "Ingrese la posicion del lugar que desea modificar"); imodp1 = Integer.parseInt(modp); for (Integrante mip1 : lista_pueblo.get(imodp).getLugares().get(imodp1).getIntegrante()) { JOptionPane.showMessageDialog(null, mip1); } modp2 = JOptionPane.showInputDialog(null, "Ingrese la posicion del integrante que desea modificar"); imodp2 = Integer.parseInt(modp2); modp11 = JOptionPane.showInputDialog(null, "1-Modificar nombre" + "2-Mofificar altura" + "3-Modificar apellido"); modp121 = Integer.parseInt(modp11); switch (modp121) { case 1: { modificar = JOptionPane.showInputDialog(null, "Ingrese el nombre al que desea modificar"); lista_pueblo.get(imodp).getLugares().get(imodp1).getIntegrante().get(imodp2).setNombre(modificar); } break; case 2: { modificaral = JOptionPane.showInputDialog(null, "Ingrese la altura al que desea modificar"); modificaral1 = Integer.parseInt(modificaral); lista_pueblo.get(imodp).getLugares().get(imodp1).getIntegrante().get(imodp2).setAltura(modificaral1); } break; case 3: { modificarap = JOptionPane.showInputDialog(null, "Ingrese el apellido al que desea modificar"); lista_pueblo.get(imodp).getLugares().get(imodp1).getIntegrante().get(imodp2).setApellido(modificarap); } break; } } break; } } break; case "4": {//simulacion String f = JOptionPane.showInputDialog("1-simulacion unica \n" + "2-Simulacion lineal \n"); switch (f) { case "1": {//batalla unica String el = ""; for (Pueblo p : lista_pueblo) { el += "\n" + lista_pueblo.indexOf(p) + " " + p; } int lug = Integer.parseInt(JOptionPane.showInputDialog(el + "\n" + "cual lugar")); String e = ""; for (Lugar j : lista_pueblo.get(lug).getLugares()) { e += "\n" + lista_pueblo.get(lug).getLugares().indexOf(j) + " " + j; } int r = Integer.parseInt(JOptionPane.showInputDialog(e + "\n" + "Cual lugar")); String t = ""; for (Integrante j : lista_pueblo.get(lug).getLugares().get(r).getIntegrante()) { t += "\n" + lista_pueblo.get(lug).getLugares().get(r).getIntegrante().indexOf(j) + " " + j; } int Integrante1 = Integer.parseInt(JOptionPane.showInputDialog(t + "\n" + "Cual integrante")); String el1 = ""; for (Pueblo p : lista_pueblo) { el1 += "\n" + lista_pueblo.indexOf(p) + " " + p; } int lug1 = Integer.parseInt(JOptionPane.showInputDialog(el1 + "\n" + "cual lugar")); String e1 = ""; for (Lugar j : lista_pueblo.get(lug1).getLugares()) { e1 += "\n" + lista_pueblo.get(lug1).getLugares().indexOf(j) + " " + j; } int r1 = Integer.parseInt(JOptionPane.showInputDialog(e + "\n" + "Cual lugar")); String t1 = ""; for (Integrante j : lista_pueblo.get(lug1).getLugares().get(r1).getIntegrante()) { t1 += "\n" + lista_pueblo.get(lug1).getLugares().get(r1).getIntegrante().indexOf(j) + " " + j; } int Integrante2 = Integer.parseInt(JOptionPane.showInputDialog(t1 + "\n" + "Cual integrante")); int cont = 0; while ( lista_pueblo.get(lug).getLugares().get(r).getIntegrante().get(Integrante1).getDefensa()>0 || lista_pueblo.get(lug1).getLugares().get(r1).getIntegrante().get(Integrante2).getDefensa()>0 ) { if (cont == 0) { cont++; } else if (cont == 1) { cont=0; } } } break; case "2": {//batalla lineal } break; } } break; } } } }
package VASL.build.module; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import VASL.environment.*; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.GlobalOptions; import VASSAL.command.CommandEncoder; import VASSAL.configure.*; import VASSAL.i18n.Resources; import VASSAL.preferences.Prefs; import VASSAL.tools.KeyStrokeListener; import VASSAL.tools.KeyStrokeSource; import VASSAL.tools.imageop.Op; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.InputEvent; import java.awt.event.KeyListener; import java.awt.image.BufferedImage; import java.util.*; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.GroupLayout; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.KeyStroke; import static VASSAL.build.GameModule.getGameModule; /** * The chat window component. Displays text messages and * accepts i. Also acts as a {@link CommandEncoder}, * encoding/decoding commands that display message in the text area */ public class ASLChatter extends VASSAL.build.module.Chatter { private ArrayList<ChatterListener> chatter_listeners = new ArrayList<ChatterListener>(); public static final String BEFORE_CATEGORY = " "; private static final String CHAT_FONT = "ChatFont"; private static final String BUTTON_FONT = "ButtonFont"; private static final String USE_DICE_IMAGES = "useDiceImages"; //$NON-NLS-1$ private static final String SHOW_DICE_STATS = "showDiceStats"; //$NON-NLS-1$ private static final String CHAT_BACKGROUND_COLOR = "chatBackgroundColor"; //$NON-NLS-1$ private static final String COLORED_DICE_COLOR = "coloredDiceColor"; //$NON-NLS-1$ private static final String SINGLE_DIE_COLOR = "singleDieColor"; //$NON-NLS-1$ private static final String THIRD_DIE_COLOR = "thirdDieColor"; //$NON-NLS-1$ private static final String NOTIFICATION_LEVEL = "notificationLevel"; //$NON-NLS-1$ private final static String m_strFileNameFormat = "DC%s_%s.png"; private static final String preferenceTabName = "VASL"; // alwaysontop preference protected static final String DICE_CHAT_COLOR = "HTMLDiceChatColor"; private enum DiceType { WHITE, COLORED, OTHER_DUST, BOTH, SINGLE } private Color m_clrBackground; private String m_clrColoredDiceColor; private String m_clrDustColoredDiceColor; private Color myASLChat; private String m_clrSingleDieColor; private JButton m_btnStats; private JButton m_btnDR; private JButton m_btnIFT; private JButton m_btnTH; private JButton m_btnTK; private JButton m_btnMC; private JButton m_btnRally; private JButton m_btnCC; private JButton m_btnTC; private JButton m_btndr; private JButton m_btnSA; private JButton m_btnRS; private GroupLayout m_objGroupLayout; private JPanel l_objButtonPanel; private boolean m_bUseDiceImages; private boolean m_bShowDiceStats; private final Icon [] mar_objWhiteDCIcon = new Icon[6]; private final Icon [] mar_objColoredDCIcon = new Icon[6]; private final Icon [] mar_objOtherColoredDCIcon = new Icon[6]; private final Icon [] mar_objSingleDieIcon = new Icon[6]; private Environment environment = new Environment(); private JTextField m_edtInputText; private int m_DRNotificationLevel; // create message part objects; each will be styled differently and added to chat window String msgpartCategory; String msgpartUser; String msgpartWdice; String msgpartCdice; String msgpartRest; String msgpartSpecial; String msgpartSAN; String msgpartDiceImage; public ASLChatter() { super(); m_clrBackground = Color.white; //m_clrDustColoredDiceColor = Color.magenta; //m_clrSingleDieColor = Color.RED; conversationPane.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent e) { if (!e.isConsumed()) { keyCommand(KeyStroke.getKeyStrokeForEvent(e)); } } public void keyPressed(KeyEvent e) { if (!e.isConsumed()) { keyCommand(KeyStroke.getKeyStrokeForEvent(e)); } } public void keyReleased(KeyEvent e) { if (!e.isConsumed()) { keyCommand(KeyStroke.getKeyStrokeForEvent(e)); } } } ); m_btnStats = CreateStatsDiceButton("stat.png", "", "Dice rolls stats", KeyStroke.getKeyStroke(KeyEvent.VK_F3, InputEvent.CTRL_DOWN_MASK)); m_btnDR = CreateChatterDiceButton("DRs.gif", "DR", "DR", KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), true, ASLDiceBot.OTHER_CATEGORY); m_btnIFT = CreateChatterDiceButton("", "IFT", "IFT attack DR", KeyStroke.getKeyStroke(KeyEvent.VK_I, InputEvent.CTRL_DOWN_MASK + InputEvent.SHIFT_DOWN_MASK), true, "IFT"); m_btnTH = CreateChatterDiceButton("", "TH", "To Hit DR", KeyStroke.getKeyStroke(KeyEvent.VK_H, InputEvent.CTRL_DOWN_MASK + InputEvent.SHIFT_DOWN_MASK), true, "TH"); m_btnTK = CreateChatterDiceButton("", "TK", "To Kill DR", KeyStroke.getKeyStroke(KeyEvent.VK_K, InputEvent.CTRL_DOWN_MASK + InputEvent.SHIFT_DOWN_MASK), true, "TK"); m_btnMC = CreateChatterDiceButton("", "MC", "Morale Check DR", KeyStroke.getKeyStroke(KeyEvent.VK_M, InputEvent.CTRL_DOWN_MASK + InputEvent.SHIFT_DOWN_MASK), true, "MC"); m_btnRally = CreateChatterDiceButton("", "Rally", "Rally DR", KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.CTRL_DOWN_MASK + InputEvent.SHIFT_DOWN_MASK), true, "Rally"); m_btnCC = CreateChatterDiceButton("", "CC", "Close Combat DR", KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_DOWN_MASK + InputEvent.SHIFT_DOWN_MASK), true, "CC"); m_btnTC = CreateChatterDiceButton("", "TC", "Task Check DR", KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_DOWN_MASK + InputEvent.SHIFT_DOWN_MASK), true, "TC"); m_btndr = CreateChatterDiceButton("dr.gif", "dr", "dr", KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0), false, ASLDiceBot.OTHER_CATEGORY); m_btnSA = CreateChatterDiceButton("", "SA", "Sniper Activation dr", KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK + InputEvent.SHIFT_DOWN_MASK), false, "SA"); m_btnRS = CreateChatterDiceButton("", "RS", "Random Selection dr", KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.CTRL_DOWN_MASK + InputEvent.SHIFT_DOWN_MASK), false, "RS"); JPanel l_objPanelContainer = new JPanel(); l_objPanelContainer.setLayout(new BoxLayout(l_objPanelContainer, BoxLayout.LINE_AXIS)); l_objPanelContainer.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); l_objButtonPanel = new JPanel(); l_objButtonPanel.setLayout(new GridBagLayout()); l_objButtonPanel.setBorder(BorderFactory.createEmptyBorder(1, 1, 2, 1)); l_objButtonPanel.setMaximumSize(new Dimension(1000, 1000)); GridBagConstraints l_objGridBagConstraints = new GridBagConstraints(); l_objGridBagConstraints.fill = GridBagConstraints.BOTH; l_objGridBagConstraints.weightx = 0.5; l_objGridBagConstraints.weighty = 0.5; l_objGridBagConstraints.insets = new Insets(0, 1, 0, 1); l_objButtonPanel.add(m_btnStats, l_objGridBagConstraints); l_objButtonPanel.add(m_btnDR, l_objGridBagConstraints); l_objButtonPanel.add(m_btnIFT, l_objGridBagConstraints); l_objButtonPanel.add(m_btnTH, l_objGridBagConstraints); l_objButtonPanel.add(m_btnTK, l_objGridBagConstraints); l_objButtonPanel.add(m_btnMC, l_objGridBagConstraints); l_objButtonPanel.add(m_btnTC, l_objGridBagConstraints); l_objButtonPanel.add(m_btnRally, l_objGridBagConstraints); l_objButtonPanel.add(m_btnCC, l_objGridBagConstraints); l_objButtonPanel.add(m_btndr, l_objGridBagConstraints); l_objButtonPanel.add(m_btnSA, l_objGridBagConstraints); l_objButtonPanel.add(m_btnRS, l_objGridBagConstraints); m_edtInputText = new JTextField(60); m_edtInputText.setFocusTraversalKeysEnabled(false); m_edtInputText.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { send(formatChat(e.getActionCommand())); m_edtInputText.setText(""); //$NON-NLS-1$ } }); m_edtInputText.setMaximumSize(new Dimension(m_edtInputText.getMaximumSize().width, m_edtInputText.getPreferredSize().height)); scroll.setViewportView(conversationPane); l_objPanelContainer.add(l_objButtonPanel); m_objGroupLayout = new GroupLayout(this); setLayout(m_objGroupLayout); m_objGroupLayout.setHorizontalGroup( m_objGroupLayout.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(scroll) .addComponent(l_objPanelContainer, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(m_edtInputText) ); m_objGroupLayout.setVerticalGroup( m_objGroupLayout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(m_objGroupLayout.createSequentialGroup() .addComponent(scroll, GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE) .addGap(0, 0, 0) .addComponent(l_objPanelContainer, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(m_edtInputText, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) ); } public JPanel getButtonPanel() { //used by SASLDice extension return l_objButtonPanel; } private void SetButtonsFonts(Font objFont) { m_btnStats.setFont(objFont); m_btnDR.setFont(objFont); m_btnIFT.setFont(objFont); m_btnTH.setFont(objFont); m_btnTK.setFont(objFont); m_btnMC.setFont(objFont); m_btnRally.setFont(objFont); m_btnCC.setFont(objFont); m_btnTC.setFont(objFont); m_btndr.setFont(objFont); m_btnSA.setFont(objFont); m_btnRS.setFont(objFont); } private JButton CreateInfoButton(String strCaption, String strTooltip, final String strMsg, KeyStroke objKeyStroke) { // used by SASLDice extension JButton l_btn = new JButton(strCaption); l_btn.setPreferredSize(new Dimension(90, 25)); l_btn.setMargin(new Insets(l_btn.getMargin().top, 0, l_btn.getMargin().bottom, 0)); ActionListener l_objAL = new ActionListener() { public void actionPerformed(ActionEvent e) { send(formatChat(strMsg)); } }; l_btn.addActionListener(l_objAL); KeyStrokeListener l_objListener = new KeyStrokeListener(l_objAL); l_objListener.setKeyStroke(objKeyStroke); AddHotKeyToTooltip(l_btn, l_objListener, strTooltip); l_btn.setFocusable(false); GameModule.getGameModule().addKeyStrokeListener(l_objListener); return l_btn; } private JButton CreateStatsDiceButton(String strImage, String strCaption, String strTooltip, KeyStroke keyStroke) { JButton l_btn = new JButton(strCaption); l_btn.setMinimumSize(new Dimension(5, 30)); l_btn.setMargin(new Insets(0, 0, 0, -1)); try { if (!strImage.isEmpty()) { l_btn.setIcon(new ImageIcon(Op.load(strImage).getImage(null))); } } catch (Exception ex) { } ActionListener l_objAL = new ActionListener() { public void actionPerformed(ActionEvent e) { try { ASLDiceBot l_objDice = GameModule.getGameModule().getComponentsOf(ASLDiceBot.class).iterator().next(); if (l_objDice != null) { l_objDice.statsToday(); } } catch (Exception ex) { } } }; l_btn.addActionListener(l_objAL); KeyStrokeListener l_Listener = new KeyStrokeListener(l_objAL); l_Listener.setKeyStroke(keyStroke); AddHotKeyToTooltip(l_btn, l_Listener, strTooltip); l_btn.setFocusable(false); GameModule.getGameModule().addKeyStrokeListener(l_Listener); return l_btn; } public JButton CreateChatterDiceButton(String strImage, String strCaption, String strTooltip, KeyStroke keyStroke, final boolean bDice, final String strCat) { JButton l_btn = new JButton(strCaption); l_btn.setMinimumSize(new Dimension(5, 30)); l_btn.setMargin(new Insets(0, 0, 0, -1)); try { if (!strImage.isEmpty()) { l_btn.setIcon(new ImageIcon(Op.load(strImage).getImage(null))); } } catch (Exception ex) { } ActionListener l_objAL = new ActionListener() { public void actionPerformed(ActionEvent e) { try { ASLDiceBot l_objDice = GameModule.getGameModule().getComponentsOf(ASLDiceBot.class).iterator().next(); if (l_objDice != null) { if (bDice) { l_objDice.DR(strCat); } else { l_objDice.dr(strCat); } } } catch (Exception ex) { } } }; l_btn.addActionListener(l_objAL); KeyStrokeListener l_Listener = new KeyStrokeListener(l_objAL); l_Listener.setKeyStroke(keyStroke); AddHotKeyToTooltip(l_btn, l_Listener, strTooltip); l_btn.setFocusable(false); GameModule.getGameModule().addKeyStrokeListener(l_Listener); return l_btn; } private void AddHotKeyToTooltip(JButton objButton, KeyStrokeListener objListener, String strTooltipText) { if (objListener.getKeyStroke() != null) objButton.setToolTipText(strTooltipText + " [" + HotKeyConfigurer.getString(objListener.getKeyStroke()) + "]"); } protected void makeASLStyleSheet(Font f) { if (this.style != null) { if (f == null) { if (this.myFont == null) { f = new Font("SansSerif", 0, 12); this.myFont = f; } else { f = this.myFont; } } this.addStyle(".msgcategory", f, Color.black, "bold", 0); this.addStyle(".msguser", f, gameMsg4, "bold", 0); this.addStyle(".msgspecial", f, gameMsg, "bold", 0); style.addRule( " .tbl { border:0px solid #C0C0C0; border-collapse:collapse; border-spacing:0px; padding:0px; background:#CCFFCC;}" + " .tbl th { border:1px solid #C0C0C0; padding:5px; background:#FFFF66;}" + " .tbl td {border:1px solid #C0C0C0; padding:5px; text-align: right;}" + " .tbl tr.total {border:2px solid #black; background:#CCFFFF;}" + " .tbl td.up {border-top:2px solid black; padding:5px; font-weight: bold; text-align: right;}"); } } @Override protected String formatChat(String text) { final String id = GlobalOptions.getInstance().getPlayerId(); return "<" + (id.length() == 0 ? "(" + getAnonymousUserName() + ")" : id) + "> - " + text; //$NON-NLS-1$ //$NON-NLS-2$ } @Override public JTextField getInputField() { return m_edtInputText; } String [] FindUser (String strVal) { String [] lar_strRetValue = new String[] {strVal,"",""}; int l_iUserStart = strVal.indexOf("<"); int l_iUserEnd = strVal.indexOf(">"); if ((l_iUserStart != -1) && (l_iUserEnd != -1)) { lar_strRetValue[0] = strVal.substring(0, l_iUserStart + 1); lar_strRetValue[1] = strVal.substring(l_iUserStart + 1, l_iUserEnd); lar_strRetValue[2] = strVal.substring(l_iUserEnd+1); } return lar_strRetValue; } @Override public void show(String strMsg) { try { if (strMsg.length() > 0) { if (strMsg.startsWith("!!")) // dice stats button has been clicked { strMsg = makeTableString(strMsg); } else if (strMsg.startsWith("*** 3d6 = ")) { Parse3d6(strMsg); } else if (strMsg.startsWith("*** (")) { ParseNewDiceRoll(strMsg); strMsg = makeMessageString(); } else if (strMsg.startsWith("<")) { ParseUserMsg(strMsg); strMsg = makeMessageString(); } else if (strMsg.startsWith("-")) { ParseSystemMsg(strMsg); } else if (strMsg.startsWith("*")) { ParseMoveMsg(strMsg); } else { ParseDefaultMsg(strMsg); } } } catch (Exception ex) { ex.printStackTrace(); } super.show(strMsg); } private void ParseDefaultMsg(String strMsg) { try { //StyleConstants.setForeground(m_objMainStyle, Color.black); //m_objDocument.insertString(m_objDocument.getLength(), "\n" + strMsg, m_objMainStyle); } catch (Exception ex) { ex.printStackTrace(); } } private void ParseMoveMsg(String strMsg) { try { //StyleConstants.setForeground(m_objMainStyle, m_clrGameMsg); //m_objDocument.insertString(m_objDocument.getLength(), "\n" + strMsg, m_objMainStyle); } catch (Exception ex) { ex.printStackTrace(); } } private void ParseSystemMsg(String strMsg) { try { //StyleConstants.setForeground(m_objMainStyle, m_clrSystemMsg); //m_objDocument.insertString(m_objDocument.getLength(), "\n" + strMsg, m_objMainStyle); } catch (Exception ex) { ex.printStackTrace(); } } private void ParseUserMsg(String strMsg) { try { String[] lar_strParts = FindUser(strMsg); if ((!lar_strParts[1].isEmpty()) && (!lar_strParts[2].isEmpty())) { msgpartCategory = ""; msgpartCdice=""; msgpartWdice=""; msgpartSAN="";msgpartRest=""; msgpartDiceImage="";msgpartSpecial=""; msgpartUser = lar_strParts[1]; msgpartRest = lar_strParts[2]; } } catch (Exception ex) { ex.printStackTrace(); } } private void ParseNewDiceRoll(String strMsg) { String l_strCategory = "", l_strDice = "", l_strUser = "", l_strSAN = ""; int l_iFirstDice, l_iSecondDice; msgpartCategory=null; msgpartUser=null; msgpartCdice=null; msgpartWdice=null; msgpartSpecial=null; msgpartRest=null; msgpartDiceImage=null; Map<DiceType, Integer> otherDice = new HashMap<>(); DustLevel dustLevel = environment.getCurrentDustLevel(); try { String l_strRestOfMsg = strMsg.substring("*** (".length()); int l_iPos = l_strRestOfMsg.indexOf(" DR) "); if (l_iPos != -1) { l_strCategory = l_strRestOfMsg.substring(0, l_iPos); l_strRestOfMsg = l_strRestOfMsg.substring(l_iPos + " DR) ".length()); l_iPos = l_strRestOfMsg.indexOf(" ***"); if (l_iPos != -1) { l_strDice = l_strRestOfMsg.substring(0, l_iPos); l_strRestOfMsg = l_strRestOfMsg.substring(l_iPos + " ***".length());// <FredKors> Allied SAN [1 / 8 avg 6,62 (6,62)] (01.51 - by random.org) if (l_strDice.length() == 3 || l_strDice.length() == 5) { String [] lar_strDice = l_strDice.split(","); if (lar_strDice.length == 2 || (lar_strDice.length == 3 && environment.dustInEffect())) { l_iFirstDice = Integer.parseInt(lar_strDice[0]); l_iSecondDice = Integer.parseInt(lar_strDice[1]); if(environment.dustInEffect() && lar_strDice.length == 3) { otherDice.put(DiceType.OTHER_DUST, Integer.parseInt(lar_strDice[2])); } if ((l_iFirstDice > 0) && (l_iFirstDice < 7) && (l_iSecondDice > 0) && (l_iSecondDice < 7)) { String[] lar_strParts = FindUser(l_strRestOfMsg); ArrayList<String> specialMessages = new ArrayList<String>(); if ((!lar_strParts[1].isEmpty()) && (!lar_strParts[2].isEmpty())) { l_strUser = lar_strParts[1]; l_strRestOfMsg = lar_strParts[2]; // > Allied SAN [1 / 8 avg 6,62 (6,62)] (01.51 - by random.org) l_strRestOfMsg = l_strRestOfMsg.replace(">", " ").trim(); //Allied SAN [1 / 8 avg 6,62 (6,62)] (01.51 - by random.org) // Add special event hints, if necessary // First, SAN, which should not trigger for Rally, TK and CC rolls // and should happen on "Only Sniper" setting and in Full ASL mode if(m_DRNotificationLevel == 3 || m_DRNotificationLevel == 1) { if ((!l_strCategory.equals("TK")) && (!l_strCategory.equals("CC")) && (!l_strCategory.equals(("Rally")))) { if (l_strRestOfMsg.startsWith("Axis SAN")) { l_strSAN = "Axis SAN"; specialMessages.add("Axis SAN"); l_strRestOfMsg = l_strRestOfMsg.substring("Axis SAN".length()); } else if (l_strRestOfMsg.startsWith("Allied SAN")) { l_strSAN = "Allied SAN"; specialMessages.add("Allied SAN"); l_strRestOfMsg = l_strRestOfMsg.substring("Allied SAN".length()); } else if (l_strRestOfMsg.startsWith("Axis/Allied SAN")) { l_strSAN = "Axis/Allied SAN"; specialMessages.add("Axis/Allied SAN"); l_strRestOfMsg = l_strRestOfMsg.substring("Axis/Allied SAN".length()); } } if (l_strCategory.equals("TC")) { if (l_strRestOfMsg.startsWith("Axis Booby Trap")) { l_strSAN = "Axis Booby Trap"; specialMessages.add("Axis Booby Trap"); l_strRestOfMsg = l_strRestOfMsg.substring("Axis Booby Trap".length()); } else if (l_strRestOfMsg.startsWith("Allied Booby Trap")) { l_strSAN = "Allied Booby Trap"; specialMessages.add("Allied Booby Trap"); l_strRestOfMsg = l_strRestOfMsg.substring("Allied Booby Trap".length()); } else if (l_strRestOfMsg.startsWith("Axis/Allied Booby Trap")) { l_strSAN = "Axis/Allied Booby Trap"; specialMessages.add("Axis/Allied Booby Trap"); l_strRestOfMsg = l_strRestOfMsg.substring("Axis/Allied Booby Trap".length()); } } } msgpartSAN=l_strSAN; // ALL of these happen only in Starter Kit mode or Full ASL mode if(m_DRNotificationLevel >= 2) { // For TH rolls only, show possible hit location, Unlikely hit and multiple hit if (l_strCategory.equals("TH")) { if (l_iFirstDice == l_iSecondDice) { // Starter Kit + Full ASL if (l_iFirstDice == 1) { specialMessages.add("Unlikely Hit (C3.6)"); } // Full ASL only if (m_DRNotificationLevel == 3) { specialMessages.add("Multiple Hits 15..40mm (C3.8)"); } } if (l_iFirstDice < l_iSecondDice) { specialMessages.add("Turret"); } else { specialMessages.add("Hull"); } HandleSpecialMessagesForOtherDice(l_strCategory, specialMessages, l_iFirstDice,l_iSecondDice, otherDice); } else if (l_strCategory.equals("TK")) { if (l_iFirstDice == l_iSecondDice) { if (l_iFirstDice == 6) { specialMessages.add("Dud (C7.35)"); } } } else if (l_strCategory.equals("MC")) { // Full ASL only if (l_iFirstDice == 1 && l_iSecondDice == 1 && m_DRNotificationLevel == 3) { specialMessages.add("Heat of Battle (A15.1)"); } // Starter Kit & Full ASL else if (l_iFirstDice == 6 && l_iSecondDice == 6) { specialMessages.add("Casualty MC (A10.31)"); } HandleSpecialMessagesForOtherDice(l_strCategory, specialMessages, l_iFirstDice,l_iSecondDice, otherDice); } else if (l_strCategory.equals("TC")) { } else if (l_strCategory.equals("Rally")) { // Full ASL only if (l_iFirstDice == 1 && l_iSecondDice == 1 && m_DRNotificationLevel == 3) { specialMessages.add("Heat of Battle (A15.1) or Field Promotion (A18.11)"); } // Starter Kit + Full ASL else if (l_iFirstDice == 6 && l_iSecondDice == 6) { specialMessages.add("Fate -> Casualty Reduction (A10.64)"); } } else if (l_strCategory.equals("IFT")) { // check for cowering if (l_iFirstDice == l_iSecondDice) { // Full ASL only if (l_iFirstDice == 1 && m_DRNotificationLevel == 3) { specialMessages.add("Unlikely Kill vs * (A7.309)"); } // Starter Kit + Full ASL specialMessages.add("Cower if MMC w/o LDR"); } HandleSpecialMessagesForOtherDice(l_strCategory, specialMessages, l_iFirstDice,l_iSecondDice, otherDice); } else if (l_strCategory.equals("CC")) { // Full ASL only if (l_iFirstDice == 1 && l_iSecondDice == 1 && m_DRNotificationLevel == 3) { specialMessages.add("Infiltration (A11.22), Field Promotion (A18.12), Unlikely Kill (A11.501)"); } else if (l_iFirstDice == 6 && l_iSecondDice == 6 && m_DRNotificationLevel == 3) { specialMessages.add("Infiltration (A11.22)"); } } } // check if SASL Dice button clicked and if so ask for special message string - SASL Dice buttons are created via extension if(m_DRNotificationLevel == 3 && l_strCategory.equals("EP")){ if (l_iFirstDice == l_iSecondDice) { switch (l_iFirstDice) { case 1: specialMessages.add("Green and Conscript Units Panic"); break; case 2: specialMessages.add("2nd Line, Partisan, Green, and Conscript Units Panic"); break; case 3: case 4: specialMessages.add("1st Line, 2nd Line, Partisan, Green, and Conscript Units Panic"); break; case 5: case 6: specialMessages.add("Any Unit Panics"); break; } } } // Construct Special Message string String l_strSpecialMessages = ""; for (int i = 0; i < specialMessages.size(); ++i) { l_strSpecialMessages += specialMessages.get(i); if (i < specialMessages.size() - 1) { l_strSpecialMessages += ", "; } } msgpartCategory = BEFORE_CATEGORY + l_strCategory; if (m_bUseDiceImages) { msgpartCdice = Integer.toString(l_iFirstDice); msgpartWdice= Integer.toString(l_iSecondDice); PaintIcon(l_iFirstDice, DiceType.COLORED,true); PaintIcon(l_iSecondDice, DiceType.WHITE,true); //Add any other dice required for ( Map.Entry<DiceType, Integer> entry : otherDice.entrySet()) { PaintIcon(entry.getValue(), entry.getKey() ,true); } } else { msgpartCdice = Integer.toString(l_iFirstDice); msgpartWdice= Integer.toString(l_iSecondDice); } msgpartUser = l_strUser; msgpartSpecial = l_strSpecialMessages; if (m_bShowDiceStats) { msgpartRest = l_strRestOfMsg; } FireDiceRoll(); msgpartUser = " ... " + msgpartUser; } else { } } else { } } else { } } else { } } else { } } else { l_iPos = l_strRestOfMsg.indexOf(" dr) "); if (l_iPos != -1) { l_strCategory = l_strRestOfMsg.substring(0, l_iPos); l_strRestOfMsg = l_strRestOfMsg.substring(l_iPos + " dr) ".length()); l_iPos = l_strRestOfMsg.indexOf(" ***"); if (l_iPos != -1) { l_strDice = l_strRestOfMsg.substring(0, l_iPos); l_strRestOfMsg = l_strRestOfMsg.substring(l_iPos + " ***".length());// <FredKors> [1 / 8 avg 6,62 (6,62)] (01.51 - by random.org) if (l_strDice.length() == 1) { int l_iDice = Integer.parseInt(l_strDice); if ((l_iDice > 0) && (l_iDice < 7)) { String[] lar_strParts = FindUser(l_strRestOfMsg); if ((!lar_strParts[1].isEmpty()) && (!lar_strParts[2].isEmpty())) { l_strUser = lar_strParts[1]; l_strRestOfMsg = lar_strParts[2]; // > [1 / 8 avg 6,62 (6,62)] (01.51 - by random.org) l_strRestOfMsg = l_strRestOfMsg.replace(">", " ").trim(); msgpartCategory = BEFORE_CATEGORY + l_strCategory; if (m_bUseDiceImages) { msgpartCdice = (l_strDice); msgpartWdice="-1"; PaintIcon(l_iDice, DiceType.SINGLE,true); } else msgpartCdice = l_strDice; msgpartWdice="-1"; { } msgpartUser = " ... " + l_strUser; // added by DR 2018 to add chatter text on Sniper Activation dr if (l_strCategory.equals("SA")) { String sniperstring=""; if (l_iDice == 1) { sniperstring ="Eliminates SMC, Dummy stack, Sniper; Stuns & Recalls CE crew; breaks MMC & Inherent crew of certain vehicles; immobilizes unarmored vehicle (A14.3)" ; } else if (l_iDice == 2) { sniperstring ="Eliminates Dummy stack; Wounds SMC; Stuns CE crew; pins MMC, Inherent crew of certain vehicles, Sniper (A14.3)" ; } msgpartSpecial = sniperstring; } FireDiceRoll(); } else { } } else{ } } else { } } else { } } else { } } } catch (Exception ex) { ex.printStackTrace(); } } private void HandleSpecialMessagesForOtherDice(final String l_strCategory, final ArrayList<String> specialMessages, final int l_iFirstDice, final int l_iSecondDice, final Map<DiceType, Integer> otherDice) { int total = l_iFirstDice + l_iSecondDice; int unmodifiedTotal = total; final String SPACE = " "; // Dust if(environment.dustInEffect() && m_DRNotificationLevel == 3) { switch (l_strCategory) { case "TH": case "IFT": { if (environment.isSpecialDust()) { total += environment.getSpecialDust(otherDice.get(DiceType.OTHER_DUST)); } else { if (environment.isLightDust()) { total += Environment.getLightDust(otherDice.get(DiceType.OTHER_DUST)); } else { total += Environment.getModerateDust(otherDice.get(DiceType.OTHER_DUST)); } } specialMessages.add(environment.getCurrentDustLevel().toString() + SPACE); break; } case "MC": { if (environment.isSpecialDust()) { total -= environment.getSpecialDust(otherDice.get(DiceType.OTHER_DUST)); } else { if (environment.isLightDust()) { total -= Environment.getLightDust(otherDice.get(DiceType.OTHER_DUST)); } else { total -= Environment.getModerateDust(otherDice.get(DiceType.OTHER_DUST)); } } specialMessages.add(environment.getCurrentDustLevel().toString() +" - if interdicted, MC is " + total); break; } } } // Night if(environment.isNight() && m_DRNotificationLevel == 3) { switch (l_strCategory) { case "TH": case "IFT": { total += 1; specialMessages.add( "+1 Night LV" + SPACE); break; } } } if(environment.isLV()) { LVLevel lvLevel = environment.getCurrentLVLevel(); switch (l_strCategory) { case "TH": case "IFT": { switch (lvLevel) { case DAWN_DUSK: { total += 1; break; } } specialMessages.add(lvLevel.toString() + SPACE); break; } } } // Fog if(environment.isFog()) { switch (l_strCategory) { case "TH": case "IFT": { FogLevel fogLevel = environment.getCurrentFogLevel(); specialMessages.add(fogLevel.toString() + SPACE); break; } } } //Heat Haze if(environment.isHeatHaze()) { switch (l_strCategory) { case "TH": case "IFT": { HeatHazeLevel heatHazeLevel = environment.getCurrentHeatHazeLevel(); specialMessages.add(heatHazeLevel.toString() + SPACE); break; } } } //Sun Blindness if(environment.isSunBlindness()) { switch (l_strCategory) { case "TH": case "IFT": { SunBlindnessLevel sunBlindnessLevel = environment.getCurrentSunBlindnessLevel(); specialMessages.add(sunBlindnessLevel.toString() + SPACE); break; } } } if( unmodifiedTotal < total || environment.dustInEffect()) { specialMessages.add("Total: " + total); } } private void Parse3d6(String strMsg) { try { String l_strRestOfMsg = strMsg.substring("*** 3d6 = ".length()); int l_iPos = l_strRestOfMsg.indexOf(" ***"); String l_strUser = ""; if (l_iPos != -1) { String l_strLast = l_strRestOfMsg.substring(l_iPos); String l_strDice = l_strRestOfMsg.substring(0, l_iPos); if (l_strDice.length() == 5) { String [] lar_strDice = l_strDice.split(","); if (lar_strDice.length == 3) { int l_iFirstDice = Integer.parseInt(lar_strDice[0]); int l_iSecondDice = Integer.parseInt(lar_strDice[1]); int l_iThirdDice = Integer.parseInt(lar_strDice[2]); if ((l_iFirstDice > 0) && (l_iFirstDice < 7) && (l_iSecondDice > 0) && (l_iSecondDice < 7) && (l_iThirdDice > 0) && (l_iThirdDice < 7)) { String[] lar_strParts = FindUser(l_strLast); if ((!lar_strParts[1].isEmpty()) && (!lar_strParts[2].isEmpty())) { l_strUser = lar_strParts[1]; if (m_bUseDiceImages) { } else { } } else { } } else { } } else { } } else { } } else { } } catch (Exception ex) { ex.printStackTrace(); } } private void PaintIcon(int l_iDice, DiceType diceType, boolean bSingle) { try { if(diceType == DiceType.OTHER_DUST) { } else { String dicefile = null; if (diceType == DiceType.COLORED) { dicefile = getcoloredDicefile(l_iDice); } else if (diceType == DiceType.OTHER_DUST) { //newfile = getotherdicefile(l_iDice); } else if (diceType == DiceType.SINGLE) { dicefile = getsingleDiefile(l_iDice); } else { // DiceType.WHITE dicefile = getwhitedicefile(l_iDice); } if (msgpartDiceImage==null) { msgpartDiceImage = "<img alt=\"alt text\" src=\"" + dicefile + "\">"; } else { msgpartDiceImage = msgpartDiceImage + "&nbsp <img alt=\"alt text\" src=\"" + dicefile + "\"> &nbsp"; } } } catch (Exception ex) { ex.printStackTrace(); } } @Override public void build(org.w3c.dom.Element e) { } @Override public org.w3c.dom.Element getBuildElement(org.w3c.dom.Document doc){ return doc.createElement(getClass().getName()); } private String getcoloredDicefile(int colordieroll) { try { String dicecolor = getcoloredDicecolor(); return String.format(m_strFileNameFormat, String.valueOf(colordieroll), dicecolor); } catch (Exception ex) { ex.printStackTrace(); } return null; //TODO NEED TO HANDLE } private String getsingleDiefile(int singledieroll) { try { String dicecolor = getsingleDiecolor(); return String.format(m_strFileNameFormat, String.valueOf(singledieroll), dicecolor); } catch (Exception ex) { ex.printStackTrace(); } return null; //TODO NEED TO HANDLE } private String getsingleDiecolor(){ if (m_clrSingleDieColor==null){ return "B"; } else if (m_clrSingleDieColor.equals("Black")) { return "B"; } else if (m_clrSingleDieColor.equals("Blue")){ return "DB"; } else if (m_clrSingleDieColor.equals("Red")){ return "R"; } else if (m_clrSingleDieColor.equals("Green")){ return "G"; } else if (m_clrSingleDieColor.equals("Yellow")){ return "Y"; } else if (m_clrSingleDieColor.equals("Cyan")){ return "C"; } else if (m_clrSingleDieColor.equals("Orange")) { return "O"; } else if (m_clrSingleDieColor.equals("Purple")){ return "P"; } else { return "B"; } } private String getcoloredDicecolor(){ if (m_clrColoredDiceColor==null){ return "B"; } else if (m_clrColoredDiceColor.equals("Black")) { return "B"; } else if (m_clrColoredDiceColor.equals("Blue")){ return "DB"; } else if (m_clrColoredDiceColor.equals("Red")){ return "R"; } else if (m_clrColoredDiceColor.equals("Green")){ return "G"; } else if (m_clrColoredDiceColor.equals("Yellow")){ return "Y"; } else if (m_clrColoredDiceColor.equals("Cyan")){ return "C"; } else if (m_clrColoredDiceColor.equals("Orange")) { return "O"; } else if (m_clrColoredDiceColor.equals("Purple")){ return "P"; } else { return "B"; } } private String getwhitedicefile(int dieval){ switch (dieval){ case 1: return "DC1_W.png"; case 2: return "DC2_W.png"; case 3: return "DC3_W.png"; case 4: return "DC4_W.png"; case 5: return "DC5_W.png"; case 6: return "DC6_W.png"; default: return null; } } private String makeMessageString() { // need to add html formatting if (msgpartCategory == null) { msgpartCategory = ""; } if (msgpartCdice == null) { msgpartCdice = ""; } if (msgpartWdice == null) { msgpartWdice = ""; } if (msgpartUser == null) { msgpartUser = ""; } if (msgpartSpecial == null) { msgpartSpecial = ""; } if (msgpartRest == null) { msgpartRest = ""; } if (msgpartWdice== "-1"){ msgpartWdice=""; } String catstyle = "msgcategory"; String userstyle = "msguser"; String specialstyle = "msgspecial"; //text-decoration: underline"; //<p style="text-decoration: underline;">This text will be underlined.</p> if (m_bUseDiceImages) { return "*~<span class=" + userstyle + ">" + msgpartDiceImage + "</span>" + "<span class=" + catstyle + ">" + msgpartCategory + "</span>" + "<span class=" + userstyle + ">" + msgpartUser + "</span>" + " " + "<u>" + "<span class=" + specialstyle + ">" + msgpartSpecial + "</span>" + "</u>" + " " + msgpartRest; } else { return "*~<span class=" + catstyle + ">" + msgpartCategory + "</span>" + " " + msgpartCdice + " " + msgpartWdice + " " + "<span class=" + userstyle + ">" + msgpartUser + "</span>" + " " + "<u>" + "<span class=" + specialstyle + ">" + msgpartSpecial + "</span>" + "</u>" + " " + msgpartRest; } } private String makeTableString(String strMsg){ strMsg= strMsg.substring(2); // strip out "!!" String tablestyle = "tbl"; return "*~<span class=" + tablestyle + ">" + strMsg + "</span>"; } /** * Expects to be added to a GameModule. Adds itself to the * controls window and registers itself as a * {@link CommandEncoder} */ @Override public void addTo(Buildable b) { GameModule l_objGameModule = (GameModule) b; if (l_objGameModule.getChatter() != null) { // deleted code here which removed VASSAL elements but getChatter is always null at this point } l_objGameModule.setChatter(this); l_objGameModule.addCommandEncoder(this); l_objGameModule.addKeyStrokeSource(new KeyStrokeSource(this, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)); l_objGameModule.getPlayerWindow().addChatter(this); l_objGameModule.getControlPanel().add(this, BorderLayout.CENTER); final Prefs l_objModulePrefs = l_objGameModule.getPrefs(); // font pref FontConfigurer l_objChatFontConfigurer = null; FontConfigurer l_objChatFontConfigurer_Exist = (FontConfigurer)l_objModulePrefs.getOption("ChatFont"); if (l_objChatFontConfigurer_Exist == null) { l_objChatFontConfigurer = new FontConfigurer(CHAT_FONT, Resources.getString("Chatter.chat_font_preference")); //$NON-NLS-1$ //$NON-NLS-2$ l_objModulePrefs.addOption(Resources.getString("Chatter.chat_window"), l_objChatFontConfigurer); //$NON-NLS-1$ } else { l_objChatFontConfigurer = l_objChatFontConfigurer_Exist; } l_objChatFontConfigurer.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { setFont((Font) evt.getNewValue()); makeStyleSheet((Font) evt.getNewValue()); makeASLStyleSheet((Font) evt.getNewValue()); send(" "); send("- Chatter font changed"); send(" "); } }); l_objChatFontConfigurer.fireUpdate(); // buttons font pref FontConfigurer l_objButtonsFontConfigurer = null; FontConfigurer l_objButtonsFontConfigurer_Exist = (FontConfigurer)l_objModulePrefs.getOption("ButtonFont"); if (l_objButtonsFontConfigurer_Exist == null) { l_objButtonsFontConfigurer = new FontConfigurer(BUTTON_FONT, "Chatter's dice buttons font: "); //$NON-NLS-1$ //$NON-NLS-2$ l_objModulePrefs.addOption(Resources.getString("Chatter.chat_window"), l_objButtonsFontConfigurer); //$NON-NLS-1$ } else { l_objButtonsFontConfigurer = l_objButtonsFontConfigurer_Exist; } l_objButtonsFontConfigurer.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { SetButtonsFonts((Font) evt.getNewValue()); } }); l_objButtonsFontConfigurer.fireUpdate(); //background colour pref ColorConfigurer l_objBackgroundColor = null; ColorConfigurer l_objBackgroundColor_Exist = (ColorConfigurer)l_objModulePrefs.getOption(CHAT_BACKGROUND_COLOR); if (l_objBackgroundColor_Exist == null) { l_objBackgroundColor = new ColorConfigurer(CHAT_BACKGROUND_COLOR, "Background color: ", Color.white); //$NON-NLS-1$ l_objModulePrefs.addOption(Resources.getString("Chatter.chat_window"), l_objBackgroundColor); //$NON-NLS-1$ } else { l_objBackgroundColor = l_objBackgroundColor_Exist; } m_clrBackground = (Color) l_objModulePrefs.getValue(CHAT_BACKGROUND_COLOR); l_objBackgroundColor.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { m_clrBackground = (Color) e.getNewValue(); conversationPane.setBackground(m_clrBackground); } }); l_objBackgroundColor.fireUpdate(); // game message color pref Prefs globalPrefs = Prefs.getGlobalPrefs(); ColorConfigurer gameMsgColor = new ColorConfigurer("HTMLgameMessage1Color", Resources.getString("Chatter.game_messages_preference"), Color.black); gameMsgColor.addPropertyChangeListener((e) -> { gameMsg = (Color)e.getNewValue(); makeStyleSheet((Font)null); makeASLStyleSheet((Font)null); }); globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsgColor); gameMsg = (Color)globalPrefs.getValue("HTMLgameMessage1Color"); // sys messages pref ColorConfigurer l_objSystemMsgColor = null; ColorConfigurer l_objSystemMsgColor_Exist = (ColorConfigurer)l_objModulePrefs.getOption(SYS_MSG_COLOR); if (l_objSystemMsgColor_Exist == null) { l_objSystemMsgColor = new ColorConfigurer(SYS_MSG_COLOR, Resources.getString("Chatter.system_message_preference"), new Color(160, 160, 160)); //$NON-NLS-1$ l_objModulePrefs.addOption(Resources.getString("Chatter.chat_window"), l_objSystemMsgColor); //$NON-NLS-1$ } else { l_objSystemMsgColor = l_objSystemMsgColor_Exist; } systemMsg = (Color) l_objModulePrefs.getValue(SYS_MSG_COLOR); makeStyleSheet((Font)null); l_objSystemMsgColor.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { systemMsg = (Color) e.getNewValue(); makeStyleSheet((Font)null); } }); // myChat preference ColorConfigurer l_objMyChatColor = null; ColorConfigurer l_objMyChatColor_Exist = (ColorConfigurer)l_objModulePrefs.getOption(MY_CHAT_COLOR); if (l_objMyChatColor_Exist == null) { l_objMyChatColor = new ColorConfigurer(MY_CHAT_COLOR, "My Name and Text Messages" , Color.gray); //$NON-NLS-1$ l_objModulePrefs.addOption(Resources.getString("Chatter.chat_window"), l_objMyChatColor); //$NON-NLS-1$ } else { l_objMyChatColor = l_objMyChatColor_Exist; } gameMsg4 = (Color) l_objModulePrefs.getValue(MY_CHAT_COLOR); makeStyleSheet((Font)null); l_objMyChatColor.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { gameMsg4 = (Color) e.getNewValue(); makeStyleSheet((Font)null); } }); // other chat preference ColorConfigurer l_objOtherChatColor = null; ColorConfigurer l_objOtherChatColor_Exist = (ColorConfigurer)l_objModulePrefs.getOption(OTHER_CHAT_COLOR); if (l_objOtherChatColor_Exist == null) { l_objOtherChatColor = new ColorConfigurer(OTHER_CHAT_COLOR, Resources.getString("Chatter.other_text_preference"), Color.black); //$NON-NLS-1$ l_objModulePrefs.addOption(Resources.getString("Chatter.chat_window"), l_objOtherChatColor); //$NON-NLS-1$ } else { l_objOtherChatColor = l_objOtherChatColor_Exist; } otherChat = (Color) l_objModulePrefs.getValue(OTHER_CHAT_COLOR); makeStyleSheet((Font)null); l_objOtherChatColor.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { otherChat = (Color) e.getNewValue(); makeStyleSheet((Font)null); } }); // dice chat pref ColorConfigurer l_objDiceChatColor = null; ColorConfigurer l_objDiceChatColor_Exist = (ColorConfigurer)l_objModulePrefs.getOption(DICE_CHAT_COLOR); if (l_objDiceChatColor_Exist == null) { l_objDiceChatColor = new ColorConfigurer(DICE_CHAT_COLOR, "Dice Results font color: ", Color.black); //$NON-NLS-1$ l_objModulePrefs.addOption(Resources.getString("Chatter.chat_window"), l_objDiceChatColor); //$NON-NLS-1$ } else { l_objDiceChatColor = l_objDiceChatColor_Exist; } gameMsg5 = (Color) l_objModulePrefs.getValue(DICE_CHAT_COLOR); makeStyleSheet((Font)null); l_objDiceChatColor.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { gameMsg5 = (Color) e.getNewValue(); makeStyleSheet((Font)null); } }); // dice images pref BooleanConfigurer l_objUseDiceImagesOption = null; BooleanConfigurer l_objUseDiceImagesOption_Exist = (BooleanConfigurer)l_objModulePrefs.getOption(USE_DICE_IMAGES); if (l_objUseDiceImagesOption_Exist == null) { l_objUseDiceImagesOption = new BooleanConfigurer(USE_DICE_IMAGES, "Use images for dice rolls", Boolean.TRUE); //$NON-NLS-1$ l_objModulePrefs.addOption(Resources.getString("Chatter.chat_window"), l_objUseDiceImagesOption); //$NON-NLS-1$ } else { l_objUseDiceImagesOption = l_objUseDiceImagesOption_Exist; } m_bUseDiceImages = (Boolean) (l_objModulePrefs.getValue(USE_DICE_IMAGES)); l_objUseDiceImagesOption.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { m_bUseDiceImages = (Boolean) e.getNewValue(); } }); // dice stats pref BooleanConfigurer l_objShowDiceStatsOption = null; BooleanConfigurer l_objShowDiceStatsOption_Exist = (BooleanConfigurer)l_objModulePrefs.getOption(SHOW_DICE_STATS); if (l_objShowDiceStatsOption_Exist == null) { l_objShowDiceStatsOption = new BooleanConfigurer(SHOW_DICE_STATS, "Show dice stats after each dice rolls", Boolean.FALSE); //$NON-NLS-1$ l_objModulePrefs.addOption(Resources.getString("Chatter.chat_window"), l_objShowDiceStatsOption); //$NON-NLS-1$ } else { l_objShowDiceStatsOption = l_objShowDiceStatsOption_Exist; } m_bShowDiceStats = (Boolean) (l_objModulePrefs.getValue(SHOW_DICE_STATS)); l_objShowDiceStatsOption.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { m_bShowDiceStats = (Boolean) e.getNewValue(); } }); // coloured die pref StringEnumConfigurer coloredDiceColor = null; StringEnumConfigurer coloredDiceColor_Exist = (StringEnumConfigurer) l_objModulePrefs.getOption(COLORED_DICE_COLOR); if (coloredDiceColor_Exist==null){ coloredDiceColor = new StringEnumConfigurer(COLORED_DICE_COLOR, "Colored Die Color:", new String[] {"Black", "Blue","Cyan", "Purple", "Red", "Green", "Yellow", "Orange"} ); l_objModulePrefs.addOption(Resources.getString("Chatter.chat_window"), coloredDiceColor); } else { coloredDiceColor = coloredDiceColor_Exist; } coloredDiceColor.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { m_clrColoredDiceColor = (String) e.getNewValue(); if (m_clrColoredDiceColor==null){ m_clrColoredDiceColor = "Red"; } } }); m_clrColoredDiceColor = l_objModulePrefs.getStoredValue("coloredDiceColor"); final Set<String> COLORARRAY = new HashSet<String>(Arrays.asList( new String[] {"Black", "Blue","Cyan", "Purple", "Red", "Green", "Yellow", "Orange"})); if (!COLORARRAY.contains(m_clrColoredDiceColor)){ m_clrColoredDiceColor = "Red"; } // single die pref StringEnumConfigurer l_objColoredDieColor = null; StringEnumConfigurer l_objColoredDieColor_Exist = (StringEnumConfigurer)l_objModulePrefs.getOption(SINGLE_DIE_COLOR); if (l_objColoredDieColor_Exist == null) { l_objColoredDieColor = new StringEnumConfigurer(SINGLE_DIE_COLOR, "Single die color: ", new String[] {"Black", "Blue","Cyan", "Purple", "Red", "Green", "Yellow", "Orange"} ); l_objModulePrefs.addOption(Resources.getString("Chatter.chat_window"), l_objColoredDieColor); //$NON-NLS-1$ } else { l_objColoredDieColor = l_objColoredDieColor_Exist; } l_objColoredDieColor.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { m_clrSingleDieColor = (String) e.getNewValue(); if (m_clrSingleDieColor==null){ m_clrSingleDieColor = "Red"; } } }); m_clrSingleDieColor = l_objModulePrefs.getStoredValue("singleDieColor"); if (!COLORARRAY.contains(m_clrSingleDieColor)){ m_clrSingleDieColor = "Red"; } // third die pref StringEnumConfigurer l_objThirdDieColor = null; StringEnumConfigurer l_objThirdDieColor_Exist = (StringEnumConfigurer)l_objModulePrefs.getOption(THIRD_DIE_COLOR); if (l_objThirdDieColor == null) { l_objThirdDieColor = new StringEnumConfigurer(THIRD_DIE_COLOR, "Third die color: ", new String[] {"Black", "Blue","Cyan", "Purple", "Red", "Green", "Yellow", "Orange"} ); l_objModulePrefs.addOption(Resources.getString("Chatter.chat_window"), l_objThirdDieColor); //$NON-NLS-1$ } else { l_objThirdDieColor = l_objThirdDieColor_Exist; } l_objThirdDieColor.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { m_clrDustColoredDiceColor = (String) e.getNewValue(); if (m_clrDustColoredDiceColor==null){ m_clrDustColoredDiceColor = "Red"; } } }); m_clrDustColoredDiceColor = l_objModulePrefs.getStoredValue("thirdDieColor"); if (!COLORARRAY.contains(m_clrDustColoredDiceColor)){ m_clrDustColoredDiceColor = "Red"; } l_objThirdDieColor.fireUpdate(); // rule set pref StringEnumConfigurer l_objSpecialDiceRollNotificationLevel = (StringEnumConfigurer)l_objModulePrefs.getOption(NOTIFICATION_LEVEL); final String[] l_DROptions = { "None", "Snipers only", "Starter Kit", "Full ASL" }; if(l_objSpecialDiceRollNotificationLevel == null) { l_objSpecialDiceRollNotificationLevel = new StringEnumConfigurer(NOTIFICATION_LEVEL, "Notify about special DRs: ", l_DROptions); l_objSpecialDiceRollNotificationLevel.setValue("Full ASL"); l_objModulePrefs.addOption(Resources.getString("Chatter.chat_window"), l_objSpecialDiceRollNotificationLevel); } for(int i = 0; i < l_DROptions.length; ++i) { if (l_DROptions[i].equals(l_objSpecialDiceRollNotificationLevel.getValueString())) { m_DRNotificationLevel = i; break; } } // just for access from inside the event handler final StringEnumConfigurer __cfg = l_objSpecialDiceRollNotificationLevel; l_objSpecialDiceRollNotificationLevel.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { for(int i = 0; i < l_DROptions.length; ++i){ if(l_DROptions[i].equals(__cfg.getValueString())) { m_DRNotificationLevel = i; return; } } m_DRNotificationLevel = 3; } }); // Player Window pref l_objColoredDieColor.fireUpdate(); final BooleanConfigurer AlwaysOnTop = new BooleanConfigurer("PWAlwaysOnTop", "Player Window (menus, toolbar, chat) is always on top in uncombined application mode (requires a VASSAL restart)", false); getGameModule().getPrefs().addOption(preferenceTabName, AlwaysOnTop); } @Override public void add(Buildable b) { } @Override public void keyCommand(KeyStroke e) { if ((e.getKeyCode() == 0 || e.getKeyCode() == KeyEvent.CHAR_UNDEFINED) && !Character.isISOControl(e.getKeyChar())) { m_edtInputText.setText(m_edtInputText.getText() + e.getKeyChar()); } else if (e.isOnKeyRelease()) { switch (e.getKeyCode()) { case KeyEvent.VK_ENTER: if (m_edtInputText.getText().length() > 0) { send(formatChat(m_edtInputText.getText())); } m_edtInputText.setText(""); //$NON-NLS-1$ break; case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_DELETE: String s = m_edtInputText.getText(); if (s.length() > 0) { m_edtInputText.setText(s.substring(0, s.length() - 1)); } break; } } } private void FireDiceRoll() { for (ChatterListener objListener : chatter_listeners) objListener.DiceRoll(msgpartCategory, msgpartUser, msgpartSAN, Integer.parseInt(msgpartCdice), Integer.parseInt(msgpartWdice)); } public void addListener(ChatterListener toAdd) { chatter_listeners.add(toAdd); } public void removeListener(ChatterListener toRemove) { chatter_listeners.remove(toRemove); } public interface ChatterListener { public void DiceRoll(String strCategory, String strUser, String strSAN, int iFirstDice, int iSecondDice); } }
package afk.bot.london; import afk.bot.Robot; import afk.bot.RobotConfigManager; import afk.ge.ems.Constants; import java.util.UUID; /** * * @author Daniel */ public abstract class AbstractRobot implements Robot { private static int numBots = 0; public static final String MOTOR_TOP_SPEED = "Motor.topSpeed"; public static final String MOTOR_ANGULAR_VELOCITY = "Motor.angularVelocity"; public static final String LIFE_MAX_HP = "Life.maxHp"; public static final String TURRET_ANGULAR_VELOCITY = "Turret.angularVelocity"; public static final String BARREL_ANGULAR_VELOCITY = "Barrel.angularVelocity"; public static final String VISION_DIST = "Vision.dist"; public static final String VISION_FOVY = "Vision.fovy"; public static final String VISION_FOVX = "Vision.fovx"; private int[] actions; protected RobotEvent events; private UUID id; private int botNum; private RobotConfigManager config; public AbstractRobot(int numActions) { actions = new int[numActions]; events = new RobotEvent(); id = UUID.randomUUID(); botNum = numBots++; } @Override public final void setConfigManager(RobotConfigManager config) { this.config = config; } @Override public final RobotConfigManager getConfigManager() { return config; } @Override public void init() { setName(getClass().getSimpleName()); } /** * Set the type of this robot. e.g. small tank, large helicopter, etc. * * @param type */ protected final void setType(String type) { setProperty("type", type); } /** * Set the name of this robot. e.g. "The Karl Device" or "Mega J" * * @param name */ protected final void setName(String name) { setProperty("name", name); } private void setProperty(String key, String value) { if (config == null) { throw new RuntimeException("Error: No config manager!"); } config.setProperty(id, key, value); } private String getProperty(String key) { if (config == null) { throw new RuntimeException("Error: No config manager!"); } return config.getProperty(id, key); } private Object getConstant(String key) { if (config == null) { throw new RuntimeException("Error: No config manager!"); } return config.getConstant(id, key); } @Override public final UUID getId() { return id; } @Override public final int getBotNum() { return botNum; } /** * Get the top speed of the robot in units per game tick. * @return the top speed of the robot. */ public final float getTopSpeed() { return (Float)getConstant(MOTOR_TOP_SPEED); } /** * Get the angular velocity (rotation speed) of the robot in degrees * per game tick. * @return the angular velocity of the robot. */ public final float getAngularVelocity() { return (Float)getConstant(MOTOR_ANGULAR_VELOCITY); } /** * Get the maximum life of the robot. * @return the maximum life of the robot. */ public final float getMaxLife() { return (Float)getConstant(LIFE_MAX_HP); } /** * Get the angular velocity of the robot's turret. * @return the angular velocity of the robot's turret. */ public final float getTurretAngularVelocity() { return (Float)getConstant(TURRET_ANGULAR_VELOCITY); } /** * Get the angular velocity of the robot's barrel. * @return the angular velocity of the robot's barrel. */ public final float getBarrelAngularVelocity() { return (Float)getConstant(BARREL_ANGULAR_VELOCITY); } /** * Get how far the robot can see. * @return the view distance of the robot. */ public final float getViewDistance() { return (Float)getConstant(VISION_DIST); } /** * Get the vertical field of view of the robot in degrees. * @return the vertical field of view of the robot. */ public final float getVerticalFOV() { return (Float)getConstant(VISION_FOVY); } /** * Get the horizontal field of view of the robot in degrees. * @return the horizontal field of view of the robot. */ public final float getHorizontalFOV() { return (Float)getConstant(VISION_FOVX); } /** * Instruct the robot to apply action to be run for a certain number * of ticks. * @param index the index of the action to set. * @param ticks the number of ticks to apply the action for. */ protected final void setActionValue(int index, int ticks) { if (ticks < 0) { throw new RuntimeException("Robot attempted to travel back in time!"); } actions[index] = ticks; } /** * Get the number of ticks an action is still running for. * e.g. getActionValue(MOVE_FORWARD) would tell you how much further your * tank will move forward with its current instructions. * @param index * @return */ protected final int getActionValue(int index) { return actions[index]; } @Override public final boolean[] getActions() { boolean[] flags = new boolean[actions.length]; for (int i = 0; i < actions.length; i++) { flags[i] = actions[i] > 0; } return flags; } @Override public final void clearActions() { for (int x = 0; x < actions.length; x++) { actions[x] = 0; } } @Override public final void setEvents(RobotEvent event) { this.events = event; } private String primitiveToString() { return getClass().getSimpleName(); } private String complexToString() { String name = config.getProperty(getId(), "name"); if (name == null || name.trim().isEmpty()) { name = primitiveToString(); } return name; } @Override public final String toString() { return config == null ? primitiveToString() : complexToString(); } }
package com.jmpmain.lvslrpg; import java.util.Vector; import com.jmpmain.lvslrpg.entities.LineEntity; import android.annotation.SuppressLint; import android.graphics.Canvas; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.view.MotionEvent; import android.view.SurfaceHolder; /** * Main game thread. * All game logic is managed here. */ public class GameThread extends Thread implements SensorEventListener{ /** Counter for updates per second(ups). */ private int updateCallCount; /** The updates per second of the previous second. */ public int ups; /** Last time fps second had elapsed. */ private long lastUpdateCallReset; /** * Last time game was updated. */ private long lastUpdate; /** * GameSurface Surface Holder. */ private SurfaceHolder surfaceHolder; /** * Main surface game is drawn to. */ private GameSurface gameSurface; /** * Thread running state. */ private boolean running; public int touchX; public int touchY; /** Current game map. */ public Map map; public LineEntity line; public Vector<LineEntity> enemies; public GameThread(SurfaceHolder holder, GameSurface surface){ surfaceHolder = holder; gameSurface = surface; updateCallCount = 0; ups = 0; lastUpdateCallReset = 0; line = new LineEntity(500/12, 500/12); line.setDirection(1, 0); line.setColor(128, 0, 255, 0); enemies = new Vector<LineEntity>(); { LineEntity enemy = new LineEntity(10/12, 500/12); enemy.setColor(128, 255, 255, 0); enemies.add(enemy); } { LineEntity enemy = new LineEntity(500/12, 10/12); enemy.setColor(128, 0, 255, 255); enemies.add(enemy); } { LineEntity enemy = new LineEntity(500/12, 1500/12); enemy.setColor(128, 0, 0, 255); enemies.add(enemy); } { LineEntity enemy = new LineEntity(1000/12, 500/12); enemy.setColor(128, 255, 0, 0); enemies.add(enemy); } setRunning(false); } /** * Set thread running state. */ public void setRunning(boolean r){ running = r; } /** * Screen touch handler. */ public void onTouchEvent(MotionEvent event){ if(event.getAction() == MotionEvent.ACTION_UP){ touchX = (int) event.getX(); touchY = (int) event.getY(); int radius = (int)((float)gameSurface.getWidth()*0.05); if(touchY > gameSurface.getHeight() - (radius*2 + 20) && touchY < gameSurface.getHeight() - 20){ //Left turn button pressed. if(touchX > 20 && touchX < radius*2 + 20){ if(line.getYVelocity() != 0){ line.setDirection(-1, 0); }else if(line.getXVelocity() != 0){ line.setDirection(0, 1); } } //Right turn button pressed. if(touchX > gameSurface.getWidth() - (radius*2 + 20) && touchX < gameSurface.getWidth() - 20){ if(line.getYVelocity() != 0){ line.setDirection(1, 0); }else if(line.getXVelocity() != 0){ line.setDirection(0, -1); } } } }else if(event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE){ touchX = (int) event.getX(); touchY = (int) event.getY(); //line.setTarget(event.getX(), event.getY()); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Handle sensor accuracy change. } @Override public void onSensorChanged(SensorEvent event) { // TODO Handle sensor value changes. } @SuppressLint("WrongCall") private void drawCall(Canvas gameCanvas){ //Draw game state. gameCanvas = surfaceHolder.lockCanvas(); if(gameCanvas != null){ synchronized (surfaceHolder) { gameSurface.onDraw(gameCanvas); } surfaceHolder.unlockCanvasAndPost(gameCanvas); } } @Override /** * Main game loop. */ public void run() { Canvas gameCanvas = null; //Game loop. while (running) { //Check if game state should be updated. if(System.currentTimeMillis() - lastUpdate < 25){ drawCall(gameCanvas); continue; } lastUpdate = System.currentTimeMillis(); long currentTimeMillis = System.currentTimeMillis(); //Update debug parameters. if(BuildConfig.DEBUG){ updateCallCount++; if(System.currentTimeMillis() - lastUpdateCallReset > 1000){ lastUpdateCallReset = System.currentTimeMillis(); ups = updateCallCount; updateCallCount = 0; } } line.update(currentTimeMillis); for(int i = 0; i < enemies.size(); i++){ enemies.get(i).setTarget(line.getX(), line.getY()); enemies.get(i).update(currentTimeMillis); if(enemies.get(i).dead){ enemies.remove(i); i } }drawCall(gameCanvas); } } }
package matlabcontrol; import java.awt.EventQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicLong; import com.mathworks.jmi.Matlab; import com.mathworks.jmi.NativeMatlab; class JMIWrapper { /** * Map of unique identifier to stored object. */ private static final ConcurrentHashMap<String, StoredObject> STORED_OBJECTS = new ConcurrentHashMap<String, StoredObject>(); /** * The fully qualified name of this class. */ private static final String CLASS_NAME = JMIWrapper.class.getName(); private JMIWrapper() { } /** * Retrieves the stored object. If it is not to be kept permanently then the reference will no longer be kept. * * @param id * @return */ public static Object retrieveStoredObject(String id) { Object obj = null; StoredObject stored = STORED_OBJECTS.get(id); if(stored != null) { obj = stored.object; if(!stored.storePermanently) { STORED_OBJECTS.remove(id); } } return obj; } /** * @see MatlabInteractor#storeObject(java.lang.Object, boolean) */ static String storeObject(Object obj, boolean storePermanently) { StoredObject stored = new StoredObject(obj, storePermanently); STORED_OBJECTS.put(stored.id, stored); String retrievalString = CLASS_NAME + ".retrieveStoredObject('" + stored.id + "')"; return retrievalString; } /** * An object stored by matlabcontrol that can be accessed via {@link #retrieveStoredObject(java.lang.String)}. */ private static class StoredObject { private static AtomicLong _creationCounter = new AtomicLong(); private final Object object; private final boolean storePermanently; private final String id; private StoredObject(Object object, boolean storePermanently) { this.object = object; this.storePermanently = storePermanently; this.id = "STORED_OBJECT_" + _creationCounter.incrementAndGet(); } } /** * @see MatlabInteractor#exit() */ static void exit() throws MatlabInvocationException { invoke(new Runnable() { @Override public void run() { try { Matlab.mtFevalConsoleOutput("exit", null, 0); } catch (Exception e) { } } }); } /** * @see MatlabInteractor#setVariable(java.lang.String, java.lang.Object) */ static void setVariable(String variableName, Object value) throws MatlabInvocationException { feval("assignin", new Object[] { "base", variableName, value }); } /** * @see MatlabInteractor#getVariable(java.lang.String) */ static Object getVariable(String variableName) throws MatlabInvocationException { return returningEval(variableName, 1); } /** * @see MatlabInteractor#eval(java.lang.String) */ static void eval(final String command) throws MatlabInvocationException { returningEval(command, 0); } /** * @see MatlabInteractor#returningEval(java.lang.String, int) */ static Object returningEval(final String command, final int returnCount) throws MatlabInvocationException { return returningFeval("eval", new Object[]{ command }, returnCount); } /** * @see MatlabInteractor#returningFeval(java.lang.String, java.lang.Object[]) */ static void feval(final String functionName, final Object[] args) throws MatlabInvocationException { returningFeval(functionName, args, 0); } /** * @see MatlabInteractor#returningFeval(java.lang.String, java.lang.Object[], int) */ static Object returningFeval(final String functionName, final Object[] args, final int returnCount) throws MatlabInvocationException { return invokeAndWait(new Callable<Object>() { @Override public Object call() throws Exception { return Matlab.mtFevalConsoleOutput(functionName, args, returnCount); } }); } /** * @see MatlabInteractor#returningFeval(java.lang.String, java.lang.Object[]) */ static Object returningFeval(final String functionName, final Object[] args) throws MatlabInvocationException { return invokeAndWait(new Callable<Object>() { @Override public Object call() throws Exception { //Get the number of arguments that will be returned int nargout = 0; Object result = Matlab.mtFevalConsoleOutput("nargout", new String[] { functionName }, 1); nargout = (int) ((double[]) result)[0]; //If an unlimited number of arguments (represented by -1), throw an exception if(nargout == -1) { throw new MatlabInvocationException(functionName + " has a variable number of return arguments. " + "Instead used returningFeval(String, Object[], int) with the return count specified."); } return Matlab.mtFevalConsoleOutput(functionName, args, nargout); } }); } private static void invoke(final Runnable runnable) { if(NativeMatlab.nativeIsMatlabThread()) { runnable.run(); } else { Matlab.whenMatlabReady(runnable); } } private static <T> T invokeAndWait(final Callable<T> callable) throws MatlabInvocationException { T result; if(EventQueue.isDispatchThread()) { throw new MatlabInvocationException(MatlabInvocationException.EVENT_DISPATCH_THREAD_MSG); } else if(NativeMatlab.nativeIsMatlabThread()) { try { result = callable.call(); } catch(Exception e) { throw new MatlabInvocationException(MatlabInvocationException.INTERNAL_EXCEPTION_MSG, e); } } else { final ArrayBlockingQueue<MatlabReturn<T>> returnQueue = new ArrayBlockingQueue<MatlabReturn<T>>(1); Matlab.whenMatlabReady(new Runnable() { @Override public void run() { try { returnQueue.add(new MatlabReturn<T>(callable.call())); } catch(Exception e) { returnQueue.add(new MatlabReturn<T>(e)); } } }); try { //Wait for MATLAB's main thread to finish computation MatlabReturn<T> matlabReturn = returnQueue.take(); //If exception was thrown, rethrow it if(matlabReturn.exceptionThrown) { if(matlabReturn.exception instanceof MatlabInvocationException) { throw (MatlabInvocationException) matlabReturn.exception; } else { Throwable cause = new ThrowableWrapper(matlabReturn.exception); throw new MatlabInvocationException(MatlabInvocationException.INTERNAL_EXCEPTION_MSG, cause); } } //Return value computed by MATLAB else { result = matlabReturn.value; } } catch(InterruptedException e) { throw new MatlabInvocationException(MatlabInvocationException.INTERRUPTED_MSG, e); } } return result; } /** * Data returned from MATLAB. */ private static class MatlabReturn<T> { private final boolean exceptionThrown; private final T value; private final Exception exception; MatlabReturn(T value) { this.exceptionThrown = false; this.value = value; this.exception = null; } MatlabReturn(Exception exception) { this.exceptionThrown = true; this.value = null; this.exception = exception; } } }
package client.games; import battleships.backend.BattleShipsGameState; import battleships.gui.BattleShipsInputUnit; import battleships.gui.ContentPanel; import battleships.gui.GUIUpdater; import battleships.gui.listeners.BattleShipsGamePanelListeners; import battleships.gui.panels.BattleShipsPanel; import battleships.gui.panels.BattleshipGamePanels; import game.api.GameState; import game.init.Runner; import game.io.OutputUnit; import generics.GameIoFactory; import generics.GameOutputUnit; import javax.swing.*; import translator.CoordinateTranslator; import translator.TranslatorAdapter; public class BattleShipsGame implements GameStartup{ private GameState gameState; private GameIoFactory ioFactory; private JPanel contentPanel; public BattleShipsGame(){ setupObjects(); } private void setupObjects(){ GameState gameState = new BattleShipsGameState(); gameState.reset(); BattleShipsInputUnit inputUnit = new BattleShipsInputUnit(); TranslatorAdapter ta = new TranslatorAdapter(new CoordinateTranslator()); BattleshipGamePanels gamePanels = new BattleshipGamePanels(gameState, ta); BattleshipGamePanels gamePanels2 = new BattleshipGamePanels(gameState, ta); JPanel p1Panel = gamePanels.getPlayer1(); JPanel p2Panel = gamePanels.getPlayer2(); BattleShipsGamePanelListeners panelListener = new BattleShipsGamePanelListeners(p1Panel, inputUnit, ta); panelListener.addButtonListeners(); panelListener = new BattleShipsGamePanelListeners(p2Panel, inputUnit, ta); panelListener.addButtonListeners(); panelListener = new BattleShipsGamePanelListeners(gamePanels2.getPlayer1(), inputUnit, ta); panelListener.addButtonListeners(); panelListener = new BattleShipsGamePanelListeners(gamePanels2.getPlayer2(), inputUnit, ta); panelListener.addButtonListeners(); ContentPanel contentPanel = new ContentPanel(inputUnit, p2Panel); JPanel normalGamePanel = new BattleShipsPanel(gamePanels2.getPlayer1(), gamePanels2.getPlayer2()); GUIUpdater guiUpdater = new GUIUpdater(contentPanel, p1Panel, p2Panel, normalGamePanel); OutputUnit outputUnit = new GameOutputUnit(guiUpdater); this.gameState = gameState; this.ioFactory = new GameIoFactory(inputUnit, outputUnit); this.contentPanel = contentPanel; } @Override public JPanel getContentPane() { return contentPanel; } @Override public void start() { new Runner(gameState, ioFactory).run(); } }
package com.haskforce; import com.haskforce.jps.model.JpsHaskellModelSerializerExtension; import com.haskforce.utils.ExecUtil; import com.intellij.openapi.projectRoots.AdditionalDataConfigurable; import com.intellij.openapi.projectRoots.SdkAdditionalData; import com.intellij.openapi.projectRoots.SdkModel; import com.intellij.openapi.projectRoots.SdkModificator; import com.intellij.openapi.projectRoots.SdkType; import com.intellij.openapi.util.SystemInfo; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.File; public class HaskellSdkType extends SdkType { public HaskellSdkType() { super(JpsHaskellModelSerializerExtension.HASKELL_SDK_TYPE_ID); } @NotNull public static HaskellSdkType getInstance() { return SdkType.findInstance(HaskellSdkType.class); } @Override public Icon getIcon() { return HaskellIcons.FILE; } @Nullable @Override public AdditionalDataConfigurable createAdditionalDataConfigurable(SdkModel sdkModel, SdkModificator sdkModificator) { return null; } @Override public String getPresentableName() { return JpsHaskellModelSerializerExtension.HASKELL_SDK_TYPE_ID; } @Override public void saveAdditionalData(@NotNull SdkAdditionalData additionalData, @NotNull Element additional) { } @Override public boolean isValidSdkHome(String path) { return getVersionString(path) != null; } @Override public String suggestSdkName(String currentSdkName, String sdkHome) { return "GHC"; } @Nullable @Override public String getVersionString(final String sdkHome) { if (sdkHome == null) { return null; } File ghc = getExecutable(sdkHome); if (ghc.canExecute()) { return ExecUtil.run(ghc.getPath() + " --numeric-version"); } return null; } @Nullable @Override public String suggestHomePath() { String libPath = suggestGhcLibDir(); if (libPath == null) { return null; } return new File(libPath).getParentFile().getParent(); } /** * Returns the value of ghc --print-libdir if ghc is available in PATH. */ @Nullable public static String suggestGhcLibDir() { // Try running whatever GHC we have in $PATH. return ExecUtil.run("ghc --print-libdir"); } /** * Best effort at locating GHC according to given path. */ @NotNull public static File getExecutable(@NotNull final String path) { // We might get called with /usr/local/bin, or the true SDK // path. The goal is to run ghc at this stage, so adapt to whatever. String extra = path.endsWith("bin") ? "" : File.separator + "bin"; return new File(path + extra, SystemInfo.isWindows ? "ghc.exe" : "ghc"); } }
package com.jonasry.stereosvr; import java.awt.image.BufferedImage; public class Barrel { public static final boolean ENABLED = Boolean.getBoolean("corrections.barrel"); public static final double STRENGTH = Integer.getInteger("corrections.barrel.strength", 0); public static final double ZOOM = 1; public static BufferedImage applyCorrection(BufferedImage image) { if (!ENABLED) { return image; } final int width = image.getWidth(); final int height = image.getHeight(); final int halfWidth = width / 2; final int halfHeight = height / 2; final double strength = Math.max(STRENGTH, 0.00001); final double correctionRadius = Math.sqrt(width * width + height * height) / strength; System.out.println("Applying Barrel Distortion Correction using correctionRadius=" + correctionRadius); final BufferedImage output = new BufferedImage(width, height, image.getType()); for (int y = 0; y < width; y++) { for (int x = 0; x < width; x++) { final int dx = x - halfWidth; final int dy = y - halfHeight; final double distance = Math.sqrt(dx * dx + dy * dy); final double r = distance / correctionRadius; double theta = 1; if (r != 0) { theta = Math.atan(r) / r; } final int sx = (int) Math.round(halfWidth + theta * dx * ZOOM); final int sy = (int) Math.round(halfHeight + theta * dy * ZOOM); if (sx < width && sx >= 0 && sy < height && sy >= 0) { output.setRGB(x, y, image.getRGB(sx, sy)); } } } return output; } }
package com.opencms.file; import java.io.*; import java.util.*; import java.util.zip.*; import java.text.*; import java.security.*; import java.lang.reflect.*; import org.w3c.dom.*; import com.opencms.template.*; import com.opencms.core.*; public class CmsRegistry extends A_CmsXmlContent implements I_CmsRegistry { /** * The xml-document representing the registry. */ private Document m_xmlReg; /** * The filename for the registry. */ private String m_regFileName; /** * A hashtable with shortcuts into the dom-structure for each module. */ private Hashtable m_modules = new Hashtable(); /** * The cms-object to get access to the system with the context of the current user. */ private CmsObject m_cms = null; /** * The date-format to use. */ private SimpleDateFormat m_dateFormat = new java.text.SimpleDateFormat("MM.dd.yyyy"); /** * A message digest to check the resource-codes */ private MessageDigest m_digest; /** * Declaration of Module event-method names. */ private static final String C_UPLOAD_EVENT_METHOD_NAME = "moduleWasUploaded"; private static final String C_UPDATE_PARAMETER_EVENT_METHOD_NAME = "moduleParameterWasUpdated"; private static final String C_DELETE_EVENT_METHOD_NAME = "moduleWasDeleted"; /** * Declaration of an empty module in the registry. */ private static final String[] C_EMPTY_MODULE = { "<module><name>", "</name><nicename>", "</nicename><version>", "</version><description>", "</description><author>", "</author><email/><creationdate>", "</creationdate><view/><documentation/><dependencies/><maintenance_class/><parameters/><repository/></module>" }; /** * Creates a new CmsRegistry for a user. The cms-object represents the current state of the current user. * * @param CmsObject the cms-object to get access to the system */ public CmsRegistry(CmsRegistry reg, CmsObject cms) { super(); // there is no need of a real copy for this parameters m_modules = reg.m_modules; m_regFileName = reg.m_regFileName; m_xmlReg = reg.m_xmlReg; // store the cms-object for this instance. m_cms = cms; try { m_digest = MessageDigest.getInstance(CmsImport.C_IMPORT_DIGEST); } catch (NoSuchAlgorithmException e) { m_digest = null; } } /** * Creates a new CmsRegistry. The regFileName is the path to the registry-file in * the server filesystem. * * @param String regFileName the path to the registry-file in the server fs. */ public CmsRegistry(String regFileName) throws CmsException { super(); try { // store the filename m_regFileName = regFileName; // get the file File xmlFile = new File(m_regFileName); // get a buffered reader BufferedReader reader = new BufferedReader(new FileReader(xmlFile)); StringBuffer content = new StringBuffer(); String buffer = ""; do { content.append(buffer); buffer = reader.readLine(); } while (buffer != null); reader.close(); // parse the registry-xmlfile and store it. m_xmlReg = parse(content.toString()); init(); } catch (Exception exc) { throw new CmsException("couldn't init registry", CmsException.C_REGISTRY_ERROR, exc); } } /** * Checks, if the dependencies are fullfilled. * @param module the dom-element describing the new module. * @returns, if the dependencies are fullfilled, or not. */ private Vector checkDependencies(Element module) throws CmsException { Vector retValue = new Vector(); try { Element dependencies = (Element) (module.getElementsByTagName("dependencies").item(0)); NodeList deps = dependencies.getElementsByTagName("dependency"); for (int i = 0; i < deps.getLength(); i++) { String name = ((Element) deps.item(i)).getElementsByTagName("name").item(0).getFirstChild().getNodeValue(); int minVersion = Integer.parseInt(((Element) deps.item(i)).getElementsByTagName("minversion").item(0).getFirstChild().getNodeValue()); int maxVersion = Integer.parseInt(((Element) deps.item(i)).getElementsByTagName("maxversion").item(0).getFirstChild().getNodeValue()); // get the version of the needed repository int currentVersion = getModuleVersion(name); if( currentVersion == -1 ) { retValue.addElement("The needed module " + name + " dosen't exists"); } else if( currentVersion < minVersion ) { retValue.addElement("Module " + name + " version " + minVersion + " is not high enougth" ); } else if( ( maxVersion != C_ANY_VERSION ) && (currentVersion > maxVersion) ) { retValue.addElement("Module " + name + " version " + maxVersion + " is to high"); } } } catch (Exception exc) { throw new CmsException("Could not check the dependencies", CmsException.C_REGISTRY_ERROR, exc); } return retValue; } /** * Checks if the type of the value is correct. * @param type the type that the value should have.. * @param value the value to check. */ private boolean checkType(String type, String value) { type = type.toLowerCase(); try { if("string".equals(type) ) { if( value != null) { return true; } else { return false; } } else if("int".equals(type) || "integer".equals(type)) { Integer.parseInt(value); return true; } else if("float".equals(type)) { Float.valueOf(value); return true; } else if("boolean".equals(type)) { Boolean.valueOf(value); return true; } else if("long".equals(type)) { Long.valueOf(value); return true; } else if("double".equals(type)) { Double.valueOf(value); return true; } else if("byte".equals(type)) { Byte.valueOf(value); return true; } else { // the type dosen't exist return false; } } catch(Exception exc) { // the type of the value was wrong return false; } } /** * This method clones the registry. * * @param CmsObject the current cms-object to get access to the system. * @return the cloned registry. */ public I_CmsRegistry clone(CmsObject cms) { return new CmsRegistry(this, cms); } /** * This method creates a new module in the repository. * * @param String modulename the name of the module. * @param String niceModulename another name of the module. * @param String description the description of the module. * @param String author the name of the author. * @param long createDate the creation date of the module * @param int version the version number of the module. * @throws CmsException if the user has no right to create a new module. */ public void createModule(String modulename, String niceModulename, String description, String author, long createDate, int version) throws CmsException { createModule(modulename, niceModulename, description, author, m_dateFormat.format(new Date(createDate)), version); } /** * This method creates a new module in the repository. * * @param String modulename the name of the module. * @param String niceModulename another name of the module. * @param String description the description of the module. * @param String author the name of the author. * @param String createDate the creation date of the module in the format: mm.dd.yyyy * @param int version the version number of the module. * @throws CmsException if the user has no right to create a new module. */ public void createModule(String modulename, String niceModulename, String description, String author, String createDate, int version) throws CmsException { // find out if the module exists already if (moduleExists(modulename)) { throw new CmsException("Module exists already " + modulename, CmsException.C_REGISTRY_ERROR); } // check if the user is allowed to perform this action if (!hasAccess()) { throw new CmsException("No access to perform the action 'createModule'", CmsException.C_REGISTRY_ERROR); } // create the new module in the registry String moduleString = C_EMPTY_MODULE[0] + modulename; moduleString += C_EMPTY_MODULE[1] + niceModulename; moduleString += C_EMPTY_MODULE[2] + version; moduleString += C_EMPTY_MODULE[3] + description; moduleString += C_EMPTY_MODULE[4] + author; moduleString += C_EMPTY_MODULE[5] + createDate; moduleString += C_EMPTY_MODULE[6]; Document doc = parse(moduleString); m_xmlReg.getElementsByTagName("modules").item(0).appendChild(getXmlParser().importNode(m_xmlReg, doc.getFirstChild())); saveRegistry(); } /** * This method checks which modules need this module. If a module depends on this the name * will be returned in the vector. * @param modulename The name of the module to check. * @returns a Vector with modulenames that depends on the overgiven module. */ public Vector deleteCheckDependencies(String modulename) throws CmsException { Enumeration names = getModuleNames(); Vector modules; Vector minVersions; Vector maxVersions; Vector result = new Vector(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); modules = new Vector(); minVersions = new Vector(); maxVersions = new Vector(); getModuleDependencies(name, modules, minVersions, maxVersions); // needs this module the module to test? if (modules.contains(modulename)) { // yes - store it in the result result.addElement(name); } } return result; } /** * This method checks for conflicting files before the deletion of a module. * It uses several Vectors to return the different conflicting files. * * @param modulename the name of the module that should be deleted. * @param filesWithProperty a return value. The files that are marked with the module-property for this module. * @param missingFiles a return value. The files that are missing. * @param wrongChecksum a return value. The files that should be deleted but have another checksum as at import-time. * @param filesInUse a return value. The files that should be deleted but are in use by other modules. * @param resourcesForProject a return value. The files that should be copied to a project to delete. */ public void deleteGetConflictingFileNames(String modulename, Vector filesWithProperty, Vector missingFiles, Vector wrongChecksum, Vector filesInUse, Vector resourcesForProject) throws CmsException { // the files and checksums for this module Vector moduleFiles = new Vector(); Vector moduleChecksums = new Vector(); getModuleFiles(modulename, moduleFiles, moduleChecksums); // the files and checksums for all other modules Vector otherFiles = new Vector(); Vector otherChecksums = new Vector(); Enumeration modules = getModuleNames(); while (modules.hasMoreElements()) { String module = (String) modules.nextElement(); // get the files only for modules that are not for the current module. if (!module.equals(modulename)) { // get the files getModuleFiles(module, otherFiles, otherChecksums); } } for (int i = 0; i < moduleFiles.size(); i++) { // get the current file and checksum String currentFile = (String) moduleFiles.elementAt(i); String currentChecksum = (String) moduleChecksums.elementAt(i); CmsFile file = null; try { String resource = currentFile.substring(0, currentFile.indexOf("/",1) + 1); if(!resourcesForProject.contains(resource)) { // add the resource, if it dosen't already exist resourcesForProject.addElement(resource); } } catch(StringIndexOutOfBoundsException exc) { // this is a resource in root-folder: ignore the excpetion } // is it a file - then check all the possibilities if (!currentFile.endsWith("/")) { // exists the file in the cms? try { file = m_cms.readFile(currentFile); } catch (CmsException exc) { // the file dosen't exist - mark it as deleted missingFiles.addElement(currentFile); } // is the file in use of another module? if (otherFiles.contains(currentFile)) { // yes - mark it as in use filesInUse.addElement(currentFile); } // was the file changed? if (file != null) { // create the current digest-content for the file String digestContent = com.opencms.util.Encoder.escape(new String(m_digest.digest(file.getContents()))); if (!currentChecksum.equals(digestContent)) { // the file was changed, the checksums are different wrongChecksum.addElement(currentFile); } } } } // determine the files with the property for this module. Vector files = m_cms.getFilesWithProperty("module", modulename + "_" + getModuleVersion(modulename)); for(int i = 0; i < files.size(); i++) { String currentFile = (String)files.elementAt(i); if(!moduleFiles.contains(currentFile )) { // is the file in use of another module? if (!otherFiles.contains(currentFile)) { filesWithProperty.addElement(currentFile); try { String resource = currentFile.substring(0, currentFile.indexOf("/",1) + 1); if(!resourcesForProject.contains(resource)) { // add the resource, if it dosen't already exist resourcesForProject.addElement(resource); } } catch(StringIndexOutOfBoundsException exc) { // this is a resource in root-folder: ignore the excpetion } } } } } /** * Deletes a module. This method is synchronized, so only one module can be deleted at one time. * * @param module-name the name of the module that should be deleted. * @param exclusion a Vector with resource-names that should be excluded from this deletion. */ public synchronized void deleteModule(String module, Vector exclusion) throws CmsException { // check if the module exists if (!moduleExists(module)) { throw new CmsException("Module '"+module+"' does not exist", CmsException.C_REGISTRY_ERROR); } // check if the user is allowed to perform this action if (!hasAccess()) { throw new CmsException("No access to perform the action 'deleteModule'", CmsException.C_REGISTRY_ERROR); } // check, if deletion is allowed Vector deps = deleteCheckDependencies(module); if(deps.size() != 0) { // there are dependencies - throw exception throw new CmsException("There are dependencies for the module " + module + ": deletion is not allowed.", CmsException.C_REGISTRY_ERROR); } // try to invoke the event-method for delete on this calss. Class eventClass = getModuleMaintenanceEventClass(module); try { Class declaration[] = {CmsObject.class}; Object arguments[] = {m_cms}; Method eventMethod = eventClass.getMethod(C_DELETE_EVENT_METHOD_NAME, declaration); eventMethod.invoke(null, arguments); } catch(Exception exc) { // ignore the exception. } // get the files, that are belonging to the module. Vector resourceNames = new Vector(); Vector missingFiles = new Vector(); Vector wrongChecksum = new Vector(); Vector filesInUse = new Vector(); Vector resourceCodes = new Vector(); // get files by property deleteGetConflictingFileNames(module, resourceNames, missingFiles, wrongChecksum, filesInUse, new Vector()); // get files by registry getModuleFiles(module, resourceNames, resourceCodes); // move through all resource-names and try to delete them for (int i = resourceNames.size() - 1; i >= 0; i try { String currentResource = (String) resourceNames.elementAt(i); if ((!exclusion.contains(currentResource)) && (!filesInUse.contains(currentResource))) { m_cms.lockResource(currentResource, true); if(currentResource.endsWith("/") ) { // this is a folder m_cms.deleteEmptyFolder(currentResource); } else { // this is a file m_cms.deleteFile(currentResource); } } } catch (CmsException exc) { // ignore the exception and delete the next resource. } } // delete all entries for the module in the registry Element moduleElement = getModuleElement(module); moduleElement.getParentNode().removeChild(moduleElement); saveRegistry(); try { init(); } catch (Exception exc) { throw new CmsException("couldn't init registry", CmsException.C_REGISTRY_ERROR, exc); } } /** * Deletes the view for a module. * * @param String the name of the module. */ public void deleteModuleView(String modulename) throws CmsException { // check if the user is allowed to perform this action if (!hasAccess()) { throw new CmsException("No access to perform the action 'deleteModuleView'", CmsException.C_REGISTRY_ERROR); } try { Element module = getModuleElement(modulename); Element view = (Element) (module.getElementsByTagName("view").item(0)); // delete all subnodes while(view.hasChildNodes()) { view.removeChild(view.getFirstChild()); } saveRegistry(); } catch (Exception exc) { // ignore the exception - reg is not welformed } } /** * This method exports a module to the filesystem. * * @param moduleName the name of the module to be exported. * @param String[] an array of resources to be exported. * @param fileName the name of the file to write the export to. */ public void exportModule(String moduleName, String[] resources, String fileName) throws CmsException { // check if the user is allowed to import a module. if (!hasAccess()) { throw new CmsException("No access to perform the action 'exportModule'", CmsException.C_REGISTRY_ERROR); } CmsExport exp = new CmsExport(fileName, resources, m_cms, getModuleElement(moduleName)); } /** * Gets a description of this content type. * For OpenCms internal use only. * @return Content type description. */ public String getContentDescription() { return "Registry"; } /** * This method returns the author of the module. * * @parameter String the name of the module. * @return java.lang.String the author of the module. */ public String getModuleAuthor(String modulename) { return getModuleData(modulename, "author"); } /** * This method returns the email of author of the module. * * @parameter String the name of the module. * @return java.lang.String the email of author of the module. */ public String getModuleAuthorEmail(String modulename) { return getModuleData(modulename, "email"); } /** * Gets the create date of the module. * * @parameter String the name of the module. * @return long the create date of the module. */ public long getModuleCreateDate(String modulname) { long retValue = -1; try { String value = getModuleData(modulname, "creationdate"); retValue = m_dateFormat.parse(value).getTime(); } catch (Exception exc) { // ignore the exception - reg is not welformed } return retValue; } /** * Private method to return module data like author. * * @param String modulename the name of the module. * @param String dataName the name of the tag to get the data from. * @returns String the value for the requested data. */ private String getModuleData(String module, String dataName) { String retValue = null; try { Element moduleElement = getModuleElement(module); retValue = moduleElement.getElementsByTagName(dataName).item(0).getFirstChild().getNodeValue(); } catch (Exception exc) { // ignore the exception - registry is not wellformed } return retValue; } /** * Returns the module dependencies for the module. * * @param module String the name of the module to check. * @param modules Vector in this parameter the names of the dependend modules will be returned. * @param minVersions Vector in this parameter the minimum versions of the dependend modules will be returned. * @param maxVersions Vector in this parameter the maximum versions of the dependend modules will be returned. * @return int the amount of dependencies for the module will be returned. */ public int getModuleDependencies(String modulename, Vector modules, Vector minVersions, Vector maxVersions) { try { Element module = getModuleElement(modulename); Element dependencies = (Element) (module.getElementsByTagName("dependencies").item(0)); NodeList deps = dependencies.getElementsByTagName("dependency"); for (int i = 0; i < deps.getLength(); i++) { modules.addElement(((Element) deps.item(i)).getElementsByTagName("name").item(0).getFirstChild().getNodeValue()); minVersions.addElement(((Element) deps.item(i)).getElementsByTagName("minversion").item(0).getFirstChild().getNodeValue()); maxVersions.addElement(((Element) deps.item(i)).getElementsByTagName("maxversion").item(0).getFirstChild().getNodeValue()); } } catch (Exception exc) { // ignore the exception - reg is not welformed } return modules.size(); } /** * Returns the description of the module. * * @parameter String the name of the module. * @return java.lang.String the description of the module. */ public String getModuleDescription(String module) { return getModuleData(module, "description"); } /** * Gets the url to the documentation of the module. * * @parameter String the name of the module. * @return java.lang.String the url to the documentation of the module. */ public String getModuleDocumentPath(String modulename) { return getModuleData(modulename, "documentation"); } /** * Private method to get the Element representing a module. * * @param String the name of the module. * */ private Element getModuleElement(String name) { return (Element) m_modules.get(name); } /** * Reads the module-element from the manifest in the zip-file. * @param string the name of the zip-file to read from. * @returns the module-element or null if it dosen't exist. */ private Element getModuleElementFromImport(String filename) { try { // get the zip-file ZipFile importZip = new ZipFile(filename); // read the minifest ZipEntry entry = importZip.getEntry("manifest.xml"); InputStream stream = importZip.getInputStream(entry); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String content = ""; String buffer = ""; do { content += buffer; buffer = reader.readLine(); } while (buffer != null); // parse the manifest Document manifest = parse(content); reader.close(); importZip.close(); // get the module-element return (Element)(manifest.getElementsByTagName("module").item(0)); } catch (Exception exc) { return null; } } /** * Returns all filenames and hashcodes belonging to the module. * * @param String modulname the name of the module. * @param retNames the names of the resources belonging to the module. * @param retCodes the hashcodes of the resources belonging to the module. * @return the amount of entrys. */ public int getModuleFiles(String modulename, Vector retNames, Vector retCodes) { try { Element module = getModuleElement(modulename); Element files = (Element) (module.getElementsByTagName("files").item(0)); NodeList file = files.getElementsByTagName("file"); for (int i = 0; i < file.getLength(); i++) { retNames.addElement(((Element) file.item(i)).getElementsByTagName("name").item(0).getFirstChild().getNodeValue()); retCodes.addElement(((Element) file.item(i)).getElementsByTagName("checksum").item(0).getFirstChild().getNodeValue()); } } catch (Exception exc) { // ignore the exception - reg is not welformed } return retNames.size(); } /** * Returns the class, that receives all maintenance-events for the module. * * @parameter String the name of the module. * @return java.lang.Class that receives all maintenance-events for the module. */ public Class getModuleMaintenanceEventClass(String modulname) { try { Vector repositories = new Vector(); String[] reposNoVector = getRepositories(); for (int i=0; i<reposNoVector.length; i++){ repositories.addElement(reposNoVector[i]); } ClassLoader loader = this.getClass().getClassLoader(); return loader.loadClass(getModuleData(modulname, "maintenance_class")); } catch(Exception exc) { return null; } } /** * Returns the name of the class, that receives all maintenance-events for the module. * * @parameter String the name of the module. * @return java.lang.Class that receives all maintenance-events for the module. */ public String getModuleMaintenanceEventName(String modulname) { return getModuleData(modulname, "maintenance_class"); } /** * Returns the names of all available modules. * * @return Enumeration the names of all available modules. */ public Enumeration getModuleNames() { return m_modules.keys(); } /** * Returns the nice name of the module. * * @parameter String the name of the module. * @return java.lang.String the description of the module. */ public String getModuleNiceName(String module) { return getModuleData(module, "nicename"); } /** * Gets a parameter for a module. * * @param modulename java.lang.String the name of the module. * @param parameter java.lang.String the name of the parameter to set. * @return value java.lang.String the value to set for the parameter. */ public String getModuleParameter(String modulename, String parameter) { String retValue = null; try { Element param = getModuleParameterElement(modulename, parameter); retValue = param.getElementsByTagName("value").item(0).getFirstChild().getNodeValue(); } catch (Exception exc) { // ignore the exception - parameter is not existent } return retValue; } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @return boolean the value for the parameter in the module. */ public boolean getModuleParameterBoolean(String modulname, String parameter) { if ("true".equals(getModuleParameter(modulname, parameter).toLowerCase())) { return true; } else { return false; } } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @param default the default value. * @return boolean the value for the parameter in the module. */ public Boolean getModuleParameterBoolean(String modulname, String parameter, Boolean defaultValue) { return new Boolean(getModuleParameterBoolean(modulname, parameter, defaultValue.booleanValue())); } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @param default the default value. * @return boolean the value for the parameter in the module. */ public boolean getModuleParameterBoolean(String modulname, String parameter, boolean defaultValue) { if (getModuleParameterBoolean(modulname, parameter)) { return true; } else { return defaultValue; } } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @param default the default value. * @return boolean the value for the parameter in the module. */ public byte getModuleParameterByte(String modulname, String parameter) { return Byte.parseByte(getModuleParameter(modulname, parameter)); } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @param default the default value. * @return boolean the value for the parameter in the module. */ public byte getModuleParameterByte(String modulname, String parameter, byte defaultValue) { try { return getModuleParameterByte(modulname, parameter); } catch (Exception exc) { return defaultValue; } } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @param default the default value. * @return boolean the value for the parameter in the module. */ public Byte getModuleParameterByte(String modulname, String parameter, Byte defaultValue) { return new Byte(getModuleParameterByte(modulname, parameter, defaultValue.byteValue())); } /** * Returns a description for parameter in a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @return String the description for the parameter in the module. */ public String getModuleParameterDescription(String modulname, String parameter) { String retValue = null; try { Element param = getModuleParameterElement(modulname, parameter); retValue = param.getElementsByTagName("description").item(0).getFirstChild().getNodeValue(); } catch (Exception exc) { // ignore the exception - parameter is not existent } return retValue; } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @return boolean the value for the parameter in the module. */ public double getModuleParameterDouble(String modulname, String parameter) { return Double.valueOf(getModuleParameter(modulname, parameter)).doubleValue(); } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @param default the default value. * @return boolean the value for the parameter in the module. */ public double getModuleParameterDouble(String modulname, String parameter, double defaultValue) { try { return getModuleParameterDouble(modulname, parameter); } catch (Exception exc) { return defaultValue; } } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @param default the default value. * @return boolean the value for the parameter in the module. */ public Double getModuleParameterDouble(String modulname, String parameter, Double defaultValue) { return new Double(getModuleParameterDouble(modulname, parameter, defaultValue.doubleValue())); } /** * Private method to get them XML-Element for a parameter in a module. * * @param modulename String the name of the module. * @param parameter String the name of the parameter. * @return Element the XML-Element corresponding to the parameter. */ private Element getModuleParameterElement(String modulename, String parameter) { Element retValue = null; try { Element module = getModuleElement(modulename); Element parameters = (Element) (module.getElementsByTagName("parameters").item(0)); NodeList para = parameters.getElementsByTagName("para"); for (int i = 0; i < para.getLength(); i++) { if (((Element) para.item(i)).getElementsByTagName("name").item(0).getFirstChild().getNodeValue().equals(parameter)) { // this is the element for the parameter. retValue = (Element) para.item(i); // stop searching - parameter was found break; } } } catch (Exception exc) { // ignore the exception - reg is not welformed } return retValue; } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @param default the default value. * @return boolean the value for the parameter in the module. */ public float getModuleParameterFloat(String modulname, String parameter) { return Float.valueOf(getModuleParameter(modulname, parameter)).floatValue(); } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @param default the default value. * @return boolean the value for the parameter in the module. */ public float getModuleParameterFloat(String modulname, String parameter, float defaultValue) { try { return getModuleParameterFloat(modulname, parameter); } catch (Exception exc) { return defaultValue; } } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @param default the default value. * @return boolean the value for the parameter in the module. */ public Float getModuleParameterFloat(String modulname, String parameter, Float defaultValue) { return new Float(getModuleParameterFloat(modulname, parameter, defaultValue.floatValue())); } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @return boolean the value for the parameter in the module. */ public int getModuleParameterInteger(String modulname, String parameter) { return Integer.parseInt(getModuleParameter(modulname, parameter)); } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @param default the default value. * @return boolean the value for the parameter in the module. */ public int getModuleParameterInteger(String modulname, String parameter, int defaultValue) { try { return getModuleParameterInteger(modulname, parameter); } catch (Exception exc) { return defaultValue; } } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @param default the default value. * @return boolean the value for the parameter in the module. */ public Integer getModuleParameterInteger(String modulname, String parameter, Integer defaultValue) { return new Integer(getModuleParameterInteger(modulname, parameter, defaultValue.intValue())); } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @param default the default value. * @return boolean the value for the parameter in the module. */ public long getModuleParameterLong(String modulname, String parameter) { return Long.valueOf(getModuleParameter(modulname, parameter)).longValue(); } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @param default the default value. * @return boolean the value for the parameter in the module. */ public long getModuleParameterLong(String modulname, String parameter, long defaultValue) { try { return getModuleParameterLong(modulname, parameter); } catch (Exception exc) { return defaultValue; } } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @param default the default value. * @return boolean the value for the parameter in the module. */ public Long getModuleParameterLong(String modulname, String parameter, Long defaultValue) { return new Long(getModuleParameterLong(modulname, parameter, defaultValue.longValue())); } /** * Gets all parameter-names for a module. * * @param modulename String the name of the module. * @return value String[] the names of the parameters for a module. */ public String[] getModuleParameterNames(String modulename) { String[] retValue = null; try { Element module = getModuleElement(modulename); Element parameters = (Element) (module.getElementsByTagName("parameters").item(0)); NodeList para = parameters.getElementsByTagName("para"); retValue = new String[para.getLength()]; for (int i = 0; i < para.getLength(); i++) { retValue[i] = ((Element) para.item(i)).getElementsByTagName("name").item(0).getFirstChild().getNodeValue(); } } catch (Exception exc) { // ignore the exception - reg is not welformed } return retValue; } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @return boolean the value for the parameter in the module. */ public String getModuleParameterString(String modulname, String parameter) { return getModuleParameter(modulname, parameter); } /** * Returns a parameter for a module. * * @param modulname String the name of the module. * @param parameter String the name of the parameter. * @param default the default value. * @return boolean the value for the parameter in the module. */ public String getModuleParameterString(String modulname, String parameter, String defaultValue) { try { return getModuleParameterString(modulname, parameter); } catch (Exception exc) { return defaultValue; } } /** * This method returns the type of a parameter in a module. * * @param modulename the name of the module. * @param parameter the name of the parameter. * @return the type of the parameter. */ public String getModuleParameterType(String modulename, String parameter) { String retValue = null; try { Element param = getModuleParameterElement(modulename, parameter); retValue = param.getElementsByTagName("type").item(0).getFirstChild().getNodeValue(); } catch (Exception exc) { // ignore the exception - parameter is not existent } return retValue; } /** * Returns all repositories for a module. * * @parameter String modulname the name of the module. * @return java.lang.String[] the reprositories of a module. */ public java.lang.String[] getModuleRepositories(String modulename) { String[] retValue = null; try { Element module = getModuleElement(modulename); Element repository = (Element) (module.getElementsByTagName("repository").item(0)); NodeList paths = repository.getElementsByTagName("path"); retValue = new String[paths.getLength()]; for (int i = 0; i < paths.getLength(); i++) { retValue[i] = paths.item(i).getFirstChild().getNodeValue(); } } catch (Exception exc) { // ignore the exception - reg is not welformed } return retValue; } /** * Returns the upload-date for the module. * * @parameter String the name of the module. * @return java.lang.String the upload-date for the module. */ public long getModuleUploadDate(String modulname) { long retValue = -1; try { String value = getModuleData(modulname, "uploaddate"); retValue = m_dateFormat.parse(value).getTime(); } catch (Exception exc) { // ignore the exception - reg is not welformed } return retValue; } /** * Returns the user-name of the user who had uploaded the module. * * @parameter String the name of the module. * @return java.lang.String the user-name of the user who had uploaded the module. */ public String getModuleUploadedBy(String modulename) { return getModuleData(modulename, "uploadedby"); } /** * This method returns the version of the module. * * @parameter String the name of the module. * @return java.lang.String the version of the module. */ public int getModuleVersion(String modulename) { int retValue = -1; try { retValue = Integer.parseInt(getModuleData(modulename, "version")); } catch (Exception exc) { // ignore the exception - reg is not welformed } return retValue; } /** * Returns the name of the view, that is implemented by the module. * * @parameter String the name of the module. * @return java.lang.String the name of the view, that is implemented by the module. */ public String getModuleViewName(String modulename) { String retValue = null; try { Element module = getModuleElement(modulename); Element view = (Element) (module.getElementsByTagName("view").item(0)); retValue = view.getElementsByTagName("name").item(0).getFirstChild().getNodeValue(); } catch (Exception exc) { // ignore the exception - reg is not welformed } return retValue; } /** * Returns the url to the view-url for the module within the system. * * @parameter String the name of the module. * @return java.lang.String the view-url to the module. */ public String getModuleViewUrl(String modulname) { String retValue = null; try { Element module = getModuleElement(modulname); Element view = (Element) (module.getElementsByTagName("view").item(0)); retValue = view.getElementsByTagName("url").item(0).getFirstChild().getNodeValue(); } catch (Exception exc) { // ignore the exception - reg is not welformed } return retValue; } /** * Returns all repositories for all modules. * * @return java.lang.String[] the reprositories of all modules. */ public java.lang.String[] getRepositories() { NodeList repositories = m_xmlReg.getElementsByTagName("repository"); Vector retValue = new Vector(); String[] retValueArray = new String[0]; for (int x = 0; x < repositories.getLength(); x++) { NodeList paths = ((Element) repositories.item(x)).getElementsByTagName("path"); for (int y = 0; y < paths.getLength(); y++) { retValue.addElement(paths.item(y).getFirstChild().getNodeValue()); } } retValueArray = new String[retValue.size()]; retValue.copyInto(retValueArray); return retValueArray; } /** * Returns all Resourcetypes and korresponding parameter for System and all modules. * * @parameter Vector names in this parameter the names of the Resourcetypes will be returned. * @parameter Vector launcherTypes in this parameters the launcherType will be returned(int). * @parameter Vector launcherClass in this parameters the launcherClass will be returned. * @parameter Vector resourceClass in this parameters the resourceClass will be returned. * @return int the amount of resourcetypes. */ public int getResourceTypes(Vector names, Vector launcherTypes, Vector launcherClass, Vector resourceClass){ try{ NodeList resTypes = m_xmlReg.getElementsByTagName("restype"); for (int x = 0; x < resTypes.getLength(); x++){ try{ String name = ((Element)resTypes.item(x)).getElementsByTagName("name").item(0).getFirstChild().getNodeValue(); String lType = ((Element)resTypes.item(x)).getElementsByTagName("launcherType").item(0).getFirstChild().getNodeValue(); String lClass = ""; try{ lClass = ((Element)resTypes.item(x)).getElementsByTagName("launcherClass").item(0).getFirstChild().getNodeValue(); }catch(Exception ex){ } String resClass = ((Element)resTypes.item(x)).getElementsByTagName("resourceClass").item(0).getFirstChild().getNodeValue(); names.addElement(name); launcherTypes.addElement(lType); launcherClass.addElement(lClass); resourceClass.addElement(resClass); }catch(Exception exc){ // ignore the exeption } } return names.size(); }catch(Exception e){ // no returnvalues return 0; } } /** * Returns a value for a system-key. * E.g. <code>&lt;system&gt;&lt;mailserver&gt;mail.server.com&lt;/mailserver&gt;&lt;/system&gt;</code> * can be requested via <code>getSystemValue("mailserver");</code> and returns "mail.server.com". * * @parameter String the key of the system-value. * @return the value for that system-key. */ public String getSystemValue(String key) { String retValue = null; try { Element systemElement = (Element)m_xmlReg.getElementsByTagName("system").item(0); retValue = systemElement.getElementsByTagName(key).item(0).getFirstChild().getNodeValue(); } catch (Exception exc) { // ignore the exception - registry is not wellformed } return retValue; } /** * Returns a vector of value for a system-key. * * @parameter String the key of the system-value. * @return the values for that system-key. */ public Hashtable getSystemValues(String key) { Hashtable retValue = new Hashtable(); try { Element systemElement = (Element)m_xmlReg.getElementsByTagName("system").item(0); NodeList list = systemElement.getElementsByTagName(key).item(0).getChildNodes(); for(int i=0; i < list.getLength(); i++) { retValue.put(list.item(i).getNodeName(), list.item(i).getFirstChild().getNodeValue()); } } catch (Exception exc) { // ignore the exception - registry is not wellformed } return retValue; } /** * Returns all views and korresponding urls for all modules. * * @parameter String[] views in this parameter the views will be returned. * @parameter String[] urls in this parameters the urls vor the views will be returned. * @return int the amount of views. */ public int getViews(Vector views, Vector urls) { try { NodeList viewList = m_xmlReg.getElementsByTagName("view"); for (int x = 0; x < viewList.getLength(); x++) { try { String name = ((Element) viewList.item(x)).getElementsByTagName("name").item(0).getFirstChild().getNodeValue(); String url = ((Element) viewList.item(x)).getElementsByTagName("url").item(0).getFirstChild().getNodeValue(); views.addElement(name); urls.addElement(url); } catch(Exception exc) { // ignore the exception and try the next view-pair. } } return views.size(); } catch (Exception exc) { // no return-vaules return 0; } } /** * Gets the expected tagname for the XML documents of this content type * @return Expected XML tagname. */ public String getXmlDocumentTagName() { return "registry"; } /** * Returns true if the user has write-access to the registry. Otherwise false. * @returns true if access is granted, else false. */ private boolean hasAccess() { // check the access - only the admin has write access. boolean retValue = false; try{ retValue = m_cms.isAdmin(); } catch(CmsException exc) { // ignore the exception - no access granted } return retValue; } /** * Checks the dependencies for a new Module. * @param moduleZip the name of the zipfile for the new module. * @return a Vector with dependencies that are not fullfilled. */ public Vector importCheckDependencies(String moduleZip) throws CmsException { Element newModule = getModuleElementFromImport(moduleZip); return checkDependencies(newModule); } /** * Checks for files that already exist in the system but should be replaced by the module. * * @param moduleZip The name of the zip-file to import. * @returns The complete paths to the resources that have conflicts. */ public Vector importGetConflictingFileNames(String moduleZip) throws CmsException { if (!hasAccess()) { throw new CmsException("No access to perform the action 'getConflictingFileNames'", CmsException.C_REGISTRY_ERROR); } CmsImport cmsImport = new CmsImport(moduleZip, "/", m_cms); return cmsImport.getConflictingFilenames(); } /** * Returns the name of the module to be imported. * * @param moduleZip the name of the zip-file to import from. * @return The name of the module to be imported. */ public String importGetModuleName(String moduleZip) { Element newModule = getModuleElementFromImport(moduleZip); return newModule.getElementsByTagName("name").item(0).getFirstChild().getNodeValue(); } /** * Returns all files that are needed to create a project for the module-import. * * @param moduleZip The name of the zip-file to import. * @returns The complete paths for resources that should be in the import-project. */ public Vector importGetResourcesForProject(String moduleZip) throws CmsException { if (!hasAccess()) { throw new CmsException("No access to perform the action 'importGetResourcesForProject'", CmsException.C_REGISTRY_ERROR); } CmsImport cmsImport = new CmsImport(moduleZip, "/", m_cms); return cmsImport.getResourcesForProject(); } /** * Imports a module. This method is synchronized, so only one module can be imported at on time. * * @param moduleZip the name of the zip-file to import from. * @param exclusion a Vector with resource-names that should be excluded from this import. */ public synchronized void importModule(String moduleZip, Vector exclusion) throws CmsException { // check if the user is allowed to import a module. if (!hasAccess()) { throw new CmsException("No access to perform the action 'importModule'", CmsException.C_REGISTRY_ERROR); } Element newModule = getModuleElementFromImport(moduleZip); String newModuleName = newModule.getElementsByTagName("name").item(0).getFirstChild().getNodeValue(); String newModuleVersion = newModule.getElementsByTagName("version").item(0).getFirstChild().getNodeValue(); // exists the module already? if (moduleExists(newModuleName)) { throw new CmsException("The module " + newModuleName + " exists already", CmsException.C_REGISTRY_ERROR); } Vector dependencies = checkDependencies(newModule); // are there any dependencies not fulfilled? if (dependencies.size() != 0) { throw new CmsException("the dependencies for the module are not fulfilled.", CmsException.C_REGISTRY_ERROR); } Vector resourceNames = new Vector(); Vector resourceCodes = new Vector(); CmsImport cmsImport = new CmsImport(moduleZip, "/", m_cms); cmsImport.importResources(exclusion, resourceNames, resourceCodes, "module", newModuleName + "_" + newModuleVersion); // import the module data into the registry Element regModules = (Element) (m_xmlReg.getElementsByTagName("modules").item(0)); // set the import-date Node uploadDate = newModule.getOwnerDocument().createElement("uploaddate"); uploadDate.appendChild(newModule.getOwnerDocument().createTextNode(m_dateFormat.format(new java.util.Date()))); newModule.appendChild(uploadDate); // set the import-user Node uploadBy = newModule.getOwnerDocument().createElement("uploadedby"); uploadBy.appendChild(newModule.getOwnerDocument().createTextNode(m_cms.getRequestContext().currentUser().getName())); newModule.appendChild(uploadBy); // set the files Node files = newModule.getOwnerDocument().createElement("files"); // store the resources-names that are depending to the module for (int i = 0; i < resourceNames.size(); i++) { Node file = newModule.getOwnerDocument().createElement("file"); files.appendChild(file); Node name = newModule.getOwnerDocument().createElement("name"); file.appendChild(name); Node checksum = newModule.getOwnerDocument().createElement("checksum"); file.appendChild(checksum); name.appendChild(newModule.getOwnerDocument().createTextNode((String) resourceNames.elementAt(i))); checksum.appendChild(newModule.getOwnerDocument().createTextNode(com.opencms.util.Encoder.escape( (String) resourceCodes.elementAt(i)))); } // append the files to the module-entry newModule.appendChild(files); // append the module data to the registry Node newNode = getXmlParser().importNode(m_xmlReg, newModule); regModules.appendChild(newNode); saveRegistry(); try { init(); } catch (Exception exc) { throw new CmsException("couldn't init registry", CmsException.C_REGISTRY_ERROR, exc); } // try to invoke the event-method for upload on this calss. Class eventClass = getModuleMaintenanceEventClass(newModuleName); try { Class declaration[] = {CmsObject.class}; Object arguments[] = {m_cms}; Method eventMethod = eventClass.getMethod(C_UPLOAD_EVENT_METHOD_NAME, declaration); eventMethod.invoke(null, arguments); } catch(Exception exc) { // ignore the exception. } } /** * Inits all member-variables for the instance. */ private void init() throws Exception { // get the entry-points for the modules NodeList modules = m_xmlReg.getElementsByTagName("module"); // create the hashtable for the shortcuts m_modules.clear(); // walk throug all modules for (int i = 0; i < modules.getLength(); i++) { Element module = (Element) modules.item(i); String moduleName = module.getElementsByTagName("name").item(0).getFirstChild().getNodeValue(); // store the shortcuts to the modules m_modules.put(moduleName, module); } } /** * Checks if the module exists already in the repository. * * @parameter String the name of the module. * @return true if the module exists, else false. */ public boolean moduleExists(String modulename) { return m_modules.containsKey(modulename); } /** * Saves the registry and stores it to the registry-file. */ private void saveRegistry() throws CmsException { try { // get the file File xmlFile = new File(m_regFileName); // get a buffered writer BufferedWriter xmlWriter = new BufferedWriter(new FileWriter(xmlFile)); // parse the registry-xmlfile and store it. A_CmsXmlContent.getXmlParser().getXmlText(m_xmlReg, xmlWriter); // reinit the modules-hashtable init(); } catch (Exception exc) { throw new CmsException("couldn't save registry", CmsException.C_REGISTRY_ERROR, exc); } } /** * This method sets the author of the module. * * @param String the name of the module. * @param String the name of the author. */ public void setModuleAuthor(String modulename, String author) throws CmsException { setModuleData(modulename, "author", author); } /** * This method sets the email of author of the module. * * @param String the name of the module. * @param String the email of author of the module. */ public void setModuleAuthorEmail(String modulename, String email) throws CmsException { setModuleData(modulename, "email", email); } /** * Sets the create date of the module. * * @param String the name of the module. * @param long the create date of the module. */ public void setModuleCreateDate(String modulname, long createdate) throws CmsException { setModuleData(modulname, "creationdate", m_dateFormat.format(new Date(createdate))); } /** * Sets the create date of the module. * * @param String the name of the module. * @param String the create date of the module. Format: mm.dd.yyyy */ public void setModuleCreateDate(String modulname, String createdate) throws CmsException { setModuleData(modulname, "creationdate", createdate); } /** * Private method to set module data like author. * * @param String modulename the name of the module. * @param String dataName the name of the tag to set the data for. * @param String the value to be set. */ private void setModuleData(String module, String dataName, String value) throws CmsException { if (!hasAccess()) { throw new CmsException("No access to perform the action 'setModuleData'", CmsException.C_REGISTRY_ERROR); } try { Element moduleElement = getModuleElement(module); Node tag = moduleElement.getElementsByTagName(dataName).item(0); setTagValue(tag, value); // save the registry saveRegistry(); } catch (Exception exc) { // ignore the exception - registry is not wellformed } } /** * Sets the module dependencies for the module. * * @param module String the name of the module to check. * @param modules Vector in this parameter the names of the dependend modules will be returned. * @param minVersions Vector in this parameter the minimum versions of the dependend modules will be returned. * @param maxVersions Vector in this parameter the maximum versions of the dependend modules will be returned. */ public void setModuleDependencies(String modulename, Vector modules, Vector minVersions, Vector maxVersions) throws CmsException { if (!hasAccess()) { throw new CmsException("No access to perform the action 'setModuleDependencies'", CmsException.C_REGISTRY_ERROR); } try { Element module = getModuleElement(modulename); Element dependencies = (Element) (module.getElementsByTagName("dependencies").item(0)); // delete all subnodes while(dependencies.hasChildNodes()) { dependencies.removeChild(dependencies.getFirstChild()); } // create the new dependencies for (int i = 0; i < modules.size(); i++) { Element dependency = m_xmlReg.createElement("dependency"); dependencies.appendChild(dependency); Element name = m_xmlReg.createElement("name"); Element min = m_xmlReg.createElement("minversion"); Element max = m_xmlReg.createElement("maxversion"); name.appendChild(m_xmlReg.createTextNode(modules.elementAt(i).toString())); min.appendChild(m_xmlReg.createTextNode(minVersions.elementAt(i).toString())); max.appendChild(m_xmlReg.createTextNode(maxVersions.elementAt(i).toString())); dependency.appendChild(name); dependency.appendChild(min); dependency.appendChild(max); } // save the registry saveRegistry(); } catch (Exception exc) { // ignore the exception - reg is not welformed } } /** * Sets the description of the module. * * @param String the name of the module. * @param String the description of the module. */ public void setModuleDescription(String module, String description) throws CmsException { setModuleData(module, "description", description); } /** * Sets the url to the documentation of the module. * * @param String the name of the module. * @param java.lang.String the url to the documentation of the module. */ public void setModuleDocumentPath(String modulename, String url) throws CmsException { setModuleData(modulename, "documentation", url); } /** * Sets the classname, that receives all maintenance-events for the module. * * @param String the name of the module. * @param String the name of the class that receives all maintenance-events for the module. */ public void setModuleMaintenanceEventClass(String modulname, String classname) throws CmsException { setModuleData(modulname, "maintenance_class", classname); } /** * Sets the description of the module. * * @param String the name of the module. * @param String the nice name of the module. */ public void setModuleNiceName(String module, String nicename) throws CmsException { setModuleData(module, "nicename", nicename); } /** * Sets a parameter for a module. * * @param modulename java.lang.String the name of the module. * @param parameter java.lang.String the name of the parameter to set. * @param the value to set for the parameter. */ public void setModuleParameter(String modulename, String parameter, byte value) throws CmsException { setModuleParameter(modulename, parameter, value + ""); } /** * Sets a parameter for a module. * * @param modulename java.lang.String the name of the module. * @param parameter java.lang.String the name of the parameter to set. * @param the value to set for the parameter. */ public void setModuleParameter(String modulename, String parameter, double value) throws CmsException { setModuleParameter(modulename, parameter, value + ""); } /** * Sets a parameter for a module. * * @param modulename java.lang.String the name of the module. * @param parameter java.lang.String the name of the parameter to set. * @param the value to set for the parameter. */ public void setModuleParameter(String modulename, String parameter, float value) throws CmsException { setModuleParameter(modulename, parameter, value + ""); } /** * Sets a parameter for a module. * * @param modulename java.lang.String the name of the module. * @param parameter java.lang.String the name of the parameter to set. * @param the value to set for the parameter. */ public void setModuleParameter(String modulename, String parameter, int value) throws CmsException { setModuleParameter(modulename, parameter, value + ""); } /** * Sets a parameter for a module. * * @param modulename java.lang.String the name of the module. * @param parameter java.lang.String the name of the parameter to set. * @param the value to set for the parameter. */ public void setModuleParameter(String modulename, String parameter, long value) throws CmsException { setModuleParameter(modulename, parameter, value + ""); } /** * Sets a parameter for a module. * * @param modulename java.lang.String the name of the module. * @param parameter java.lang.String the name of the parameter to set. * @param the value to set for the parameter. */ public void setModuleParameter(String modulename, String parameter, Boolean value) throws CmsException { setModuleParameter(modulename, parameter, value.toString()); } /** * Sets a parameter for a module. * * @param modulename java.lang.String the name of the module. * @param parameter java.lang.String the name of the parameter to set. * @param the value to set for the parameter. */ public void setModuleParameter(String modulename, String parameter, Byte value) throws CmsException { setModuleParameter(modulename, parameter, value.toString()); } /** * Sets a parameter for a module. * * @param modulename java.lang.String the name of the module. * @param parameter java.lang.String the name of the parameter to set. * @param the value to set for the parameter. */ public void setModuleParameter(String modulename, String parameter, Double value) throws CmsException { setModuleParameter(modulename, parameter, value.toString()); } /** * Sets a parameter for a module. * * @param modulename java.lang.String the name of the module. * @param parameter java.lang.String the name of the parameter to set. * @param the value to set for the parameter. */ public void setModuleParameter(String modulename, String parameter, Float value) throws CmsException { setModuleParameter(modulename, parameter, value.toString()); } /** * Sets a parameter for a module. * * @param modulename java.lang.String the name of the module. * @param parameter java.lang.String the name of the parameter to set. * @param the value to set for the parameter. */ public void setModuleParameter(String modulename, String parameter, Integer value) throws CmsException { setModuleParameter(modulename, parameter, value.toString()); } /** * Sets a parameter for a module. * * @param modulename java.lang.String the name of the module. * @param parameter java.lang.String the name of the parameter to set. * @param the value to set for the parameter. */ public void setModuleParameter(String modulename, String parameter, Long value) throws CmsException { setModuleParameter(modulename, parameter, value.toString()); } /** * Sets a parameter for a module. * * @param modulename java.lang.String the name of the module. * @param parameter java.lang.String the name of the parameter to set. * @param value java.lang.String the value to set for the parameter. */ public void setModuleParameter(String modulename, String parameter, String value) throws CmsException { // check if the user is allowed to set parameters if (!hasAccess()) { throw new CmsException("No access to perform the action 'setModuleParameter'", CmsException.C_REGISTRY_ERROR); } try { Element param = getModuleParameterElement(modulename, parameter); if (!checkType(getModuleParameterType(modulename, parameter), value)) { throw new CmsException("wrong number format for " + parameter + " -> " + value, CmsException.C_REGISTRY_ERROR); } param.getElementsByTagName("value").item(0).getFirstChild().setNodeValue(value); saveRegistry(); // try to invoke the event-method for setting parameters on this class. Class eventClass = getModuleMaintenanceEventClass(modulename); try { Class declaration[] = {CmsObject.class}; Object arguments[] = {m_cms}; Method eventMethod = eventClass.getMethod(C_UPDATE_PARAMETER_EVENT_METHOD_NAME, declaration); eventMethod.invoke(null, arguments); } catch(Exception exc) { // ignore the exception. } } catch (CmsException exc) { throw exc; } catch (Exception exc) { throw new CmsException("couldn't set parameter " + parameter + " for module " + modulename + " to vale " + value, CmsException.C_REGISTRY_ERROR, exc); } } /** * Sets a parameter for a module. * * @param modulename java.lang.String the name of the module. * @param parameter java.lang.String the name of the parameter to set. * @param the value to set for the parameter. */ public void setModuleParameter(String modulename, String parameter, boolean value) throws CmsException { setModuleParameter(modulename, parameter, value + ""); } /** * Sets the module dependencies for the module. * * @param module String the name of the module to check. * @param names Vector with parameternames * @param descriptions Vector with parameterdescriptions * @param types Vector with parametertypes (string, float,...) * @param values Vector with defaultvalues for parameters */ public void setModuleParameterdef(String modulename, Vector names, Vector descriptions, Vector types, Vector values) throws CmsException { if (!hasAccess()) { throw new CmsException("No access to perform the action 'setModuleParameterdef'", CmsException.C_REGISTRY_ERROR); } try { Element module = getModuleElement(modulename); Element params = (Element) (module.getElementsByTagName("parameters").item(0)); // delete all subnodes while (params.hasChildNodes()) { params.removeChild(params.getFirstChild()); } // create the new parameters for (int i = 0; i < names.size(); i++) { Element para = m_xmlReg.createElement("para"); params.appendChild(para); Element name = m_xmlReg.createElement("name"); Element desc = m_xmlReg.createElement("description"); Element type = m_xmlReg.createElement("type"); Element value = m_xmlReg.createElement("value"); name.appendChild(m_xmlReg.createTextNode(names.elementAt(i).toString())); desc.appendChild(m_xmlReg.createTextNode(descriptions.elementAt(i).toString())); type.appendChild(m_xmlReg.createTextNode(types.elementAt(i).toString())); value.appendChild(m_xmlReg.createTextNode(values.elementAt(i).toString())); para.appendChild(name); para.appendChild(desc); para.appendChild(type); para.appendChild(value); } // save the registry saveRegistry(); // try to invoke the event-method for setting parameters on this class. Class eventClass = getModuleMaintenanceEventClass(modulename); try { Class declaration[] = {CmsObject.class}; Object arguments[] = {m_cms}; Method eventMethod = eventClass.getMethod(C_UPDATE_PARAMETER_EVENT_METHOD_NAME, declaration); eventMethod.invoke(null, arguments); } catch(Exception exc) { // ignore the exception. } } catch (Exception exc) { // ignore the exception - reg is not welformed } } /** * Sets all repositories for a module. * * @param String modulname the name of the module. * @param String[] the reprositories of a module. */ public void setModuleRepositories(String modulename, String[] repositories) throws CmsException { String[] retValue = null; if (!hasAccess()) { throw new CmsException("No access to perform the action 'setModuleRepositories'", CmsException.C_REGISTRY_ERROR); } try { Element module = getModuleElement(modulename); Element repository = (Element) (module.getElementsByTagName("repository").item(0)); // delete all subnodes while(repository .hasChildNodes()) { repository .removeChild(repository .getFirstChild()); } // create the new repository for(int i = 0; i < repositories.length; i++) { Element path = m_xmlReg.createElement("path"); path.appendChild(m_xmlReg.createTextNode(repositories[i])); repository .appendChild(path); } // save the registry saveRegistry(); } catch (Exception exc) { // ignore the exception - reg is not welformed } } /** * This method sets the version of the module. * * @param String the name of the module. * @param int the version of the module. */ public void setModuleVersion(String modulename, int version) throws CmsException { setModuleData(modulename, "version", version + ""); } /** * Sets a view for a module * * @param String the name of the module. * @param String the name of the view, that is implemented by the module. * @param String the url of the view, that is implemented by the module. */ public void setModuleView(String modulename, String viewname, String viewurl) throws CmsException { if (!hasAccess()) { throw new CmsException("No access to perform the action 'setModuleView'", CmsException.C_REGISTRY_ERROR); } try { Element module = getModuleElement(modulename); Element view = (Element) (module.getElementsByTagName("view").item(0)); if (!view.hasChildNodes()) { view.appendChild(m_xmlReg.createElement("name")); view.appendChild(m_xmlReg.createElement("url")); } setTagValue(view.getElementsByTagName("name").item(0), viewname); setTagValue(view.getElementsByTagName("url").item(0), viewurl); saveRegistry(); } catch (Exception exc) { // ignore the exception - reg is not welformed } } /** * Public method to set system values. * * @param String dataName the name of the tag to set the data for. * @param String the value to be set. */ public void setSystemValue(String dataName, String value) throws CmsException { if (!hasAccess()) { throw new CmsException("No access to perform the action 'setSystemValue'", CmsException.C_REGISTRY_ERROR); } try { Element systemElement = (Element)m_xmlReg.getElementsByTagName("system").item(0); // remove the old tag if it exists and create a new one try{ Node oldTag = systemElement.getElementsByTagName(dataName).item(0); oldTag.getParentNode().removeChild(oldTag); } catch (Exception exc){ } Element newTag = m_xmlReg.createElement(dataName); systemElement.appendChild(newTag); Node tag = systemElement.getElementsByTagName(dataName).item(0); setTagValue(tag, value); // save the registry saveRegistry(); } catch (Exception exc) { // ignore the exception - registry is not wellformed } } /** * Public method to set system values with hashtable. * * @param String dataName the name of the tag to set the data for. * @param Hashtable the value to be set. */ public void setSystemValues(String dataName, Hashtable values) throws CmsException { if (!hasAccess()) { throw new CmsException("No access to perform the action 'setSystemValues'", CmsException.C_REGISTRY_ERROR); } try { Element systemElement = (Element)m_xmlReg.getElementsByTagName("system").item(0); // remove the old tag if it exists and create a new one try{ Node oldTag = systemElement.getElementsByTagName(dataName).item(0); oldTag.getParentNode().removeChild(oldTag); } catch (Exception exc){ } Element newTag = m_xmlReg.createElement(dataName); systemElement.appendChild(newTag); Node parentTag = systemElement.getElementsByTagName(dataName).item(0); Enumeration keys = values.keys(); while(keys.hasMoreElements()){ String key = (String) keys.nextElement(); String value = (String) values.get(key); Element keyTag = m_xmlReg.createElement(key); parentTag.appendChild(keyTag); keyTag.appendChild(m_xmlReg.createTextNode(value)); } // save the registry saveRegistry(); } catch (Exception exc) { // ignore the exception - registry is not wellformed } } /** * Creates or replaces a textvalue for a parent node. * @param Node to set the textvalue. * @param String the value to be set. */ private void setTagValue(Node node, String value) { if (node.hasChildNodes()) { node.getFirstChild().setNodeValue(value); } else { node.appendChild(m_xmlReg.createTextNode(value)); } } }
package com.shade.lighting; import java.util.Arrays; import java.util.LinkedList; import org.lwjgl.opengl.GL11; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.state.StateBasedGame; import com.shade.controls.DayPhaseTimer; import com.shade.entities.Roles; /** * A view which renders a set of entities, lights, and background images in such * a way as to generate dynamic lighting. * * It's safe to draw things to the screen after calling LightMask.render if you * want them to appear above the gameplay, for instance user controls. * * <em>Note that calling render will update your entities' luminosity. Please * direct any hate mail to JJ Jou.</em> * * @author JJ Jou <j.j@duke.edu> * @author Alexander Schearer <aschearer@gmail.com> */ public class LightMask { /* Set to remove white borders from player, mushrooms, etc. */ private static final float MAGIC_ALPHA_VALUE = .65f; protected final static Color SHADE = new Color(0, 0, 0, .3f); public static final float MAX_DARKNESS = 0.4f; private DayPhaseTimer timer; private int threshold; private LinkedList<LightSource> lights; public LightMask(int threshold, DayPhaseTimer time) { this.threshold = threshold; lights = new LinkedList<LightSource>(); timer = time; } public void add(LightSource light) { lights.add(light); } public void render(StateBasedGame game, Graphics g, LuminousEntity[] entities, Image... backgrounds) { renderLights(game, g, entities); renderBackgrounds(game, g, backgrounds); renderEntities(game, g, entities); //RENDER NIGHT! WHEEE renderTimeOfDay(game, g); } public void renderTimeOfDay(StateBasedGame game, Graphics g){ Color c = g.getColor(); if(timer.getDaylightStatus()==DayPhaseTimer.DayLightStatus.DUSK){ g.setColor(new Color(1-timer.timeLeft(),1-timer.timeLeft(),0f,MAX_DARKNESS*timer.timeLeft())); g.fillRect(0, 0, game.getContainer().getWidth(), game.getContainer().getHeight()); } else if(timer.getDaylightStatus()==DayPhaseTimer.DayLightStatus.NIGHT){ g.setColor(new Color(0,0,0,MAX_DARKNESS)); g.fillRect(0, 0, game.getContainer().getWidth(), game.getContainer().getHeight()); } else if(timer.getDaylightStatus()==DayPhaseTimer.DayLightStatus.DAWN){ g.setColor(new Color(timer.timeLeft(),timer.timeLeft(),0,MAX_DARKNESS*(1-timer.timeLeft()))); g.fillRect(0, 0, game.getContainer().getWidth(), game.getContainer().getHeight()); } g.setColor(c); } private void renderLights(StateBasedGame game, Graphics g, LuminousEntity... entities) { enableStencil(); for (LightSource light : lights) { light.render(game, g, entities); } disableStencil(); GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE); g.setColor(SHADE); GameContainer c = game.getContainer(); g.fillRect(0, 0, c.getWidth(), c.getHeight()); g.setColor(Color.white); } private void renderBackgrounds(StateBasedGame game, Graphics g, Image... backgrounds) { GL11.glBlendFunc(GL11.GL_DST_ALPHA, GL11.GL_ONE); for (Image background : backgrounds) { background.draw(); } } private void renderEntities(StateBasedGame game, Graphics g, LuminousEntity... entities) { Arrays.sort(entities); int i = 0; GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glBlendFunc(GL11.GL_DST_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); while (i < entities.length && entities[i].getZIndex() < threshold) { if (entityException(entities[i])) { GL11.glAlphaFunc(GL11.GL_GREATER, GL11.GL_ZERO); } else { GL11.glAlphaFunc(GL11.GL_GREATER, MAGIC_ALPHA_VALUE); } entities[i].render(game, g); entities[i].setLuminosity(getLuminosityFor(entities[i], g)); i++; } GL11.glAlphaFunc(GL11.GL_GREATER, GL11.GL_ZERO); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); while (i < entities.length) { entities[i].render(game, g); entities[i].setLuminosity(getLuminosityFor(entities[i], g)); i++; } GL11.glDisable(GL11.GL_ALPHA_TEST); } private boolean entityException(LuminousEntity e) { return (e.getRole() == Roles.DUMMY.ordinal()); } private float getLuminosityFor(LuminousEntity entity, Graphics g) { return g.getPixel((int) entity.getXCenter(), (int) entity.getYCenter()).a; } /** * Called before drawing the shadows cast by a light. */ protected static void enableStencil() { // write only to the stencil buffer GL11.glEnable(GL11.GL_STENCIL_TEST); GL11.glColorMask(false, false, false, false); GL11.glDepthMask(false); } protected static void resetStencil(){ GL11.glClearStencil(0); // write a one to the stencil buffer everywhere we are about to draw GL11.glStencilFunc(GL11.GL_ALWAYS, 1, 1); // this is to always pass a one to the stencil buffer where we draw GL11.glStencilOp(GL11.GL_REPLACE, GL11.GL_REPLACE, GL11.GL_REPLACE); } /** * Called after drawing the shadows cast by a light. */ protected static void keepStencil() { // resume drawing to everything GL11.glDepthMask(true); GL11.glColorMask(true, true, true, true); GL11.glStencilFunc(GL11.GL_NOTEQUAL, 1, 1); // don't modify the contents of the stencil buffer GL11.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_KEEP); GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE); } protected static void disableStencil(){ GL11.glDisable(GL11.GL_STENCIL_TEST); GL11.glClear(GL11.GL_STENCIL_BUFFER_BIT); } }
package com.shade.states; import java.awt.Font; import java.io.InputStream; import java.util.LinkedList; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.TrueTypeFont; import org.newdawn.slick.geom.Vector2f; import org.newdawn.slick.state.*; import org.newdawn.slick.util.ResourceLoader; import com.shade.base.Entity; import com.shade.controls.*; import com.shade.crash.*; import com.shade.entities.*; import com.shade.entities.util.MushroomFactory; import com.shade.shadows.*; import com.shade.shadows.ShadowEntity.ShadowIntensity; public class InGameState extends BasicGameState { public static final int ID = 1; private static final float SUN_START_ANGLE = 2.5f; private static final float SUN_START_DEPTH = 10f; private static final float SUN_ANGLE_INCREMENT = 0.001f; private enum Status { NOT_STARTED, RUNNING, PAUSED, GAME_OVER }; private Status currentStatus; private ShadowLevel level; private MeterControl meter; private CounterControl counter; private Image backgroundSprite, trimSprite; private Image counterSprite; private TrueTypeFont counterFont; private Player player; private int timer, totalTimer; private int numMoles; @Override public int getID() { return ID; } public void init(GameContainer container, StateBasedGame game) throws SlickException { level = new ShadowLevel(new Grid(8, 6, 200), SUN_START_ANGLE, SUN_START_DEPTH, SUN_ANGLE_INCREMENT); currentStatus = Status.NOT_STARTED; initSprites(); initFonts(); } private void initFonts() throws SlickException { try { InputStream oi = ResourceLoader .getResourceAsStream("states/ingame/jekyll.ttf"); Font jekyll = Font.createFont(Font.TRUETYPE_FONT, oi); counterFont = new TrueTypeFont(jekyll.deriveFont(36f), true); } catch (Exception e) { throw new SlickException("Failed to load font.", e); } } private void initSprites() throws SlickException { backgroundSprite = new Image("states/ingame/background.png"); trimSprite = new Image("states/ingame/trim.png"); counterSprite = new Image("states/ingame/counter.png"); } @Override public void enter(GameContainer container, StateBasedGame game) throws SlickException { currentStatus = Status.RUNNING; totalTimer = 0; timer = 0; level.clear(); meter = new MeterControl(20, 456, 100, 100); counter = new CounterControl(60, 520, counterSprite, counterFont); numMoles = 0; initObstacles(); initBasket(); initPlayer(); level.add(new Monster(500, 300)); } private void initShrooms(GameContainer container) throws SlickException { for (int i = 0; i < 5; i++) { Vector2f p = level.randomPoint(container); level.add(MushroomFactory.makeMushroom(p.x, p.y)); } } private void initObstacles() throws SlickException { LinkedList<ShadowCaster> casters = new LinkedList<ShadowCaster>(); casters.add(new Block(55, 355, 125, 125, 16)); casters.add(new Block(224, 424, 56, 56, 6)); casters.add(new Block(324, 424, 56, 56, 6)); casters.add(new Block(75, 225, 56, 56, 6)); casters.add(new Block(545, 330, 80, 80, 10)); casters.add(new Block(445, 460, 80, 80, 10)); // domes casters.add(new Dome(288, 165, 32, 7)); casters.add(new Dome(180, 95, 44, 10)); casters.add(new Dome(300, 65, 25, 6)); casters.add(new Dome(710, 80, 28, 6)); casters.add(new Dome(600, 100, 40, 9)); casters.add(new Dome(680, 220, 60, 13)); // fences casters.add(new Fence(225, 225, 11, 120, 5)); casters.add(new Fence(390, 140, 120, 11, 5)); casters.add(new Fence(715, 368, 11, 120, 5)); casters.add(new Fence(50, 50, 11, 120, 5)); // shrubs // casters.add(new Shrub(300, 300)); // gargoyles // casters.add(new Monster(500, 300)); // Gargoyle g1 = new Gargoyle(500,300); // Gargoyle g2 = new Gargoyle(500,200); // Gargoyle g3 = new Gargoyle(500,400); // casters.add(g1); // casters.add(g2); // casters.add(g3); // level.add((Entity)g1); // level.add((Entity)g2); // level.add((Entity)g3); for (ShadowCaster c : casters) { level.add(c); } } private void initBasket() throws SlickException { Basket b = new Basket(400, 250, 65, 40); b.add(counter); b.add(meter); level.add(b); } private void initPlayer() throws SlickException { player = new Player(400, 350); level.add(player); } public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException { backgroundSprite.draw(); level.render(game, g); trimSprite.draw(); meter.render(game, g); counter.render(game, g); if (currentStatus == Status.GAME_OVER) { counterFont.drawString(320, 300, "Game Over"); } } public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { if (currentStatus == Status.RUNNING) { level.update(game, delta); timer += delta; totalTimer += delta; // first run if (totalTimer == delta) { initShrooms(container); } // Randomly plant mushrooms if (Math.random() > .9965 || timer % 5000 + delta > 5000) { Vector2f p = level.randomPoint(container); level.add(MushroomFactory.makeMushroom(p.x, p.y)); } if (counter.value >= 5 && numMoles < 1) { level.add(new Mole(4000)); numMoles++; } if (counter.value > 25 && numMoles < 2) { level.add(new Mole(5000)); numMoles++; } if (counter.value > 50 && numMoles < 3) { level.add(new Mole(6000)); numMoles++; } meter.update(game, delta); counter.update(game, delta); if (player.hasIntensity(ShadowIntensity.UNSHADOWED)) { meter.decrement(0.1); } if (player.isStunned()) { meter.decrement(0.5); } // Check for lose condition if (meter.isEmpty()) { currentStatus = Status.GAME_OVER; } } // check whether to restart if (container.getInput().isKeyPressed(Input.KEY_R)) { enter(container, game); } } }
package com.shade.states; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; import org.newdawn.slick.state.transition.FadeOutTransition; import org.newdawn.slick.state.transition.Transition; import com.shade.controls.Button; import com.shade.controls.ClickListener; import com.shade.controls.ControlListener; import com.shade.controls.CounterControl; import com.shade.controls.MeterControl; import com.shade.controls.ScoreControl; import com.shade.controls.SlickButton; import com.shade.controls.DayPhaseTimer.DayLightStatus; import com.shade.levels.LevelManager; import com.shade.resource.ResourceManager; public class InGameState extends BasicGameState { public static final int ID = 3; private LevelManager manager; private MasterState master; private ResourceManager resource; private CounterControl counter; private MeterControl meter; private int timer; private boolean transitioning; private Transition transition; private StateBasedGame game; private SlickButton play, back; public InGameState(MasterState m) throws SlickException { manager = new LevelManager(8, 6, 100); master = m; resource = m.resource; resource.register("counter", "states/ingame/counter.png"); resource.register("resume-up", "states/ingame/resume-up.png"); resource.register("resume-down", "states/ingame/resume-down.png"); resource.register("back-up", "states/common/back-up.png"); resource.register("back-down", "states/common/back-down.png"); transition = new FadeOutTransition(); initControls(); initButtons(); } @Override public int getID() { return ID; } public void init(GameContainer container, StateBasedGame game) throws SlickException { throw new RuntimeException("InGameState was init'd!"); } @Override public void enter(GameContainer container, StateBasedGame game) throws SlickException { this.game = game; counter.reset(); meter.reset(); master.scorecard.reset(); master.timer.reset(); manager.rewind(); master.control.add(counter); master.control.add(meter); master.control.load(manager.next()); timer = 0; transitioning = false; master.dimmer.rewind(); } // render the gameplay public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException { master.control.render(game, g, resource.get("background")); master.scorecard.render(game, g); if (transitioning) { transition.postRender(game, container, g); } master.dimmer.render(game, g); if (container.isPaused()) { resource.get("header").draw(400, 0); play.render(game, g); back.render(game, g); drawCentered(container, "Paused (p)"); } resource.get("trim").draw(); } // render the gameplay public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { if (container.isPaused()) { master.dimmer.update(game, 25); play.update(game, 25); back.update(game, 25); return; } if (master.dimmer.reversed()) { master.dimmer.update(game, delta); } master.control.update(game, delta); master.scorecard.update(game, delta); if (container.getInput().isKeyPressed(Input.KEY_ESCAPE)) { manager.rewind(); exit(game, TitleState.ID); } // if (container.getInput().isKeyPressed(Input.KEY_R)) { // manager.rewind(); // loadNextLevel(game); timer += delta; if (master.timer.getDaylightStatus() == DayLightStatus.NIGHT) { transitioning = true; } if (transitioning) { transition.update(game, container, delta); if (transition.isComplete()) { transitioning = false; timer = 0; meter.awardBonus(); master.timer.reset(); master.dimmer.fastforward(); loadNextLevel(game); } } } @Override public void keyPressed(int key, char c) { if (key == Input.KEY_P) { if (game.getContainer().isPaused()) { game.getContainer().resume(); master.music.resume(); master.dimmer.reverse(); } else { game.getContainer().pause(); master.music.pause(); master.dimmer.reset(); } } } private void drawCentered(GameContainer c, String s) { int x = (c.getWidth() - master.daisyLarge.getWidth(s)) / 2; int y = (c.getHeight() - master.daisyLarge.getHeight()) / 2; master.daisyLarge.drawString(x, y, s); } private void exit(StateBasedGame game, int state) { master.control.flushControls(); master.control.killPlayer(); game.enterState(state); } private void loadNextLevel(StateBasedGame game) { if (manager.hasNext()) { master.control.load(manager.next()); } else { exit(game, EnterScoreState.ID); } } private void initControls() throws SlickException { meter = new MeterControl(20, 480); meter.register(new ControlListener() { public void fire() { // The player lost exit(game, EnterScoreState.ID); } }); Image c = resource.get("counter"); counter = new CounterControl(140, 520, c, master.jekyllLarge); master.scorecard = new ScoreControl(10, 10, master.jekyllLarge); meter.pass(master.scorecard); counter.register(master.scorecard); } private void initButtons() throws SlickException { initPlayButton(); initBackButton(); } private void initPlayButton() throws SlickException { play = new SlickButton(620, 110, resource.get("resume-up"), resource .get("resume-down")); play.addListener(new ClickListener() { public void onClick(StateBasedGame game, Button clicked) { game.getContainer().resume(); master.dimmer.reverse(); } }); } private void initBackButton() throws SlickException { back = new SlickButton(620, 130, resource.get("back-up"), resource .get("back-down")); back.addListener(new ClickListener() { public void onClick(StateBasedGame game, Button clicked) { game.getContainer().resume(); master.music.resume(); master.dimmer.reverse(); manager.rewind(); exit(game, TitleState.ID); } }); } }
package com.stickycoding.rokon; import javax.microedition.khronos.opengles.GL10; /** * Layer.java * A Layer is contained inside a Scene, and are drawn in ascending order * Each Layer has a many DrawableObjects and one DrawQueue * @author Richard * */ public class Layer { protected Scene parentScene; protected FixedSizeArray<DrawableObject> drawableObjects; protected int maximumDrawableObjects; protected DrawQueue drawQueue; public Layer(Scene parentScene, int maximumDrawableObjects) { this.parentScene = parentScene; this.maximumDrawableObjects = maximumDrawableObjects; drawQueue = new DrawQueue(); drawableObjects = new FixedSizeArray<DrawableObject>(maximumDrawableObjects); } /** * Returns a DrawableObject from this layer * * @param index position in the array * @return NULL if not found */ public DrawableObject getDrawableObject(int index) { return drawableObjects.get(index); } /** * @return the current DrawQueue object for this Scene */ public DrawQueue getDrawQueue() { return drawQueue; } /** * Sets the DrawQueue method * Defaults to DrawQueue.FASTEST if unset * @param type Taken from the constants in DrawQueue */ public void setDrawQueueType(int type) { if(type < 0 || type > 4) { Debug.warning("Scene.setDrawQueueType", "Tried setting DrawQueue type to " + type + ", defaulting to 0"); drawQueue.method = DrawQueue.FASTEST; return; } drawQueue.method = type; } /** * Clears all the DrawableObjects off this Layer */ public void clear() { drawableObjects.clear(); } /** * Adds a DrawableObject to this Layer * * @param drawableObject a valid DrawableObject */ public void add(DrawableObject drawableObject) { if(drawableObject == null) { Debug.warning("Layer.add", "Tried adding an invalid DrawableObject"); return; } if(drawableObjects.getCount() == drawableObjects.getCapacity()) { Debug.warning("Layer.add", "Tried adding to a Layer which is full, maximum=" + maximumDrawableObjects); return; } drawableObjects.add(drawableObject); drawableObject.onAdd(this); } protected void onDraw(GL10 gl) { for(int i = 0; i < drawableObjects.getCapacity(); i++) { if(drawableObjects.get(i) != null) { while(drawableObjects.get(i).killNextUpdate) { if(drawableObjects.get(i).body != null) { parentScene.world.destroyBody(drawableObjects.get(i).body); drawableObjects.get(i).body = null; } drawableObjects.remove(i); } drawableObjects.get(i).onUpdate(); if(drawableObjects.get(i).isOnScreen()) { drawableObjects.get(i).onDraw(gl); } } } } }
package test; public class Test { public static void main(String[] args) { System.out.println("hello git"); System.out.println(""); } }